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
23 * who actually finally proved there really was a race.
25 * 2002/03/18 Implemented n_tty_wakeup to send SIGIO POLL_OUTs to
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
60 * This defines the low- and high-watermarks for throttling and
61 * unthrottling the TTY driver. These watermarks are used for
62 * controlling the space in the read buffer.
64 #define TTY_THRESHOLD_THROTTLE 128 /* now based on remaining room */
65 #define TTY_THRESHOLD_UNTHROTTLE 128
68 * Special byte codes used in the echo buffer to represent operations
69 * or special handling of characters. Bytes in the echo buffer that
70 * are not part of such special blocks are treated as normal character
73 #define ECHO_OP_START 0xff
74 #define ECHO_OP_MOVE_BACK_COL 0x80
75 #define ECHO_OP_SET_CANON_COL 0x81
76 #define ECHO_OP_ERASE_TAB 0x82
78 #define ECHO_COMMIT_WATERMARK 256
79 #define ECHO_BLOCK 256
80 #define ECHO_DISCARD_WATERMARK N_TTY_BUF_SIZE - (ECHO_BLOCK + 32)
85 # define n_tty_trace(f, args...) trace_printk(f, ##args)
87 # define n_tty_trace(f, args...) no_printk(f, ##args)
91 /* producer-published */
98 DECLARE_BITMAP(char_map, 256);
100 /* private to n_tty_receive_overrun (single-threaded) */
101 unsigned long overrun_time;
107 /* must hold exclusive termios_rwsem to reset these */
108 unsigned char lnext:1, erasing:1, raw:1, real_raw:1, icanon:1;
109 unsigned char push:1;
111 /* shared by producer and consumer */
112 char read_buf[N_TTY_BUF_SIZE];
113 DECLARE_BITMAP(read_flags, N_TTY_BUF_SIZE);
114 unsigned char echo_buf[N_TTY_BUF_SIZE];
116 /* consumer-published */
120 /* # of chars looked ahead (to find software flow control chars) */
121 size_t lookahead_count;
123 /* protected by output lock */
125 unsigned int canon_column;
128 struct mutex atomic_read_lock;
129 struct mutex output_lock;
132 #define MASK(x) ((x) & (N_TTY_BUF_SIZE - 1))
134 static inline size_t read_cnt(struct n_tty_data *ldata)
136 return ldata->read_head - ldata->read_tail;
139 static inline unsigned char read_buf(struct n_tty_data *ldata, size_t i)
141 return ldata->read_buf[i & (N_TTY_BUF_SIZE - 1)];
144 static inline unsigned char *read_buf_addr(struct n_tty_data *ldata, size_t i)
146 return &ldata->read_buf[i & (N_TTY_BUF_SIZE - 1)];
149 static inline unsigned char echo_buf(struct n_tty_data *ldata, size_t i)
151 smp_rmb(); /* Matches smp_wmb() in add_echo_byte(). */
152 return ldata->echo_buf[i & (N_TTY_BUF_SIZE - 1)];
155 static inline unsigned char *echo_buf_addr(struct n_tty_data *ldata, size_t i)
157 return &ldata->echo_buf[i & (N_TTY_BUF_SIZE - 1)];
160 /* If we are not echoing the data, perhaps this is a secret so erase it */
161 static void zero_buffer(struct tty_struct *tty, u8 *buffer, int size)
163 bool icanon = !!L_ICANON(tty);
164 bool no_echo = !L_ECHO(tty);
166 if (icanon && no_echo)
167 memset(buffer, 0x00, size);
170 static void tty_copy(struct tty_struct *tty, void *to, size_t tail, size_t n)
172 struct n_tty_data *ldata = tty->disc_data;
173 size_t size = N_TTY_BUF_SIZE - tail;
174 void *from = read_buf_addr(ldata, tail);
177 tty_audit_add_data(tty, from, size);
178 memcpy(to, from, size);
179 zero_buffer(tty, from, size);
182 from = ldata->read_buf;
185 tty_audit_add_data(tty, from, n);
187 zero_buffer(tty, from, n);
191 * n_tty_kick_worker - start input worker (if required)
194 * Re-schedules the flip buffer work if it may have stopped.
197 * * Caller holds exclusive %termios_rwsem, or
198 * * n_tty_read()/consumer path:
199 * holds non-exclusive %termios_rwsem
201 static void n_tty_kick_worker(struct tty_struct *tty)
203 struct n_tty_data *ldata = tty->disc_data;
205 /* Did the input worker stop? Restart it */
206 if (unlikely(READ_ONCE(ldata->no_room))) {
207 WRITE_ONCE(ldata->no_room, 0);
209 WARN_RATELIMIT(tty->port->itty == NULL,
210 "scheduling with invalid itty\n");
211 /* see if ldisc has been killed - if so, this means that
212 * even though the ldisc has been halted and ->buf.work
213 * cancelled, ->buf.work is about to be rescheduled
215 WARN_RATELIMIT(test_bit(TTY_LDISC_HALTED, &tty->flags),
216 "scheduling buffer work for halted ldisc\n");
217 tty_buffer_restart_work(tty->port);
221 static ssize_t chars_in_buffer(struct tty_struct *tty)
223 struct n_tty_data *ldata = tty->disc_data;
227 n = ldata->commit_head - ldata->read_tail;
229 n = ldata->canon_head - ldata->read_tail;
234 * n_tty_write_wakeup - asynchronous I/O notifier
237 * Required for the ptys, serial driver etc. since processes that attach
238 * themselves to the master and rely on ASYNC IO must be woken up.
240 static void n_tty_write_wakeup(struct tty_struct *tty)
242 clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
243 kill_fasync(&tty->fasync, SIGIO, POLL_OUT);
246 static void n_tty_check_throttle(struct tty_struct *tty)
248 struct n_tty_data *ldata = tty->disc_data;
251 * Check the remaining room for the input canonicalization
252 * mode. We don't want to throttle the driver if we're in
253 * canonical mode and don't have a newline yet!
255 if (ldata->icanon && ldata->canon_head == ldata->read_tail)
260 tty_set_flow_change(tty, TTY_THROTTLE_SAFE);
261 if (N_TTY_BUF_SIZE - read_cnt(ldata) >= TTY_THRESHOLD_THROTTLE)
263 throttled = tty_throttle_safe(tty);
267 __tty_set_flow_change(tty, 0);
270 static void n_tty_check_unthrottle(struct tty_struct *tty)
272 if (tty->driver->type == TTY_DRIVER_TYPE_PTY) {
273 if (chars_in_buffer(tty) > TTY_THRESHOLD_UNTHROTTLE)
275 n_tty_kick_worker(tty);
276 tty_wakeup(tty->link);
280 /* If there is enough space in the read buffer now, let the
281 * low-level driver know. We use chars_in_buffer() to
282 * check the buffer, as it now knows about canonical mode.
283 * Otherwise, if the driver is throttled and the line is
284 * longer than TTY_THRESHOLD_UNTHROTTLE in canonical mode,
285 * we won't get any more characters.
290 tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE);
291 if (chars_in_buffer(tty) > TTY_THRESHOLD_UNTHROTTLE)
293 n_tty_kick_worker(tty);
294 unthrottled = tty_unthrottle_safe(tty);
298 __tty_set_flow_change(tty, 0);
302 * put_tty_queue - add character to tty
306 * Add a character to the tty read_buf queue.
309 * * n_tty_receive_buf()/producer path:
310 * caller holds non-exclusive %termios_rwsem
312 static inline void put_tty_queue(unsigned char c, struct n_tty_data *ldata)
314 *read_buf_addr(ldata, ldata->read_head) = c;
319 * reset_buffer_flags - reset buffer state
320 * @ldata: line disc data to reset
322 * Reset the read buffer counters and clear the flags. Called from
323 * n_tty_open() and n_tty_flush_buffer().
326 * * caller holds exclusive %termios_rwsem, or
327 * * (locking is not required)
329 static void reset_buffer_flags(struct n_tty_data *ldata)
331 ldata->read_head = ldata->canon_head = ldata->read_tail = 0;
332 ldata->commit_head = 0;
333 ldata->line_start = 0;
336 bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
339 ldata->lookahead_count = 0;
342 static void n_tty_packet_mode_flush(struct tty_struct *tty)
346 if (tty->link->ctrl.packet) {
347 spin_lock_irqsave(&tty->ctrl.lock, flags);
348 tty->ctrl.pktstatus |= TIOCPKT_FLUSHREAD;
349 spin_unlock_irqrestore(&tty->ctrl.lock, flags);
350 wake_up_interruptible(&tty->link->read_wait);
355 * n_tty_flush_buffer - clean input queue
356 * @tty: terminal device
358 * Flush the input buffer. Called when the tty layer wants the buffer flushed
359 * (eg at hangup) or when the %N_TTY line discipline internally has to clean
360 * the pending queue (for example some signals).
362 * Holds %termios_rwsem to exclude producer/consumer while buffer indices are
365 * Locking: %ctrl.lock, exclusive %termios_rwsem
367 static void n_tty_flush_buffer(struct tty_struct *tty)
369 down_write(&tty->termios_rwsem);
370 reset_buffer_flags(tty->disc_data);
371 n_tty_kick_worker(tty);
374 n_tty_packet_mode_flush(tty);
375 up_write(&tty->termios_rwsem);
379 * is_utf8_continuation - utf8 multibyte check
382 * Returns: true if the utf8 character @c is a multibyte continuation
383 * character. We use this to correctly compute the on-screen size of the
384 * character when printing.
386 static inline int is_utf8_continuation(unsigned char c)
388 return (c & 0xc0) == 0x80;
392 * is_continuation - multibyte check
394 * @tty: terminal device
396 * Returns: true if the utf8 character @c is a multibyte continuation character
397 * and the terminal is in unicode mode.
399 static inline int is_continuation(unsigned char c, struct tty_struct *tty)
401 return I_IUTF8(tty) && is_utf8_continuation(c);
405 * do_output_char - output one character
406 * @c: character (or partial unicode symbol)
407 * @tty: terminal device
408 * @space: space available in tty driver write buffer
410 * This is a helper function that handles one output character (including
411 * special characters like TAB, CR, LF, etc.), doing OPOST processing and
412 * putting the results in the tty driver's write buffer.
414 * Note that Linux currently ignores TABDLY, CRDLY, VTDLY, FFDLY and NLDLY.
415 * They simply aren't relevant in the world today. If you ever need them, add
418 * Returns: the number of bytes of buffer space used or -1 if no space left.
420 * Locking: should be called under the %output_lock to protect the column state
421 * and space left in the buffer.
423 static int do_output_char(unsigned char c, struct tty_struct *tty, int space)
425 struct n_tty_data *ldata = tty->disc_data;
438 ldata->canon_column = ldata->column = 0;
439 tty->ops->write(tty, "\r\n", 2);
442 ldata->canon_column = ldata->column;
445 if (O_ONOCR(tty) && ldata->column == 0)
450 ldata->canon_column = ldata->column = 0;
453 ldata->canon_column = ldata->column = 0;
456 spaces = 8 - (ldata->column & 7);
457 if (O_TABDLY(tty) == XTABS) {
460 ldata->column += spaces;
461 tty->ops->write(tty, " ", spaces);
464 ldata->column += spaces;
467 if (ldata->column > 0)
474 if (!is_continuation(c, tty))
480 tty_put_char(tty, c);
485 * process_output - output post processor
486 * @c: character (or partial unicode symbol)
487 * @tty: terminal device
489 * Output one character with OPOST processing.
491 * Returns: -1 when the output device is full and the character must be
494 * Locking: %output_lock to protect column state and space left (also, this is
495 *called from n_tty_write() under the tty layer write lock).
497 static int process_output(unsigned char c, struct tty_struct *tty)
499 struct n_tty_data *ldata = tty->disc_data;
502 mutex_lock(&ldata->output_lock);
504 space = tty_write_room(tty);
505 retval = do_output_char(c, tty, space);
507 mutex_unlock(&ldata->output_lock);
515 * process_output_block - block post processor
516 * @tty: terminal device
517 * @buf: character buffer
518 * @nr: number of bytes to output
520 * Output a block of characters with OPOST processing.
522 * This path is used to speed up block console writes, among other things when
523 * processing blocks of output data. It handles only the simple cases normally
524 * found and helps to generate blocks of symbols for the console driver and
525 * thus improve performance.
527 * Returns: the number of characters output.
529 * Locking: %output_lock to protect column state and space left (also, this is
530 * called from n_tty_write() under the tty layer write lock).
532 static ssize_t process_output_block(struct tty_struct *tty,
533 const unsigned char *buf, unsigned int nr)
535 struct n_tty_data *ldata = tty->disc_data;
538 const unsigned char *cp;
540 mutex_lock(&ldata->output_lock);
542 space = tty_write_room(tty);
544 mutex_unlock(&ldata->output_lock);
550 for (i = 0, cp = buf; i < nr; i++, cp++) {
551 unsigned char c = *cp;
559 ldata->canon_column = ldata->column;
562 if (O_ONOCR(tty) && ldata->column == 0)
566 ldata->canon_column = ldata->column = 0;
571 if (ldata->column > 0)
578 if (!is_continuation(c, tty))
585 i = tty->ops->write(tty, buf, i);
587 mutex_unlock(&ldata->output_lock);
592 * __process_echoes - write pending echo characters
593 * @tty: terminal device
595 * Write previously buffered echo (and other ldisc-generated) characters to the
598 * Characters generated by the ldisc (including echoes) need to be buffered
599 * because the driver's write buffer can fill during heavy program output.
600 * Echoing straight to the driver will often fail under these conditions,
601 * causing lost characters and resulting mismatches of ldisc state information.
603 * Since the ldisc state must represent the characters actually sent to the
604 * driver at the time of the write, operations like certain changes in column
605 * state are also saved in the buffer and executed here.
607 * A circular fifo buffer is used so that the most recent characters are
608 * prioritized. Also, when control characters are echoed with a prefixed "^",
609 * the pair is treated atomically and thus not separated.
611 * Locking: callers must hold %output_lock.
613 static size_t __process_echoes(struct tty_struct *tty)
615 struct n_tty_data *ldata = tty->disc_data;
616 int space, old_space;
620 old_space = space = tty_write_room(tty);
622 tail = ldata->echo_tail;
623 while (MASK(ldata->echo_commit) != MASK(tail)) {
624 c = echo_buf(ldata, tail);
625 if (c == ECHO_OP_START) {
627 bool space_left = true;
630 * Since add_echo_byte() is called without holding
631 * output_lock, we might see only portion of multi-byte
634 if (MASK(ldata->echo_commit) == MASK(tail + 1))
637 * If the buffer byte is the start of a multi-byte
638 * operation, get the next byte, which is either the
639 * op code or a control character value.
641 op = echo_buf(ldata, tail + 1);
644 case ECHO_OP_ERASE_TAB: {
645 unsigned int num_chars, num_bs;
647 if (MASK(ldata->echo_commit) == MASK(tail + 2))
649 num_chars = echo_buf(ldata, tail + 2);
652 * Determine how many columns to go back
653 * in order to erase the tab.
654 * This depends on the number of columns
655 * used by other characters within the tab
656 * area. If this (modulo 8) count is from
657 * the start of input rather than from a
658 * previous tab, we offset by canon column.
659 * Otherwise, tab spacing is normal.
661 if (!(num_chars & 0x80))
662 num_chars += ldata->canon_column;
663 num_bs = 8 - (num_chars & 7);
665 if (num_bs > space) {
671 tty_put_char(tty, '\b');
672 if (ldata->column > 0)
678 case ECHO_OP_SET_CANON_COL:
679 ldata->canon_column = ldata->column;
683 case ECHO_OP_MOVE_BACK_COL:
684 if (ldata->column > 0)
690 /* This is an escaped echo op start code */
695 tty_put_char(tty, ECHO_OP_START);
703 * If the op is not a special byte code,
704 * it is a ctrl char tagged to be echoed
705 * as "^X" (where X is the letter
706 * representing the control char).
707 * Note that we must ensure there is
708 * enough space for the whole ctrl pair.
715 tty_put_char(tty, '^');
716 tty_put_char(tty, op ^ 0100);
726 int retval = do_output_char(c, tty, space);
733 tty_put_char(tty, c);
740 /* If the echo buffer is nearly full (so that the possibility exists
741 * of echo overrun before the next commit), then discard enough
742 * data at the tail to prevent a subsequent overrun */
743 while (ldata->echo_commit > tail &&
744 ldata->echo_commit - tail >= ECHO_DISCARD_WATERMARK) {
745 if (echo_buf(ldata, tail) == ECHO_OP_START) {
746 if (echo_buf(ldata, tail + 1) == ECHO_OP_ERASE_TAB)
755 ldata->echo_tail = tail;
756 return old_space - space;
759 static void commit_echoes(struct tty_struct *tty)
761 struct n_tty_data *ldata = tty->disc_data;
762 size_t nr, old, echoed;
765 mutex_lock(&ldata->output_lock);
766 head = ldata->echo_head;
767 ldata->echo_mark = head;
768 old = ldata->echo_commit - ldata->echo_tail;
770 /* Process committed echoes if the accumulated # of bytes
771 * is over the threshold (and try again each time another
772 * block is accumulated) */
773 nr = head - ldata->echo_tail;
774 if (nr < ECHO_COMMIT_WATERMARK ||
775 (nr % ECHO_BLOCK > old % ECHO_BLOCK)) {
776 mutex_unlock(&ldata->output_lock);
780 ldata->echo_commit = head;
781 echoed = __process_echoes(tty);
782 mutex_unlock(&ldata->output_lock);
784 if (echoed && tty->ops->flush_chars)
785 tty->ops->flush_chars(tty);
788 static void process_echoes(struct tty_struct *tty)
790 struct n_tty_data *ldata = tty->disc_data;
793 if (ldata->echo_mark == ldata->echo_tail)
796 mutex_lock(&ldata->output_lock);
797 ldata->echo_commit = ldata->echo_mark;
798 echoed = __process_echoes(tty);
799 mutex_unlock(&ldata->output_lock);
801 if (echoed && tty->ops->flush_chars)
802 tty->ops->flush_chars(tty);
805 /* NB: echo_mark and echo_head should be equivalent here */
806 static void flush_echoes(struct tty_struct *tty)
808 struct n_tty_data *ldata = tty->disc_data;
810 if ((!L_ECHO(tty) && !L_ECHONL(tty)) ||
811 ldata->echo_commit == ldata->echo_head)
814 mutex_lock(&ldata->output_lock);
815 ldata->echo_commit = ldata->echo_head;
816 __process_echoes(tty);
817 mutex_unlock(&ldata->output_lock);
821 * add_echo_byte - add a byte to the echo buffer
822 * @c: unicode byte to echo
825 * Add a character or operation byte to the echo buffer.
827 static inline void add_echo_byte(unsigned char c, struct n_tty_data *ldata)
829 *echo_buf_addr(ldata, ldata->echo_head) = c;
830 smp_wmb(); /* Matches smp_rmb() in echo_buf(). */
835 * echo_move_back_col - add operation to move back a column
838 * Add an operation to the echo buffer to move back one column.
840 static void echo_move_back_col(struct n_tty_data *ldata)
842 add_echo_byte(ECHO_OP_START, ldata);
843 add_echo_byte(ECHO_OP_MOVE_BACK_COL, ldata);
847 * echo_set_canon_col - add operation to set the canon column
850 * Add an operation to the echo buffer to set the canon column to the current
853 static void echo_set_canon_col(struct n_tty_data *ldata)
855 add_echo_byte(ECHO_OP_START, ldata);
856 add_echo_byte(ECHO_OP_SET_CANON_COL, ldata);
860 * echo_erase_tab - add operation to erase a tab
861 * @num_chars: number of character columns already used
862 * @after_tab: true if num_chars starts after a previous tab
865 * Add an operation to the echo buffer to erase a tab.
867 * Called by the eraser function, which knows how many character columns have
868 * been used since either a previous tab or the start of input. This
869 * information will be used later, along with canon column (if applicable), to
870 * go back the correct number of columns.
872 static void echo_erase_tab(unsigned int num_chars, int after_tab,
873 struct n_tty_data *ldata)
875 add_echo_byte(ECHO_OP_START, ldata);
876 add_echo_byte(ECHO_OP_ERASE_TAB, ldata);
878 /* We only need to know this modulo 8 (tab spacing) */
881 /* Set the high bit as a flag if num_chars is after a previous tab */
885 add_echo_byte(num_chars, ldata);
889 * echo_char_raw - echo a character raw
890 * @c: unicode byte to echo
891 * @ldata: line disc data
893 * Echo user input back onto the screen. This must be called only when
894 * L_ECHO(tty) is true. Called from the &tty_driver.receive_buf() path.
896 * This variant does not treat control characters specially.
898 static void echo_char_raw(unsigned char c, struct n_tty_data *ldata)
900 if (c == ECHO_OP_START) {
901 add_echo_byte(ECHO_OP_START, ldata);
902 add_echo_byte(ECHO_OP_START, ldata);
904 add_echo_byte(c, ldata);
909 * echo_char - echo a character
910 * @c: unicode byte to echo
911 * @tty: terminal device
913 * Echo user input back onto the screen. This must be called only when
914 * L_ECHO(tty) is true. Called from the &tty_driver.receive_buf() path.
916 * This variant tags control characters to be echoed as "^X" (where X is the
917 * letter representing the control char).
919 static void echo_char(unsigned char c, struct tty_struct *tty)
921 struct n_tty_data *ldata = tty->disc_data;
923 if (c == ECHO_OP_START) {
924 add_echo_byte(ECHO_OP_START, ldata);
925 add_echo_byte(ECHO_OP_START, ldata);
927 if (L_ECHOCTL(tty) && iscntrl(c) && c != '\t')
928 add_echo_byte(ECHO_OP_START, ldata);
929 add_echo_byte(c, ldata);
934 * finish_erasing - complete erase
937 static inline void finish_erasing(struct n_tty_data *ldata)
939 if (ldata->erasing) {
940 echo_char_raw('/', ldata);
946 * eraser - handle erase function
947 * @c: character input
948 * @tty: terminal device
950 * Perform erase and necessary output when an erase character is present in the
951 * stream from the driver layer. Handles the complexities of UTF-8 multibyte
954 * Locking: n_tty_receive_buf()/producer path:
955 * caller holds non-exclusive %termios_rwsem
957 static void eraser(unsigned char c, struct tty_struct *tty)
959 struct n_tty_data *ldata = tty->disc_data;
960 enum { ERASE, WERASE, KILL } kill_type;
965 if (ldata->read_head == ldata->canon_head) {
966 /* process_output('\a', tty); */ /* what do you think? */
969 if (c == ERASE_CHAR(tty))
971 else if (c == WERASE_CHAR(tty))
975 ldata->read_head = ldata->canon_head;
978 if (!L_ECHOK(tty) || !L_ECHOKE(tty) || !L_ECHOE(tty)) {
979 ldata->read_head = ldata->canon_head;
980 finish_erasing(ldata);
981 echo_char(KILL_CHAR(tty), tty);
982 /* Add a newline if ECHOK is on and ECHOKE is off. */
984 echo_char_raw('\n', ldata);
991 while (MASK(ldata->read_head) != MASK(ldata->canon_head)) {
992 head = ldata->read_head;
994 /* erase a single possibly multibyte character */
997 c = read_buf(ldata, head);
998 } while (is_continuation(c, tty) &&
999 MASK(head) != MASK(ldata->canon_head));
1001 /* do not partially erase */
1002 if (is_continuation(c, tty))
1005 if (kill_type == WERASE) {
1006 /* Equivalent to BSD's ALTWERASE. */
1007 if (isalnum(c) || c == '_')
1009 else if (seen_alnums)
1012 cnt = ldata->read_head - head;
1013 ldata->read_head = head;
1015 if (L_ECHOPRT(tty)) {
1016 if (!ldata->erasing) {
1017 echo_char_raw('\\', ldata);
1020 /* if cnt > 1, output a multi-byte character */
1024 echo_char_raw(read_buf(ldata, head), ldata);
1025 echo_move_back_col(ldata);
1027 } else if (kill_type == ERASE && !L_ECHOE(tty)) {
1028 echo_char(ERASE_CHAR(tty), tty);
1029 } else if (c == '\t') {
1030 unsigned int num_chars = 0;
1032 size_t tail = ldata->read_head;
1035 * Count the columns used for characters
1036 * since the start of input or after a
1038 * This info is used to go back the correct
1039 * number of columns.
1041 while (MASK(tail) != MASK(ldata->canon_head)) {
1043 c = read_buf(ldata, tail);
1047 } else if (iscntrl(c)) {
1050 } else if (!is_continuation(c, tty)) {
1054 echo_erase_tab(num_chars, after_tab, ldata);
1056 if (iscntrl(c) && L_ECHOCTL(tty)) {
1057 echo_char_raw('\b', ldata);
1058 echo_char_raw(' ', ldata);
1059 echo_char_raw('\b', ldata);
1061 if (!iscntrl(c) || L_ECHOCTL(tty)) {
1062 echo_char_raw('\b', ldata);
1063 echo_char_raw(' ', ldata);
1064 echo_char_raw('\b', ldata);
1068 if (kill_type == ERASE)
1071 if (ldata->read_head == ldata->canon_head && L_ECHO(tty))
1072 finish_erasing(ldata);
1076 static void __isig(int sig, struct tty_struct *tty)
1078 struct pid *tty_pgrp = tty_get_pgrp(tty);
1080 kill_pgrp(tty_pgrp, sig, 1);
1086 * isig - handle the ISIG optio
1090 * Called when a signal is being sent due to terminal input. Called from the
1091 * &tty_driver.receive_buf() path, so serialized.
1093 * Performs input and output flush if !NOFLSH. In this context, the echo
1094 * buffer is 'output'. The signal is processed first to alert any current
1095 * readers or writers to discontinue and exit their i/o loops.
1097 * Locking: %ctrl.lock
1099 static void isig(int sig, struct tty_struct *tty)
1101 struct n_tty_data *ldata = tty->disc_data;
1103 if (L_NOFLSH(tty)) {
1107 } else { /* signal and flush */
1108 up_read(&tty->termios_rwsem);
1109 down_write(&tty->termios_rwsem);
1113 /* clear echo buffer */
1114 mutex_lock(&ldata->output_lock);
1115 ldata->echo_head = ldata->echo_tail = 0;
1116 ldata->echo_mark = ldata->echo_commit = 0;
1117 mutex_unlock(&ldata->output_lock);
1119 /* clear output buffer */
1120 tty_driver_flush_buffer(tty);
1122 /* clear input buffer */
1123 reset_buffer_flags(tty->disc_data);
1125 /* notify pty master of flush */
1127 n_tty_packet_mode_flush(tty);
1129 up_write(&tty->termios_rwsem);
1130 down_read(&tty->termios_rwsem);
1135 * n_tty_receive_break - handle break
1138 * An RS232 break event has been hit in the incoming bitstream. This can cause
1139 * a variety of events depending upon the termios settings.
1141 * Locking: n_tty_receive_buf()/producer path:
1142 * caller holds non-exclusive termios_rwsem
1144 * Note: may get exclusive %termios_rwsem if flushing input buffer
1146 static void n_tty_receive_break(struct tty_struct *tty)
1148 struct n_tty_data *ldata = tty->disc_data;
1152 if (I_BRKINT(tty)) {
1156 if (I_PARMRK(tty)) {
1157 put_tty_queue('\377', ldata);
1158 put_tty_queue('\0', ldata);
1160 put_tty_queue('\0', ldata);
1164 * n_tty_receive_overrun - handle overrun reporting
1167 * Data arrived faster than we could process it. While the tty driver has
1168 * flagged this the bits that were missed are gone forever.
1170 * Called from the receive_buf path so single threaded. Does not need locking
1171 * as num_overrun and overrun_time are function private.
1173 static void n_tty_receive_overrun(struct tty_struct *tty)
1175 struct n_tty_data *ldata = tty->disc_data;
1177 ldata->num_overrun++;
1178 if (time_after(jiffies, ldata->overrun_time + HZ) ||
1179 time_after(ldata->overrun_time, jiffies)) {
1180 tty_warn(tty, "%d input overrun(s)\n", ldata->num_overrun);
1181 ldata->overrun_time = jiffies;
1182 ldata->num_overrun = 0;
1187 * n_tty_receive_parity_error - error notifier
1188 * @tty: terminal device
1191 * Process a parity error and queue the right data to indicate the error case
1194 * Locking: n_tty_receive_buf()/producer path:
1195 * caller holds non-exclusive %termios_rwsem
1197 static void n_tty_receive_parity_error(struct tty_struct *tty, unsigned char c)
1199 struct n_tty_data *ldata = tty->disc_data;
1204 if (I_PARMRK(tty)) {
1205 put_tty_queue('\377', ldata);
1206 put_tty_queue('\0', ldata);
1207 put_tty_queue(c, ldata);
1209 put_tty_queue('\0', ldata);
1211 put_tty_queue(c, ldata);
1215 n_tty_receive_signal_char(struct tty_struct *tty, int signal, unsigned char c)
1224 process_echoes(tty);
1227 static bool n_tty_is_char_flow_ctrl(struct tty_struct *tty, unsigned char c)
1229 return c == START_CHAR(tty) || c == STOP_CHAR(tty);
1233 * n_tty_receive_char_flow_ctrl - receive flow control chars
1234 * @tty: terminal device
1236 * @lookahead_done: lookahead has processed this character already
1238 * Receive and process flow control character actions.
1240 * In case lookahead for flow control chars already handled the character in
1241 * advance to the normal receive, the actions are skipped during normal
1244 * Returns true if @c is consumed as flow-control character, the character
1245 * must not be treated as normal character.
1247 static bool n_tty_receive_char_flow_ctrl(struct tty_struct *tty, unsigned char c,
1248 bool lookahead_done)
1250 if (!n_tty_is_char_flow_ctrl(tty, c))
1256 if (c == START_CHAR(tty)) {
1258 process_echoes(tty);
1267 static void n_tty_receive_char_special(struct tty_struct *tty, unsigned char c,
1268 bool lookahead_done)
1270 struct n_tty_data *ldata = tty->disc_data;
1272 if (I_IXON(tty) && n_tty_receive_char_flow_ctrl(tty, c, lookahead_done))
1276 if (c == INTR_CHAR(tty)) {
1277 n_tty_receive_signal_char(tty, SIGINT, c);
1279 } else if (c == QUIT_CHAR(tty)) {
1280 n_tty_receive_signal_char(tty, SIGQUIT, c);
1282 } else if (c == SUSP_CHAR(tty)) {
1283 n_tty_receive_signal_char(tty, SIGTSTP, c);
1288 if (tty->flow.stopped && !tty->flow.tco_stopped && I_IXON(tty) && I_IXANY(tty)) {
1290 process_echoes(tty);
1298 } else if (c == '\n' && I_INLCR(tty))
1301 if (ldata->icanon) {
1302 if (c == ERASE_CHAR(tty) || c == KILL_CHAR(tty) ||
1303 (c == WERASE_CHAR(tty) && L_IEXTEN(tty))) {
1308 if (c == LNEXT_CHAR(tty) && L_IEXTEN(tty)) {
1311 finish_erasing(ldata);
1312 if (L_ECHOCTL(tty)) {
1313 echo_char_raw('^', ldata);
1314 echo_char_raw('\b', ldata);
1320 if (c == REPRINT_CHAR(tty) && L_ECHO(tty) && L_IEXTEN(tty)) {
1321 size_t tail = ldata->canon_head;
1323 finish_erasing(ldata);
1325 echo_char_raw('\n', ldata);
1326 while (MASK(tail) != MASK(ldata->read_head)) {
1327 echo_char(read_buf(ldata, tail), tty);
1334 if (L_ECHO(tty) || L_ECHONL(tty)) {
1335 echo_char_raw('\n', ldata);
1338 goto handle_newline;
1340 if (c == EOF_CHAR(tty)) {
1341 c = __DISABLED_CHAR;
1342 goto handle_newline;
1344 if ((c == EOL_CHAR(tty)) ||
1345 (c == EOL2_CHAR(tty) && L_IEXTEN(tty))) {
1347 * XXX are EOL_CHAR and EOL2_CHAR echoed?!?
1350 /* Record the column of first canon char. */
1351 if (ldata->canon_head == ldata->read_head)
1352 echo_set_canon_col(ldata);
1357 * XXX does PARMRK doubling happen for
1358 * EOL_CHAR and EOL2_CHAR?
1360 if (c == (unsigned char) '\377' && I_PARMRK(tty))
1361 put_tty_queue(c, ldata);
1364 set_bit(ldata->read_head & (N_TTY_BUF_SIZE - 1), ldata->read_flags);
1365 put_tty_queue(c, ldata);
1366 smp_store_release(&ldata->canon_head, ldata->read_head);
1367 kill_fasync(&tty->fasync, SIGIO, POLL_IN);
1368 wake_up_interruptible_poll(&tty->read_wait, EPOLLIN | EPOLLRDNORM);
1374 finish_erasing(ldata);
1376 echo_char_raw('\n', ldata);
1378 /* Record the column of first canon char. */
1379 if (ldata->canon_head == ldata->read_head)
1380 echo_set_canon_col(ldata);
1386 /* PARMRK doubling check */
1387 if (c == (unsigned char) '\377' && I_PARMRK(tty))
1388 put_tty_queue(c, ldata);
1390 put_tty_queue(c, ldata);
1394 * n_tty_receive_char - perform processing
1395 * @tty: terminal device
1398 * Process an individual character of input received from the driver. This is
1399 * serialized with respect to itself by the rules for the driver above.
1401 * Locking: n_tty_receive_buf()/producer path:
1402 * caller holds non-exclusive %termios_rwsem
1403 * publishes canon_head if canonical mode is active
1405 static void n_tty_receive_char(struct tty_struct *tty, unsigned char c)
1407 struct n_tty_data *ldata = tty->disc_data;
1409 if (tty->flow.stopped && !tty->flow.tco_stopped && I_IXON(tty) && I_IXANY(tty)) {
1411 process_echoes(tty);
1414 finish_erasing(ldata);
1415 /* Record the column of first canon char. */
1416 if (ldata->canon_head == ldata->read_head)
1417 echo_set_canon_col(ldata);
1421 /* PARMRK doubling check */
1422 if (c == (unsigned char) '\377' && I_PARMRK(tty))
1423 put_tty_queue(c, ldata);
1424 put_tty_queue(c, ldata);
1427 static void n_tty_receive_char_closing(struct tty_struct *tty, unsigned char c,
1428 bool lookahead_done)
1432 if (I_IUCLC(tty) && L_IEXTEN(tty))
1436 if (!n_tty_receive_char_flow_ctrl(tty, c, lookahead_done) &&
1437 tty->flow.stopped && !tty->flow.tco_stopped && I_IXANY(tty) &&
1438 c != INTR_CHAR(tty) && c != QUIT_CHAR(tty) &&
1439 c != SUSP_CHAR(tty)) {
1441 process_echoes(tty);
1447 n_tty_receive_char_flagged(struct tty_struct *tty, unsigned char c, char flag)
1451 n_tty_receive_break(tty);
1455 n_tty_receive_parity_error(tty, c);
1458 n_tty_receive_overrun(tty);
1461 tty_err(tty, "unknown flag %d\n", flag);
1467 n_tty_receive_char_lnext(struct tty_struct *tty, unsigned char c, char flag)
1469 struct n_tty_data *ldata = tty->disc_data;
1472 if (likely(flag == TTY_NORMAL)) {
1475 if (I_IUCLC(tty) && L_IEXTEN(tty))
1477 n_tty_receive_char(tty, c);
1479 n_tty_receive_char_flagged(tty, c, flag);
1482 /* Caller must ensure count > 0 */
1483 static void n_tty_lookahead_flow_ctrl(struct tty_struct *tty, const unsigned char *cp,
1484 const unsigned char *fp, unsigned int count)
1486 struct n_tty_data *ldata = tty->disc_data;
1487 unsigned char flag = TTY_NORMAL;
1489 ldata->lookahead_count += count;
1497 if (likely(flag == TTY_NORMAL))
1498 n_tty_receive_char_flow_ctrl(tty, *cp, false);
1504 n_tty_receive_buf_real_raw(struct tty_struct *tty, const unsigned char *cp,
1505 const char *fp, int count)
1507 struct n_tty_data *ldata = tty->disc_data;
1510 head = ldata->read_head & (N_TTY_BUF_SIZE - 1);
1511 n = min_t(size_t, count, N_TTY_BUF_SIZE - head);
1512 memcpy(read_buf_addr(ldata, head), cp, n);
1513 ldata->read_head += n;
1517 head = ldata->read_head & (N_TTY_BUF_SIZE - 1);
1518 n = min_t(size_t, count, N_TTY_BUF_SIZE - head);
1519 memcpy(read_buf_addr(ldata, head), cp, n);
1520 ldata->read_head += n;
1524 n_tty_receive_buf_raw(struct tty_struct *tty, const unsigned char *cp,
1525 const char *fp, int count)
1527 struct n_tty_data *ldata = tty->disc_data;
1528 char flag = TTY_NORMAL;
1533 if (likely(flag == TTY_NORMAL))
1534 put_tty_queue(*cp++, ldata);
1536 n_tty_receive_char_flagged(tty, *cp++, flag);
1541 n_tty_receive_buf_closing(struct tty_struct *tty, const unsigned char *cp,
1542 const char *fp, int count, bool lookahead_done)
1544 char flag = TTY_NORMAL;
1549 if (likely(flag == TTY_NORMAL))
1550 n_tty_receive_char_closing(tty, *cp++, lookahead_done);
1554 static void n_tty_receive_buf_standard(struct tty_struct *tty,
1555 const unsigned char *cp, const char *fp, int count, bool lookahead_done)
1557 struct n_tty_data *ldata = tty->disc_data;
1558 char flag = TTY_NORMAL;
1561 unsigned char c = *cp++;
1567 n_tty_receive_char_lnext(tty, c, flag);
1571 if (unlikely(flag != TTY_NORMAL)) {
1572 n_tty_receive_char_flagged(tty, c, flag);
1578 if (I_IUCLC(tty) && L_IEXTEN(tty))
1580 if (L_EXTPROC(tty)) {
1581 put_tty_queue(c, ldata);
1585 if (test_bit(c, ldata->char_map))
1586 n_tty_receive_char_special(tty, c, lookahead_done);
1588 n_tty_receive_char(tty, c);
1592 static void __receive_buf(struct tty_struct *tty, const unsigned char *cp,
1593 const char *fp, int count)
1595 struct n_tty_data *ldata = tty->disc_data;
1596 bool preops = I_ISTRIP(tty) || (I_IUCLC(tty) && L_IEXTEN(tty));
1597 size_t la_count = min_t(size_t, ldata->lookahead_count, count);
1599 if (ldata->real_raw)
1600 n_tty_receive_buf_real_raw(tty, cp, fp, count);
1601 else if (ldata->raw || (L_EXTPROC(tty) && !preops))
1602 n_tty_receive_buf_raw(tty, cp, fp, count);
1603 else if (tty->closing && !L_EXTPROC(tty)) {
1605 n_tty_receive_buf_closing(tty, cp, fp, la_count, true);
1606 if (count > la_count)
1607 n_tty_receive_buf_closing(tty, cp, fp, count - la_count, false);
1610 n_tty_receive_buf_standard(tty, cp, fp, la_count, true);
1611 if (count > la_count)
1612 n_tty_receive_buf_standard(tty, cp, fp, count - la_count, false);
1615 if (tty->ops->flush_chars)
1616 tty->ops->flush_chars(tty);
1619 ldata->lookahead_count -= la_count;
1621 if (ldata->icanon && !L_EXTPROC(tty))
1624 /* publish read_head to consumer */
1625 smp_store_release(&ldata->commit_head, ldata->read_head);
1627 if (read_cnt(ldata)) {
1628 kill_fasync(&tty->fasync, SIGIO, POLL_IN);
1629 wake_up_interruptible_poll(&tty->read_wait, EPOLLIN | EPOLLRDNORM);
1634 * n_tty_receive_buf_common - process input
1635 * @tty: device to receive input
1637 * @fp: flags for each char (if %NULL, all chars are %TTY_NORMAL)
1638 * @count: number of input chars in @cp
1639 * @flow: enable flow control
1641 * Called by the terminal driver when a block of characters has been received.
1642 * This function must be called from soft contexts not from interrupt context.
1643 * The driver is responsible for making calls one at a time and in order (or
1644 * using flush_to_ldisc()).
1646 * Returns: the # of input chars from @cp which were processed.
1648 * In canonical mode, the maximum line length is 4096 chars (including the line
1649 * termination char); lines longer than 4096 chars are truncated. After 4095
1650 * chars, input data is still processed but not stored. Overflow processing
1651 * ensures the tty can always receive more input until at least one line can be
1654 * In non-canonical mode, the read buffer will only accept 4095 chars; this
1655 * provides the necessary space for a newline char if the input mode is
1656 * switched to canonical.
1658 * Note it is possible for the read buffer to _contain_ 4096 chars in
1659 * non-canonical mode: the read buffer could already contain the maximum canon
1660 * line of 4096 chars when the mode is switched to non-canonical.
1662 * Locking: n_tty_receive_buf()/producer path:
1663 * claims non-exclusive %termios_rwsem
1664 * publishes commit_head or canon_head
1667 n_tty_receive_buf_common(struct tty_struct *tty, const unsigned char *cp,
1668 const char *fp, int count, int flow)
1670 struct n_tty_data *ldata = tty->disc_data;
1671 int room, n, rcvd = 0, overflow;
1673 down_read(&tty->termios_rwsem);
1677 * When PARMRK is set, each input char may take up to 3 chars
1678 * in the read buf; reduce the buffer space avail by 3x
1680 * If we are doing input canonicalization, and there are no
1681 * pending newlines, let characters through without limit, so
1682 * that erase characters will be handled. Other excess
1683 * characters will be beeped.
1685 * paired with store in *_copy_from_read_buf() -- guarantees
1686 * the consumer has loaded the data in read_buf up to the new
1687 * read_tail (so this producer will not overwrite unread data)
1689 size_t tail = smp_load_acquire(&ldata->read_tail);
1691 room = N_TTY_BUF_SIZE - (ldata->read_head - tail);
1693 room = DIV_ROUND_UP(room, 3);
1696 overflow = ldata->icanon && ldata->canon_head == tail;
1697 if (overflow && room < 0)
1700 WRITE_ONCE(ldata->no_room, flow && !room);
1704 n = min(count, room);
1708 /* ignore parity errors if handling overflow */
1709 if (!overflow || !fp || *fp != TTY_PARITY)
1710 __receive_buf(tty, cp, fp, n);
1717 } while (!test_bit(TTY_LDISC_CHANGING, &tty->flags));
1719 tty->receive_room = room;
1721 /* Unthrottle if handling overflow on pty */
1722 if (tty->driver->type == TTY_DRIVER_TYPE_PTY) {
1724 tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE);
1725 tty_unthrottle_safe(tty);
1726 __tty_set_flow_change(tty, 0);
1729 n_tty_check_throttle(tty);
1731 if (unlikely(ldata->no_room)) {
1733 * Barrier here is to ensure to read the latest read_tail in
1734 * chars_in_buffer() and to make sure that read_tail is not loaded
1735 * before ldata->no_room is set.
1738 if (!chars_in_buffer(tty))
1739 n_tty_kick_worker(tty);
1742 up_read(&tty->termios_rwsem);
1747 static void n_tty_receive_buf(struct tty_struct *tty, const unsigned char *cp,
1748 const char *fp, int count)
1750 n_tty_receive_buf_common(tty, cp, fp, count, 0);
1753 static int n_tty_receive_buf2(struct tty_struct *tty, const unsigned char *cp,
1754 const char *fp, int count)
1756 return n_tty_receive_buf_common(tty, cp, fp, count, 1);
1760 * n_tty_set_termios - termios data changed
1762 * @old: previous data
1764 * Called by the tty layer when the user changes termios flags so that the line
1765 * discipline can plan ahead. This function cannot sleep and is protected from
1766 * re-entry by the tty layer. The user is guaranteed that this function will
1767 * not be re-entered or in progress when the ldisc is closed.
1769 * Locking: Caller holds @tty->termios_rwsem
1771 static void n_tty_set_termios(struct tty_struct *tty, const struct ktermios *old)
1773 struct n_tty_data *ldata = tty->disc_data;
1775 if (!old || (old->c_lflag ^ tty->termios.c_lflag) & (ICANON | EXTPROC)) {
1776 bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
1777 ldata->line_start = ldata->read_tail;
1778 if (!L_ICANON(tty) || !read_cnt(ldata)) {
1779 ldata->canon_head = ldata->read_tail;
1782 set_bit((ldata->read_head - 1) & (N_TTY_BUF_SIZE - 1),
1784 ldata->canon_head = ldata->read_head;
1787 ldata->commit_head = ldata->read_head;
1792 ldata->icanon = (L_ICANON(tty) != 0);
1794 if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
1795 I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
1796 I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
1798 bitmap_zero(ldata->char_map, 256);
1800 if (I_IGNCR(tty) || I_ICRNL(tty))
1801 set_bit('\r', ldata->char_map);
1803 set_bit('\n', ldata->char_map);
1805 if (L_ICANON(tty)) {
1806 set_bit(ERASE_CHAR(tty), ldata->char_map);
1807 set_bit(KILL_CHAR(tty), ldata->char_map);
1808 set_bit(EOF_CHAR(tty), ldata->char_map);
1809 set_bit('\n', ldata->char_map);
1810 set_bit(EOL_CHAR(tty), ldata->char_map);
1811 if (L_IEXTEN(tty)) {
1812 set_bit(WERASE_CHAR(tty), ldata->char_map);
1813 set_bit(LNEXT_CHAR(tty), ldata->char_map);
1814 set_bit(EOL2_CHAR(tty), ldata->char_map);
1816 set_bit(REPRINT_CHAR(tty),
1821 set_bit(START_CHAR(tty), ldata->char_map);
1822 set_bit(STOP_CHAR(tty), ldata->char_map);
1825 set_bit(INTR_CHAR(tty), ldata->char_map);
1826 set_bit(QUIT_CHAR(tty), ldata->char_map);
1827 set_bit(SUSP_CHAR(tty), ldata->char_map);
1829 clear_bit(__DISABLED_CHAR, ldata->char_map);
1831 ldata->real_raw = 0;
1834 if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
1835 (I_IGNPAR(tty) || !I_INPCK(tty)) &&
1836 (tty->driver->flags & TTY_DRIVER_REAL_RAW))
1837 ldata->real_raw = 1;
1839 ldata->real_raw = 0;
1842 * Fix tty hang when I_IXON(tty) is cleared, but the tty
1843 * been stopped by STOP_CHAR(tty) before it.
1845 if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow.tco_stopped) {
1847 process_echoes(tty);
1850 /* The termios change make the tty ready for I/O */
1851 wake_up_interruptible(&tty->write_wait);
1852 wake_up_interruptible(&tty->read_wait);
1856 * n_tty_close - close the ldisc for this tty
1859 * Called from the terminal layer when this line discipline is being shut down,
1860 * either because of a close or becsuse of a discipline change. The function
1861 * will not be called while other ldisc methods are in progress.
1863 static void n_tty_close(struct tty_struct *tty)
1865 struct n_tty_data *ldata = tty->disc_data;
1868 n_tty_packet_mode_flush(tty);
1870 down_write(&tty->termios_rwsem);
1872 tty->disc_data = NULL;
1873 up_write(&tty->termios_rwsem);
1877 * n_tty_open - open an ldisc
1878 * @tty: terminal to open
1880 * Called when this line discipline is being attached to the terminal device.
1881 * Can sleep. Called serialized so that no other events will occur in parallel.
1882 * No further open will occur until a close.
1884 static int n_tty_open(struct tty_struct *tty)
1886 struct n_tty_data *ldata;
1888 /* Currently a malloc failure here can panic */
1889 ldata = vzalloc(sizeof(*ldata));
1893 ldata->overrun_time = jiffies;
1894 mutex_init(&ldata->atomic_read_lock);
1895 mutex_init(&ldata->output_lock);
1897 tty->disc_data = ldata;
1899 /* indicate buffer work may resume */
1900 clear_bit(TTY_LDISC_HALTED, &tty->flags);
1901 n_tty_set_termios(tty, NULL);
1902 tty_unthrottle(tty);
1906 static inline int input_available_p(struct tty_struct *tty, int poll)
1908 struct n_tty_data *ldata = tty->disc_data;
1909 int amt = poll && !TIME_CHAR(tty) && MIN_CHAR(tty) ? MIN_CHAR(tty) : 1;
1911 if (ldata->icanon && !L_EXTPROC(tty))
1912 return ldata->canon_head != ldata->read_tail;
1914 return ldata->commit_head - ldata->read_tail >= amt;
1918 * copy_from_read_buf - copy read data directly
1919 * @tty: terminal device
1923 * Helper function to speed up n_tty_read(). It is only called when %ICANON is
1924 * off; it copies characters straight from the tty queue.
1926 * Returns: true if it successfully copied data, but there is still more data
1930 * * called under the @ldata->atomic_read_lock sem
1931 * * n_tty_read()/consumer path:
1932 * caller holds non-exclusive %termios_rwsem;
1933 * read_tail published
1935 static bool copy_from_read_buf(struct tty_struct *tty,
1936 unsigned char **kbp,
1940 struct n_tty_data *ldata = tty->disc_data;
1943 size_t head = smp_load_acquire(&ldata->commit_head);
1944 size_t tail = ldata->read_tail & (N_TTY_BUF_SIZE - 1);
1946 n = min(head - ldata->read_tail, N_TTY_BUF_SIZE - tail);
1949 unsigned char *from = read_buf_addr(ldata, tail);
1950 memcpy(*kbp, from, n);
1951 is_eof = n == 1 && *from == EOF_CHAR(tty);
1952 tty_audit_add_data(tty, from, n);
1953 zero_buffer(tty, from, n);
1954 smp_store_release(&ldata->read_tail, ldata->read_tail + n);
1955 /* Turn single EOF into zero-length read */
1956 if (L_EXTPROC(tty) && ldata->icanon && is_eof &&
1957 (head == ldata->read_tail))
1962 /* If we have more to copy, let the caller know */
1963 return head != ldata->read_tail;
1969 * canon_copy_from_read_buf - copy read data in canonical mode
1970 * @tty: terminal device
1974 * Helper function for n_tty_read(). It is only called when %ICANON is on; it
1975 * copies one line of input up to and including the line-delimiting character
1976 * into the result buffer.
1978 * Note: When termios is changed from non-canonical to canonical mode and the
1979 * read buffer contains data, n_tty_set_termios() simulates an EOF push (as if
1980 * C-d were input) _without_ the %DISABLED_CHAR in the buffer. This causes data
1981 * already processed as input to be immediately available as input although a
1982 * newline has not been received.
1985 * * called under the %atomic_read_lock mutex
1986 * * n_tty_read()/consumer path:
1987 * caller holds non-exclusive %termios_rwsem;
1988 * read_tail published
1990 static bool canon_copy_from_read_buf(struct tty_struct *tty,
1991 unsigned char **kbp,
1994 struct n_tty_data *ldata = tty->disc_data;
1995 size_t n, size, more, c;
1997 size_t tail, canon_head;
2000 /* N.B. avoid overrun if nr == 0 */
2004 canon_head = smp_load_acquire(&ldata->canon_head);
2005 n = min(*nr, canon_head - ldata->read_tail);
2007 tail = ldata->read_tail & (N_TTY_BUF_SIZE - 1);
2008 size = min_t(size_t, tail + n, N_TTY_BUF_SIZE);
2010 n_tty_trace("%s: nr:%zu tail:%zu n:%zu size:%zu\n",
2011 __func__, *nr, tail, n, size);
2013 eol = find_next_bit(ldata->read_flags, size, tail);
2014 more = n - (size - tail);
2015 if (eol == N_TTY_BUF_SIZE && more) {
2016 /* scan wrapped without finding set bit */
2017 eol = find_first_bit(ldata->read_flags, more);
2018 found = eol != more;
2020 found = eol != size;
2023 if (n > N_TTY_BUF_SIZE)
2024 n += N_TTY_BUF_SIZE;
2027 if (!found || read_buf(ldata, eol) != __DISABLED_CHAR)
2030 n_tty_trace("%s: eol:%zu found:%d n:%zu c:%zu tail:%zu more:%zu\n",
2031 __func__, eol, found, n, c, tail, more);
2033 tty_copy(tty, *kbp, tail, n);
2038 clear_bit(eol, ldata->read_flags);
2039 smp_store_release(&ldata->read_tail, ldata->read_tail + c);
2043 ldata->line_start = ldata->read_tail;
2050 /* No EOL found - do a continuation retry if there is more data */
2051 return ldata->read_tail != canon_head;
2055 * If we finished a read at the exact location of an
2056 * EOF (special EOL character that's a __DISABLED_CHAR)
2057 * in the stream, silently eat the EOF.
2059 static void canon_skip_eof(struct tty_struct *tty)
2061 struct n_tty_data *ldata = tty->disc_data;
2062 size_t tail, canon_head;
2064 canon_head = smp_load_acquire(&ldata->canon_head);
2065 tail = ldata->read_tail;
2068 if (tail == canon_head)
2071 // See if the tail position is EOF in the circular buffer
2072 tail &= (N_TTY_BUF_SIZE - 1);
2073 if (!test_bit(tail, ldata->read_flags))
2075 if (read_buf(ldata, tail) != __DISABLED_CHAR)
2078 // Clear the EOL bit, skip the EOF char.
2079 clear_bit(tail, ldata->read_flags);
2080 smp_store_release(&ldata->read_tail, ldata->read_tail + 1);
2084 * job_control - check job control
2086 * @file: file handle
2088 * Perform job control management checks on this @file/@tty descriptor and if
2089 * appropriate send any needed signals and return a negative error code if
2090 * action should be taken.
2093 * * redirected write test is safe
2094 * * current->signal->tty check is safe
2095 * * ctrl.lock to safely reference @tty->ctrl.pgrp
2097 static int job_control(struct tty_struct *tty, struct file *file)
2099 /* Job control check -- must be done at start and after
2100 every sleep (POSIX.1 7.1.1.4). */
2101 /* NOTE: not yet done after every sleep pending a thorough
2102 check of the logic of this change. -- jlc */
2103 /* don't stop on /dev/console */
2104 if (file->f_op->write_iter == redirected_tty_write)
2107 return __tty_check_change(tty, SIGTTIN);
2112 * n_tty_read - read function for tty
2114 * @file: file object
2115 * @kbuf: kernelspace buffer pointer
2117 * @cookie: if non-%NULL, this is a continuation read
2118 * @offset: where to continue reading from (unused in n_tty)
2120 * Perform reads for the line discipline. We are guaranteed that the line
2121 * discipline will not be closed under us but we may get multiple parallel
2122 * readers and must handle this ourselves. We may also get a hangup. Always
2123 * called in user context, may sleep.
2125 * This code must be sure never to sleep through a hangup.
2127 * Locking: n_tty_read()/consumer path:
2128 * claims non-exclusive termios_rwsem;
2129 * publishes read_tail
2131 static ssize_t n_tty_read(struct tty_struct *tty, struct file *file,
2132 unsigned char *kbuf, size_t nr,
2133 void **cookie, unsigned long offset)
2135 struct n_tty_data *ldata = tty->disc_data;
2136 unsigned char *kb = kbuf;
2137 DEFINE_WAIT_FUNC(wait, woken_wake_function);
2146 * Is this a continuation of a read started earler?
2148 * If so, we still hold the atomic_read_lock and the
2149 * termios_rwsem, and can just continue to copy data.
2152 if (ldata->icanon && !L_EXTPROC(tty)) {
2154 * If we have filled the user buffer, see
2155 * if we should skip an EOF character before
2156 * releasing the lock and returning done.
2159 canon_skip_eof(tty);
2160 else if (canon_copy_from_read_buf(tty, &kb, &nr))
2163 if (copy_from_read_buf(tty, &kb, &nr))
2167 /* No more data - release locks and stop retries */
2168 n_tty_kick_worker(tty);
2169 n_tty_check_unthrottle(tty);
2170 up_read(&tty->termios_rwsem);
2171 mutex_unlock(&ldata->atomic_read_lock);
2176 c = job_control(tty, file);
2181 * Internal serialization of reads.
2183 if (file->f_flags & O_NONBLOCK) {
2184 if (!mutex_trylock(&ldata->atomic_read_lock))
2187 if (mutex_lock_interruptible(&ldata->atomic_read_lock))
2188 return -ERESTARTSYS;
2191 down_read(&tty->termios_rwsem);
2194 timeout = MAX_SCHEDULE_TIMEOUT;
2195 if (!ldata->icanon) {
2196 minimum = MIN_CHAR(tty);
2198 time = (HZ / 10) * TIME_CHAR(tty);
2200 timeout = (HZ / 10) * TIME_CHAR(tty);
2205 packet = tty->ctrl.packet;
2206 old_tail = ldata->read_tail;
2208 add_wait_queue(&tty->read_wait, &wait);
2210 /* First test for status change. */
2211 if (packet && tty->link->ctrl.pktstatus) {
2215 spin_lock_irq(&tty->link->ctrl.lock);
2216 cs = tty->link->ctrl.pktstatus;
2217 tty->link->ctrl.pktstatus = 0;
2218 spin_unlock_irq(&tty->link->ctrl.lock);
2224 if (!input_available_p(tty, 0)) {
2225 up_read(&tty->termios_rwsem);
2226 tty_buffer_flush_work(tty->port);
2227 down_read(&tty->termios_rwsem);
2228 if (!input_available_p(tty, 0)) {
2229 if (test_bit(TTY_OTHER_CLOSED, &tty->flags)) {
2233 if (tty_hung_up_p(file))
2236 * Abort readers for ttys which never actually
2237 * get hung up. See __tty_hangup().
2239 if (test_bit(TTY_HUPPING, &tty->flags))
2243 if (tty_io_nonblock(tty, file)) {
2247 if (signal_pending(current)) {
2248 retval = -ERESTARTSYS;
2251 up_read(&tty->termios_rwsem);
2253 timeout = wait_woken(&wait, TASK_INTERRUPTIBLE,
2256 down_read(&tty->termios_rwsem);
2261 if (ldata->icanon && !L_EXTPROC(tty)) {
2262 if (canon_copy_from_read_buf(tty, &kb, &nr))
2263 goto more_to_be_read;
2265 /* Deal with packet mode. */
2266 if (packet && kb == kbuf) {
2267 *kb++ = TIOCPKT_DATA;
2272 * Copy data, and if there is more to be had
2273 * and we have nothing more to wait for, then
2274 * let's mark us for retries.
2276 * NOTE! We return here with both the termios_sem
2277 * and atomic_read_lock still held, the retries
2278 * will release them when done.
2280 if (copy_from_read_buf(tty, &kb, &nr) && kb - kbuf >= minimum) {
2282 remove_wait_queue(&tty->read_wait, &wait);
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);
2315 * n_tty_write - write function for tty
2317 * @file: file object
2318 * @buf: userspace buffer pointer
2321 * Write function of the terminal device. This is serialized with respect to
2322 * other write callers but not to termios changes, reads and other such events.
2323 * Since the receive code will echo characters, thus calling driver write
2324 * methods, the %output_lock is used in the output processing functions called
2325 * here as well as in the echo processing function to protect the column state
2326 * and space left in the buffer.
2328 * This code must be sure never to sleep through a hangup.
2330 * Locking: output_lock to protect column state and space left
2331 * (note that the process_output*() functions take this lock themselves)
2334 static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
2335 const unsigned char *buf, size_t nr)
2337 const unsigned char *b = buf;
2338 DEFINE_WAIT_FUNC(wait, woken_wake_function);
2342 /* Job control check -- must be done at start (POSIX.1 7.1.1.4). */
2343 if (L_TOSTOP(tty) && file->f_op->write_iter != redirected_tty_write) {
2344 retval = tty_check_change(tty);
2349 down_read(&tty->termios_rwsem);
2351 /* Write out any echoed characters that are still pending */
2352 process_echoes(tty);
2354 add_wait_queue(&tty->write_wait, &wait);
2356 if (signal_pending(current)) {
2357 retval = -ERESTARTSYS;
2360 if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
2366 ssize_t num = process_output_block(tty, b, nr);
2378 if (process_output(c, tty) < 0)
2382 if (tty->ops->flush_chars)
2383 tty->ops->flush_chars(tty);
2385 struct n_tty_data *ldata = tty->disc_data;
2388 mutex_lock(&ldata->output_lock);
2389 c = tty->ops->write(tty, b, nr);
2390 mutex_unlock(&ldata->output_lock);
2403 if (tty_io_nonblock(tty, file)) {
2407 up_read(&tty->termios_rwsem);
2409 wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
2411 down_read(&tty->termios_rwsem);
2414 remove_wait_queue(&tty->write_wait, &wait);
2415 if (nr && tty->fasync)
2416 set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
2417 up_read(&tty->termios_rwsem);
2418 return (b - buf) ? b - buf : retval;
2422 * n_tty_poll - poll method for N_TTY
2423 * @tty: terminal device
2424 * @file: file accessing it
2427 * Called when the line discipline is asked to poll() for data or for special
2428 * events. This code is not serialized with respect to other events save
2431 * This code must be sure never to sleep through a hangup.
2433 * Locking: called without the kernel lock held -- fine.
2435 static __poll_t n_tty_poll(struct tty_struct *tty, struct file *file,
2440 poll_wait(file, &tty->read_wait, wait);
2441 poll_wait(file, &tty->write_wait, wait);
2442 if (input_available_p(tty, 1))
2443 mask |= EPOLLIN | EPOLLRDNORM;
2445 tty_buffer_flush_work(tty->port);
2446 if (input_available_p(tty, 1))
2447 mask |= EPOLLIN | EPOLLRDNORM;
2449 if (tty->ctrl.packet && tty->link->ctrl.pktstatus)
2450 mask |= EPOLLPRI | EPOLLIN | EPOLLRDNORM;
2451 if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
2453 if (tty_hung_up_p(file))
2455 if (tty->ops->write && !tty_is_writelocked(tty) &&
2456 tty_chars_in_buffer(tty) < WAKEUP_CHARS &&
2457 tty_write_room(tty) > 0)
2458 mask |= EPOLLOUT | EPOLLWRNORM;
2462 static unsigned long inq_canon(struct n_tty_data *ldata)
2464 size_t nr, head, tail;
2466 if (ldata->canon_head == ldata->read_tail)
2468 head = ldata->canon_head;
2469 tail = ldata->read_tail;
2471 /* Skip EOF-chars.. */
2472 while (MASK(head) != MASK(tail)) {
2473 if (test_bit(tail & (N_TTY_BUF_SIZE - 1), ldata->read_flags) &&
2474 read_buf(ldata, tail) == __DISABLED_CHAR)
2481 static int n_tty_ioctl(struct tty_struct *tty, unsigned int cmd,
2484 struct n_tty_data *ldata = tty->disc_data;
2489 return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
2491 down_write(&tty->termios_rwsem);
2492 if (L_ICANON(tty) && !L_EXTPROC(tty))
2493 retval = inq_canon(ldata);
2495 retval = read_cnt(ldata);
2496 up_write(&tty->termios_rwsem);
2497 return put_user(retval, (unsigned int __user *) arg);
2499 return n_tty_ioctl_helper(tty, cmd, arg);
2503 static struct tty_ldisc_ops n_tty_ops = {
2504 .owner = THIS_MODULE,
2508 .close = n_tty_close,
2509 .flush_buffer = n_tty_flush_buffer,
2511 .write = n_tty_write,
2512 .ioctl = n_tty_ioctl,
2513 .set_termios = n_tty_set_termios,
2515 .receive_buf = n_tty_receive_buf,
2516 .write_wakeup = n_tty_write_wakeup,
2517 .receive_buf2 = n_tty_receive_buf2,
2518 .lookahead_buf = n_tty_lookahead_flow_ctrl,
2522 * n_tty_inherit_ops - inherit N_TTY methods
2523 * @ops: struct tty_ldisc_ops where to save N_TTY methods
2525 * Enables a 'subclass' line discipline to 'inherit' N_TTY methods.
2528 void n_tty_inherit_ops(struct tty_ldisc_ops *ops)
2533 EXPORT_SYMBOL_GPL(n_tty_inherit_ops);
2535 void __init n_tty_init(void)
2537 tty_register_ldisc(&n_tty_ops);