xref: /openbmc/linux/drivers/tty/n_tty.c (revision c4c3c32d)
1 // SPDX-License-Identifier: GPL-1.0+
2 /*
3  * n_tty.c --- implements the N_TTY line discipline.
4  *
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,
8  * anyway...)
9  *
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.
13  *
14  * Written by Theodore Ts'o, Copyright 1994.
15  *
16  * This file also contains code originally written by Linus Torvalds,
17  * Copyright 1991, 1992, 1993, and by Julian Cowley, Copyright 1994.
18  *
19  * Reduced memory usage for older ARM systems  - Russell King.
20  *
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.
24  *
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
28  *		EAGAIN
29  */
30 
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>
50 
51 #include "tty.h"
52 
53 /*
54  * Until this number of characters is queued in the xmit buffer, select will
55  * return "we have room for writes".
56  */
57 #define WAKEUP_CHARS 256
58 
59 /*
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.
63  */
64 #define TTY_THRESHOLD_THROTTLE		128 /* now based on remaining room */
65 #define TTY_THRESHOLD_UNTHROTTLE	128
66 
67 /*
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
71  * codes.
72  */
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
77 
78 #define ECHO_COMMIT_WATERMARK	256
79 #define ECHO_BLOCK		256
80 #define ECHO_DISCARD_WATERMARK	N_TTY_BUF_SIZE - (ECHO_BLOCK + 32)
81 
82 
83 #undef N_TTY_TRACE
84 #ifdef N_TTY_TRACE
85 # define n_tty_trace(f, args...)	trace_printk(f, ##args)
86 #else
87 # define n_tty_trace(f, args...)	no_printk(f, ##args)
88 #endif
89 
90 struct n_tty_data {
91 	/* producer-published */
92 	size_t read_head;
93 	size_t commit_head;
94 	size_t canon_head;
95 	size_t echo_head;
96 	size_t echo_commit;
97 	size_t echo_mark;
98 	DECLARE_BITMAP(char_map, 256);
99 
100 	/* private to n_tty_receive_overrun (single-threaded) */
101 	unsigned long overrun_time;
102 	int num_overrun;
103 
104 	/* non-atomic */
105 	bool no_room;
106 
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;
110 
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];
115 
116 	/* consumer-published */
117 	size_t read_tail;
118 	size_t line_start;
119 
120 	/* # of chars looked ahead (to find software flow control chars) */
121 	size_t lookahead_count;
122 
123 	/* protected by output lock */
124 	unsigned int column;
125 	unsigned int canon_column;
126 	size_t echo_tail;
127 
128 	struct mutex atomic_read_lock;
129 	struct mutex output_lock;
130 };
131 
132 #define MASK(x) ((x) & (N_TTY_BUF_SIZE - 1))
133 
134 static inline size_t read_cnt(struct n_tty_data *ldata)
135 {
136 	return ldata->read_head - ldata->read_tail;
137 }
138 
139 static inline unsigned char read_buf(struct n_tty_data *ldata, size_t i)
140 {
141 	return ldata->read_buf[i & (N_TTY_BUF_SIZE - 1)];
142 }
143 
144 static inline unsigned char *read_buf_addr(struct n_tty_data *ldata, size_t i)
145 {
146 	return &ldata->read_buf[i & (N_TTY_BUF_SIZE - 1)];
147 }
148 
149 static inline unsigned char echo_buf(struct n_tty_data *ldata, size_t i)
150 {
151 	smp_rmb(); /* Matches smp_wmb() in add_echo_byte(). */
152 	return ldata->echo_buf[i & (N_TTY_BUF_SIZE - 1)];
153 }
154 
155 static inline unsigned char *echo_buf_addr(struct n_tty_data *ldata, size_t i)
156 {
157 	return &ldata->echo_buf[i & (N_TTY_BUF_SIZE - 1)];
158 }
159 
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)
162 {
163 	bool icanon = !!L_ICANON(tty);
164 	bool no_echo = !L_ECHO(tty);
165 
166 	if (icanon && no_echo)
167 		memset(buffer, 0x00, size);
168 }
169 
170 static void tty_copy(struct tty_struct *tty, void *to, size_t tail, size_t n)
171 {
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);
175 
176 	if (n > size) {
177 		tty_audit_add_data(tty, from, size);
178 		memcpy(to, from, size);
179 		zero_buffer(tty, from, size);
180 		to += size;
181 		n -= size;
182 		from = ldata->read_buf;
183 	}
184 
185 	tty_audit_add_data(tty, from, n);
186 	memcpy(to, from, n);
187 	zero_buffer(tty, from, n);
188 }
189 
190 /**
191  * n_tty_kick_worker - start input worker (if required)
192  * @tty: terminal
193  *
194  * Re-schedules the flip buffer work if it may have stopped.
195  *
196  * Locking:
197  *  * Caller holds exclusive %termios_rwsem, or
198  *  * n_tty_read()/consumer path:
199  *	holds non-exclusive %termios_rwsem
200  */
201 static void n_tty_kick_worker(struct tty_struct *tty)
202 {
203 	struct n_tty_data *ldata = tty->disc_data;
204 
205 	/* Did the input worker stop? Restart it */
206 	if (unlikely(READ_ONCE(ldata->no_room))) {
207 		WRITE_ONCE(ldata->no_room, 0);
208 
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
214 		 */
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);
218 	}
219 }
220 
221 static ssize_t chars_in_buffer(struct tty_struct *tty)
222 {
223 	struct n_tty_data *ldata = tty->disc_data;
224 	ssize_t n = 0;
225 
226 	if (!ldata->icanon)
227 		n = ldata->commit_head - ldata->read_tail;
228 	else
229 		n = ldata->canon_head - ldata->read_tail;
230 	return n;
231 }
232 
233 /**
234  * n_tty_write_wakeup	-	asynchronous I/O notifier
235  * @tty: tty device
236  *
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.
239  */
240 static void n_tty_write_wakeup(struct tty_struct *tty)
241 {
242 	clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
243 	kill_fasync(&tty->fasync, SIGIO, POLL_OUT);
244 }
245 
246 static void n_tty_check_throttle(struct tty_struct *tty)
247 {
248 	struct n_tty_data *ldata = tty->disc_data;
249 
250 	/*
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!
254 	 */
255 	if (ldata->icanon && ldata->canon_head == ldata->read_tail)
256 		return;
257 
258 	while (1) {
259 		int throttled;
260 		tty_set_flow_change(tty, TTY_THROTTLE_SAFE);
261 		if (N_TTY_BUF_SIZE - read_cnt(ldata) >= TTY_THRESHOLD_THROTTLE)
262 			break;
263 		throttled = tty_throttle_safe(tty);
264 		if (!throttled)
265 			break;
266 	}
267 	__tty_set_flow_change(tty, 0);
268 }
269 
270 static void n_tty_check_unthrottle(struct tty_struct *tty)
271 {
272 	if (tty->driver->type == TTY_DRIVER_TYPE_PTY) {
273 		if (chars_in_buffer(tty) > TTY_THRESHOLD_UNTHROTTLE)
274 			return;
275 		n_tty_kick_worker(tty);
276 		tty_wakeup(tty->link);
277 		return;
278 	}
279 
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.
286 	 */
287 
288 	while (1) {
289 		int unthrottled;
290 		tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE);
291 		if (chars_in_buffer(tty) > TTY_THRESHOLD_UNTHROTTLE)
292 			break;
293 		n_tty_kick_worker(tty);
294 		unthrottled = tty_unthrottle_safe(tty);
295 		if (!unthrottled)
296 			break;
297 	}
298 	__tty_set_flow_change(tty, 0);
299 }
300 
301 /**
302  * put_tty_queue		-	add character to tty
303  * @c: character
304  * @ldata: n_tty data
305  *
306  * Add a character to the tty read_buf queue.
307  *
308  * Locking:
309  *  * n_tty_receive_buf()/producer path:
310  *	caller holds non-exclusive %termios_rwsem
311  */
312 static inline void put_tty_queue(unsigned char c, struct n_tty_data *ldata)
313 {
314 	*read_buf_addr(ldata, ldata->read_head) = c;
315 	ldata->read_head++;
316 }
317 
318 /**
319  * reset_buffer_flags	-	reset buffer state
320  * @ldata: line disc data to reset
321  *
322  * Reset the read buffer counters and clear the flags. Called from
323  * n_tty_open() and n_tty_flush_buffer().
324  *
325  * Locking:
326  *  * caller holds exclusive %termios_rwsem, or
327  *  * (locking is not required)
328  */
329 static void reset_buffer_flags(struct n_tty_data *ldata)
330 {
331 	ldata->read_head = ldata->canon_head = ldata->read_tail = 0;
332 	ldata->commit_head = 0;
333 	ldata->line_start = 0;
334 
335 	ldata->erasing = 0;
336 	bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
337 	ldata->push = 0;
338 
339 	ldata->lookahead_count = 0;
340 }
341 
342 static void n_tty_packet_mode_flush(struct tty_struct *tty)
343 {
344 	unsigned long flags;
345 
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);
351 	}
352 }
353 
354 /**
355  * n_tty_flush_buffer	-	clean input queue
356  * @tty: terminal device
357  *
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).
361  *
362  * Holds %termios_rwsem to exclude producer/consumer while buffer indices are
363  * reset.
364  *
365  * Locking: %ctrl.lock, exclusive %termios_rwsem
366  */
367 static void n_tty_flush_buffer(struct tty_struct *tty)
368 {
369 	down_write(&tty->termios_rwsem);
370 	reset_buffer_flags(tty->disc_data);
371 	n_tty_kick_worker(tty);
372 
373 	if (tty->link)
374 		n_tty_packet_mode_flush(tty);
375 	up_write(&tty->termios_rwsem);
376 }
377 
378 /**
379  * is_utf8_continuation	-	utf8 multibyte check
380  * @c: byte to check
381  *
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.
385  */
386 static inline int is_utf8_continuation(unsigned char c)
387 {
388 	return (c & 0xc0) == 0x80;
389 }
390 
391 /**
392  * is_continuation	-	multibyte check
393  * @c: byte to check
394  * @tty: terminal device
395  *
396  * Returns: true if the utf8 character @c is a multibyte continuation character
397  * and the terminal is in unicode mode.
398  */
399 static inline int is_continuation(unsigned char c, struct tty_struct *tty)
400 {
401 	return I_IUTF8(tty) && is_utf8_continuation(c);
402 }
403 
404 /**
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
409  *
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.
413  *
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
416  * them here.
417  *
418  * Returns: the number of bytes of buffer space used or -1 if no space left.
419  *
420  * Locking: should be called under the %output_lock to protect the column state
421  * and space left in the buffer.
422  */
423 static int do_output_char(unsigned char c, struct tty_struct *tty, int space)
424 {
425 	struct n_tty_data *ldata = tty->disc_data;
426 	int	spaces;
427 
428 	if (!space)
429 		return -1;
430 
431 	switch (c) {
432 	case '\n':
433 		if (O_ONLRET(tty))
434 			ldata->column = 0;
435 		if (O_ONLCR(tty)) {
436 			if (space < 2)
437 				return -1;
438 			ldata->canon_column = ldata->column = 0;
439 			tty->ops->write(tty, "\r\n", 2);
440 			return 2;
441 		}
442 		ldata->canon_column = ldata->column;
443 		break;
444 	case '\r':
445 		if (O_ONOCR(tty) && ldata->column == 0)
446 			return 0;
447 		if (O_OCRNL(tty)) {
448 			c = '\n';
449 			if (O_ONLRET(tty))
450 				ldata->canon_column = ldata->column = 0;
451 			break;
452 		}
453 		ldata->canon_column = ldata->column = 0;
454 		break;
455 	case '\t':
456 		spaces = 8 - (ldata->column & 7);
457 		if (O_TABDLY(tty) == XTABS) {
458 			if (space < spaces)
459 				return -1;
460 			ldata->column += spaces;
461 			tty->ops->write(tty, "        ", spaces);
462 			return spaces;
463 		}
464 		ldata->column += spaces;
465 		break;
466 	case '\b':
467 		if (ldata->column > 0)
468 			ldata->column--;
469 		break;
470 	default:
471 		if (!iscntrl(c)) {
472 			if (O_OLCUC(tty))
473 				c = toupper(c);
474 			if (!is_continuation(c, tty))
475 				ldata->column++;
476 		}
477 		break;
478 	}
479 
480 	tty_put_char(tty, c);
481 	return 1;
482 }
483 
484 /**
485  * process_output	-	output post processor
486  * @c: character (or partial unicode symbol)
487  * @tty: terminal device
488  *
489  * Output one character with OPOST processing.
490  *
491  * Returns: -1 when the output device is full and the character must be
492  * retried.
493  *
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).
496  */
497 static int process_output(unsigned char c, struct tty_struct *tty)
498 {
499 	struct n_tty_data *ldata = tty->disc_data;
500 	int	space, retval;
501 
502 	mutex_lock(&ldata->output_lock);
503 
504 	space = tty_write_room(tty);
505 	retval = do_output_char(c, tty, space);
506 
507 	mutex_unlock(&ldata->output_lock);
508 	if (retval < 0)
509 		return -1;
510 	else
511 		return 0;
512 }
513 
514 /**
515  * process_output_block	-	block post processor
516  * @tty: terminal device
517  * @buf: character buffer
518  * @nr: number of bytes to output
519  *
520  * Output a block of characters with OPOST processing.
521  *
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.
526  *
527  * Returns: the number of characters output.
528  *
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).
531  */
532 static ssize_t process_output_block(struct tty_struct *tty,
533 				    const unsigned char *buf, unsigned int nr)
534 {
535 	struct n_tty_data *ldata = tty->disc_data;
536 	int	space;
537 	int	i;
538 	const unsigned char *cp;
539 
540 	mutex_lock(&ldata->output_lock);
541 
542 	space = tty_write_room(tty);
543 	if (space <= 0) {
544 		mutex_unlock(&ldata->output_lock);
545 		return space;
546 	}
547 	if (nr > space)
548 		nr = space;
549 
550 	for (i = 0, cp = buf; i < nr; i++, cp++) {
551 		unsigned char c = *cp;
552 
553 		switch (c) {
554 		case '\n':
555 			if (O_ONLRET(tty))
556 				ldata->column = 0;
557 			if (O_ONLCR(tty))
558 				goto break_out;
559 			ldata->canon_column = ldata->column;
560 			break;
561 		case '\r':
562 			if (O_ONOCR(tty) && ldata->column == 0)
563 				goto break_out;
564 			if (O_OCRNL(tty))
565 				goto break_out;
566 			ldata->canon_column = ldata->column = 0;
567 			break;
568 		case '\t':
569 			goto break_out;
570 		case '\b':
571 			if (ldata->column > 0)
572 				ldata->column--;
573 			break;
574 		default:
575 			if (!iscntrl(c)) {
576 				if (O_OLCUC(tty))
577 					goto break_out;
578 				if (!is_continuation(c, tty))
579 					ldata->column++;
580 			}
581 			break;
582 		}
583 	}
584 break_out:
585 	i = tty->ops->write(tty, buf, i);
586 
587 	mutex_unlock(&ldata->output_lock);
588 	return i;
589 }
590 
591 /**
592  * __process_echoes	-	write pending echo characters
593  * @tty: terminal device
594  *
595  * Write previously buffered echo (and other ldisc-generated) characters to the
596  * tty.
597  *
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.
602  *
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.
606  *
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.
610  *
611  * Locking: callers must hold %output_lock.
612  */
613 static size_t __process_echoes(struct tty_struct *tty)
614 {
615 	struct n_tty_data *ldata = tty->disc_data;
616 	int	space, old_space;
617 	size_t tail;
618 	unsigned char c;
619 
620 	old_space = space = tty_write_room(tty);
621 
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) {
626 			unsigned char op;
627 			bool space_left = true;
628 
629 			/*
630 			 * Since add_echo_byte() is called without holding
631 			 * output_lock, we might see only portion of multi-byte
632 			 * operation.
633 			 */
634 			if (MASK(ldata->echo_commit) == MASK(tail + 1))
635 				goto not_yet_stored;
636 			/*
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.
640 			 */
641 			op = echo_buf(ldata, tail + 1);
642 
643 			switch (op) {
644 			case ECHO_OP_ERASE_TAB: {
645 				unsigned int num_chars, num_bs;
646 
647 				if (MASK(ldata->echo_commit) == MASK(tail + 2))
648 					goto not_yet_stored;
649 				num_chars = echo_buf(ldata, tail + 2);
650 
651 				/*
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.
660 				 */
661 				if (!(num_chars & 0x80))
662 					num_chars += ldata->canon_column;
663 				num_bs = 8 - (num_chars & 7);
664 
665 				if (num_bs > space) {
666 					space_left = false;
667 					break;
668 				}
669 				space -= num_bs;
670 				while (num_bs--) {
671 					tty_put_char(tty, '\b');
672 					if (ldata->column > 0)
673 						ldata->column--;
674 				}
675 				tail += 3;
676 				break;
677 			}
678 			case ECHO_OP_SET_CANON_COL:
679 				ldata->canon_column = ldata->column;
680 				tail += 2;
681 				break;
682 
683 			case ECHO_OP_MOVE_BACK_COL:
684 				if (ldata->column > 0)
685 					ldata->column--;
686 				tail += 2;
687 				break;
688 
689 			case ECHO_OP_START:
690 				/* This is an escaped echo op start code */
691 				if (!space) {
692 					space_left = false;
693 					break;
694 				}
695 				tty_put_char(tty, ECHO_OP_START);
696 				ldata->column++;
697 				space--;
698 				tail += 2;
699 				break;
700 
701 			default:
702 				/*
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.
709 				 *
710 				 */
711 				if (space < 2) {
712 					space_left = false;
713 					break;
714 				}
715 				tty_put_char(tty, '^');
716 				tty_put_char(tty, op ^ 0100);
717 				ldata->column += 2;
718 				space -= 2;
719 				tail += 2;
720 			}
721 
722 			if (!space_left)
723 				break;
724 		} else {
725 			if (O_OPOST(tty)) {
726 				int retval = do_output_char(c, tty, space);
727 				if (retval < 0)
728 					break;
729 				space -= retval;
730 			} else {
731 				if (!space)
732 					break;
733 				tty_put_char(tty, c);
734 				space -= 1;
735 			}
736 			tail += 1;
737 		}
738 	}
739 
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)
747 				tail += 3;
748 			else
749 				tail += 2;
750 		} else
751 			tail++;
752 	}
753 
754  not_yet_stored:
755 	ldata->echo_tail = tail;
756 	return old_space - space;
757 }
758 
759 static void commit_echoes(struct tty_struct *tty)
760 {
761 	struct n_tty_data *ldata = tty->disc_data;
762 	size_t nr, old, echoed;
763 	size_t head;
764 
765 	mutex_lock(&ldata->output_lock);
766 	head = ldata->echo_head;
767 	ldata->echo_mark = head;
768 	old = ldata->echo_commit - ldata->echo_tail;
769 
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);
777 		return;
778 	}
779 
780 	ldata->echo_commit = head;
781 	echoed = __process_echoes(tty);
782 	mutex_unlock(&ldata->output_lock);
783 
784 	if (echoed && tty->ops->flush_chars)
785 		tty->ops->flush_chars(tty);
786 }
787 
788 static void process_echoes(struct tty_struct *tty)
789 {
790 	struct n_tty_data *ldata = tty->disc_data;
791 	size_t echoed;
792 
793 	if (ldata->echo_mark == ldata->echo_tail)
794 		return;
795 
796 	mutex_lock(&ldata->output_lock);
797 	ldata->echo_commit = ldata->echo_mark;
798 	echoed = __process_echoes(tty);
799 	mutex_unlock(&ldata->output_lock);
800 
801 	if (echoed && tty->ops->flush_chars)
802 		tty->ops->flush_chars(tty);
803 }
804 
805 /* NB: echo_mark and echo_head should be equivalent here */
806 static void flush_echoes(struct tty_struct *tty)
807 {
808 	struct n_tty_data *ldata = tty->disc_data;
809 
810 	if ((!L_ECHO(tty) && !L_ECHONL(tty)) ||
811 	    ldata->echo_commit == ldata->echo_head)
812 		return;
813 
814 	mutex_lock(&ldata->output_lock);
815 	ldata->echo_commit = ldata->echo_head;
816 	__process_echoes(tty);
817 	mutex_unlock(&ldata->output_lock);
818 }
819 
820 /**
821  * add_echo_byte	-	add a byte to the echo buffer
822  * @c: unicode byte to echo
823  * @ldata: n_tty data
824  *
825  * Add a character or operation byte to the echo buffer.
826  */
827 static inline void add_echo_byte(unsigned char c, struct n_tty_data *ldata)
828 {
829 	*echo_buf_addr(ldata, ldata->echo_head) = c;
830 	smp_wmb(); /* Matches smp_rmb() in echo_buf(). */
831 	ldata->echo_head++;
832 }
833 
834 /**
835  * echo_move_back_col	-	add operation to move back a column
836  * @ldata: n_tty data
837  *
838  * Add an operation to the echo buffer to move back one column.
839  */
840 static void echo_move_back_col(struct n_tty_data *ldata)
841 {
842 	add_echo_byte(ECHO_OP_START, ldata);
843 	add_echo_byte(ECHO_OP_MOVE_BACK_COL, ldata);
844 }
845 
846 /**
847  * echo_set_canon_col	-	add operation to set the canon column
848  * @ldata: n_tty data
849  *
850  * Add an operation to the echo buffer to set the canon column to the current
851  * column.
852  */
853 static void echo_set_canon_col(struct n_tty_data *ldata)
854 {
855 	add_echo_byte(ECHO_OP_START, ldata);
856 	add_echo_byte(ECHO_OP_SET_CANON_COL, ldata);
857 }
858 
859 /**
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
863  * @ldata: n_tty data
864  *
865  * Add an operation to the echo buffer to erase a tab.
866  *
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.
871  */
872 static void echo_erase_tab(unsigned int num_chars, int after_tab,
873 			   struct n_tty_data *ldata)
874 {
875 	add_echo_byte(ECHO_OP_START, ldata);
876 	add_echo_byte(ECHO_OP_ERASE_TAB, ldata);
877 
878 	/* We only need to know this modulo 8 (tab spacing) */
879 	num_chars &= 7;
880 
881 	/* Set the high bit as a flag if num_chars is after a previous tab */
882 	if (after_tab)
883 		num_chars |= 0x80;
884 
885 	add_echo_byte(num_chars, ldata);
886 }
887 
888 /**
889  * echo_char_raw	-	echo a character raw
890  * @c: unicode byte to echo
891  * @ldata: line disc data
892  *
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.
895  *
896  * This variant does not treat control characters specially.
897  */
898 static void echo_char_raw(unsigned char c, struct n_tty_data *ldata)
899 {
900 	if (c == ECHO_OP_START) {
901 		add_echo_byte(ECHO_OP_START, ldata);
902 		add_echo_byte(ECHO_OP_START, ldata);
903 	} else {
904 		add_echo_byte(c, ldata);
905 	}
906 }
907 
908 /**
909  * echo_char		-	echo a character
910  * @c: unicode byte to echo
911  * @tty: terminal device
912  *
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.
915  *
916  * This variant tags control characters to be echoed as "^X" (where X is the
917  * letter representing the control char).
918  */
919 static void echo_char(unsigned char c, struct tty_struct *tty)
920 {
921 	struct n_tty_data *ldata = tty->disc_data;
922 
923 	if (c == ECHO_OP_START) {
924 		add_echo_byte(ECHO_OP_START, ldata);
925 		add_echo_byte(ECHO_OP_START, ldata);
926 	} else {
927 		if (L_ECHOCTL(tty) && iscntrl(c) && c != '\t')
928 			add_echo_byte(ECHO_OP_START, ldata);
929 		add_echo_byte(c, ldata);
930 	}
931 }
932 
933 /**
934  * finish_erasing	-	complete erase
935  * @ldata: n_tty data
936  */
937 static inline void finish_erasing(struct n_tty_data *ldata)
938 {
939 	if (ldata->erasing) {
940 		echo_char_raw('/', ldata);
941 		ldata->erasing = 0;
942 	}
943 }
944 
945 /**
946  * eraser		-	handle erase function
947  * @c: character input
948  * @tty: terminal device
949  *
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
952  * symbols.
953  *
954  * Locking: n_tty_receive_buf()/producer path:
955  *	caller holds non-exclusive %termios_rwsem
956  */
957 static void eraser(unsigned char c, struct tty_struct *tty)
958 {
959 	struct n_tty_data *ldata = tty->disc_data;
960 	enum { ERASE, WERASE, KILL } kill_type;
961 	size_t head;
962 	size_t cnt;
963 	int seen_alnums;
964 
965 	if (ldata->read_head == ldata->canon_head) {
966 		/* process_output('\a', tty); */ /* what do you think? */
967 		return;
968 	}
969 	if (c == ERASE_CHAR(tty))
970 		kill_type = ERASE;
971 	else if (c == WERASE_CHAR(tty))
972 		kill_type = WERASE;
973 	else {
974 		if (!L_ECHO(tty)) {
975 			ldata->read_head = ldata->canon_head;
976 			return;
977 		}
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. */
983 			if (L_ECHOK(tty))
984 				echo_char_raw('\n', ldata);
985 			return;
986 		}
987 		kill_type = KILL;
988 	}
989 
990 	seen_alnums = 0;
991 	while (MASK(ldata->read_head) != MASK(ldata->canon_head)) {
992 		head = ldata->read_head;
993 
994 		/* erase a single possibly multibyte character */
995 		do {
996 			head--;
997 			c = read_buf(ldata, head);
998 		} while (is_continuation(c, tty) &&
999 			 MASK(head) != MASK(ldata->canon_head));
1000 
1001 		/* do not partially erase */
1002 		if (is_continuation(c, tty))
1003 			break;
1004 
1005 		if (kill_type == WERASE) {
1006 			/* Equivalent to BSD's ALTWERASE. */
1007 			if (isalnum(c) || c == '_')
1008 				seen_alnums++;
1009 			else if (seen_alnums)
1010 				break;
1011 		}
1012 		cnt = ldata->read_head - head;
1013 		ldata->read_head = head;
1014 		if (L_ECHO(tty)) {
1015 			if (L_ECHOPRT(tty)) {
1016 				if (!ldata->erasing) {
1017 					echo_char_raw('\\', ldata);
1018 					ldata->erasing = 1;
1019 				}
1020 				/* if cnt > 1, output a multi-byte character */
1021 				echo_char(c, tty);
1022 				while (--cnt > 0) {
1023 					head++;
1024 					echo_char_raw(read_buf(ldata, head), ldata);
1025 					echo_move_back_col(ldata);
1026 				}
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;
1031 				int after_tab = 0;
1032 				size_t tail = ldata->read_head;
1033 
1034 				/*
1035 				 * Count the columns used for characters
1036 				 * since the start of input or after a
1037 				 * previous tab.
1038 				 * This info is used to go back the correct
1039 				 * number of columns.
1040 				 */
1041 				while (MASK(tail) != MASK(ldata->canon_head)) {
1042 					tail--;
1043 					c = read_buf(ldata, tail);
1044 					if (c == '\t') {
1045 						after_tab = 1;
1046 						break;
1047 					} else if (iscntrl(c)) {
1048 						if (L_ECHOCTL(tty))
1049 							num_chars += 2;
1050 					} else if (!is_continuation(c, tty)) {
1051 						num_chars++;
1052 					}
1053 				}
1054 				echo_erase_tab(num_chars, after_tab, ldata);
1055 			} else {
1056 				if (iscntrl(c) && L_ECHOCTL(tty)) {
1057 					echo_char_raw('\b', ldata);
1058 					echo_char_raw(' ', ldata);
1059 					echo_char_raw('\b', ldata);
1060 				}
1061 				if (!iscntrl(c) || L_ECHOCTL(tty)) {
1062 					echo_char_raw('\b', ldata);
1063 					echo_char_raw(' ', ldata);
1064 					echo_char_raw('\b', ldata);
1065 				}
1066 			}
1067 		}
1068 		if (kill_type == ERASE)
1069 			break;
1070 	}
1071 	if (ldata->read_head == ldata->canon_head && L_ECHO(tty))
1072 		finish_erasing(ldata);
1073 }
1074 
1075 
1076 static void __isig(int sig, struct tty_struct *tty)
1077 {
1078 	struct pid *tty_pgrp = tty_get_pgrp(tty);
1079 	if (tty_pgrp) {
1080 		kill_pgrp(tty_pgrp, sig, 1);
1081 		put_pid(tty_pgrp);
1082 	}
1083 }
1084 
1085 /**
1086  * isig			-	handle the ISIG optio
1087  * @sig: signal
1088  * @tty: terminal
1089  *
1090  * Called when a signal is being sent due to terminal input. Called from the
1091  * &tty_driver.receive_buf() path, so serialized.
1092  *
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.
1096  *
1097  * Locking: %ctrl.lock
1098  */
1099 static void isig(int sig, struct tty_struct *tty)
1100 {
1101 	struct n_tty_data *ldata = tty->disc_data;
1102 
1103 	if (L_NOFLSH(tty)) {
1104 		/* signal only */
1105 		__isig(sig, tty);
1106 
1107 	} else { /* signal and flush */
1108 		up_read(&tty->termios_rwsem);
1109 		down_write(&tty->termios_rwsem);
1110 
1111 		__isig(sig, tty);
1112 
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);
1118 
1119 		/* clear output buffer */
1120 		tty_driver_flush_buffer(tty);
1121 
1122 		/* clear input buffer */
1123 		reset_buffer_flags(tty->disc_data);
1124 
1125 		/* notify pty master of flush */
1126 		if (tty->link)
1127 			n_tty_packet_mode_flush(tty);
1128 
1129 		up_write(&tty->termios_rwsem);
1130 		down_read(&tty->termios_rwsem);
1131 	}
1132 }
1133 
1134 /**
1135  * n_tty_receive_break	-	handle break
1136  * @tty: terminal
1137  *
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.
1140  *
1141  * Locking: n_tty_receive_buf()/producer path:
1142  *	caller holds non-exclusive termios_rwsem
1143  *
1144  * Note: may get exclusive %termios_rwsem if flushing input buffer
1145  */
1146 static void n_tty_receive_break(struct tty_struct *tty)
1147 {
1148 	struct n_tty_data *ldata = tty->disc_data;
1149 
1150 	if (I_IGNBRK(tty))
1151 		return;
1152 	if (I_BRKINT(tty)) {
1153 		isig(SIGINT, tty);
1154 		return;
1155 	}
1156 	if (I_PARMRK(tty)) {
1157 		put_tty_queue('\377', ldata);
1158 		put_tty_queue('\0', ldata);
1159 	}
1160 	put_tty_queue('\0', ldata);
1161 }
1162 
1163 /**
1164  * n_tty_receive_overrun	-	handle overrun reporting
1165  * @tty: terminal
1166  *
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.
1169  *
1170  * Called from the receive_buf path so single threaded. Does not need locking
1171  * as num_overrun and overrun_time are function private.
1172  */
1173 static void n_tty_receive_overrun(struct tty_struct *tty)
1174 {
1175 	struct n_tty_data *ldata = tty->disc_data;
1176 
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;
1183 	}
1184 }
1185 
1186 /**
1187  * n_tty_receive_parity_error	-	error notifier
1188  * @tty: terminal device
1189  * @c: character
1190  *
1191  * Process a parity error and queue the right data to indicate the error case
1192  * if necessary.
1193  *
1194  * Locking: n_tty_receive_buf()/producer path:
1195  * 	caller holds non-exclusive %termios_rwsem
1196  */
1197 static void n_tty_receive_parity_error(struct tty_struct *tty, unsigned char c)
1198 {
1199 	struct n_tty_data *ldata = tty->disc_data;
1200 
1201 	if (I_INPCK(tty)) {
1202 		if (I_IGNPAR(tty))
1203 			return;
1204 		if (I_PARMRK(tty)) {
1205 			put_tty_queue('\377', ldata);
1206 			put_tty_queue('\0', ldata);
1207 			put_tty_queue(c, ldata);
1208 		} else
1209 			put_tty_queue('\0', ldata);
1210 	} else
1211 		put_tty_queue(c, ldata);
1212 }
1213 
1214 static void
1215 n_tty_receive_signal_char(struct tty_struct *tty, int signal, unsigned char c)
1216 {
1217 	isig(signal, tty);
1218 	if (I_IXON(tty))
1219 		start_tty(tty);
1220 	if (L_ECHO(tty)) {
1221 		echo_char(c, tty);
1222 		commit_echoes(tty);
1223 	} else
1224 		process_echoes(tty);
1225 }
1226 
1227 static bool n_tty_is_char_flow_ctrl(struct tty_struct *tty, unsigned char c)
1228 {
1229 	return c == START_CHAR(tty) || c == STOP_CHAR(tty);
1230 }
1231 
1232 /**
1233  * n_tty_receive_char_flow_ctrl - receive flow control chars
1234  * @tty: terminal device
1235  * @c: character
1236  * @lookahead_done: lookahead has processed this character already
1237  *
1238  * Receive and process flow control character actions.
1239  *
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
1242  * receive.
1243  *
1244  * Returns true if @c is consumed as flow-control character, the character
1245  * must not be treated as normal character.
1246  */
1247 static bool n_tty_receive_char_flow_ctrl(struct tty_struct *tty, unsigned char c,
1248 					 bool lookahead_done)
1249 {
1250 	if (!n_tty_is_char_flow_ctrl(tty, c))
1251 		return false;
1252 
1253 	if (lookahead_done)
1254 		return true;
1255 
1256 	if (c == START_CHAR(tty)) {
1257 		start_tty(tty);
1258 		process_echoes(tty);
1259 		return true;
1260 	}
1261 
1262 	/* STOP_CHAR */
1263 	stop_tty(tty);
1264 	return true;
1265 }
1266 
1267 static void n_tty_receive_char_special(struct tty_struct *tty, unsigned char c,
1268 				       bool lookahead_done)
1269 {
1270 	struct n_tty_data *ldata = tty->disc_data;
1271 
1272 	if (I_IXON(tty) && n_tty_receive_char_flow_ctrl(tty, c, lookahead_done))
1273 		return;
1274 
1275 	if (L_ISIG(tty)) {
1276 		if (c == INTR_CHAR(tty)) {
1277 			n_tty_receive_signal_char(tty, SIGINT, c);
1278 			return;
1279 		} else if (c == QUIT_CHAR(tty)) {
1280 			n_tty_receive_signal_char(tty, SIGQUIT, c);
1281 			return;
1282 		} else if (c == SUSP_CHAR(tty)) {
1283 			n_tty_receive_signal_char(tty, SIGTSTP, c);
1284 			return;
1285 		}
1286 	}
1287 
1288 	if (tty->flow.stopped && !tty->flow.tco_stopped && I_IXON(tty) && I_IXANY(tty)) {
1289 		start_tty(tty);
1290 		process_echoes(tty);
1291 	}
1292 
1293 	if (c == '\r') {
1294 		if (I_IGNCR(tty))
1295 			return;
1296 		if (I_ICRNL(tty))
1297 			c = '\n';
1298 	} else if (c == '\n' && I_INLCR(tty))
1299 		c = '\r';
1300 
1301 	if (ldata->icanon) {
1302 		if (c == ERASE_CHAR(tty) || c == KILL_CHAR(tty) ||
1303 		    (c == WERASE_CHAR(tty) && L_IEXTEN(tty))) {
1304 			eraser(c, tty);
1305 			commit_echoes(tty);
1306 			return;
1307 		}
1308 		if (c == LNEXT_CHAR(tty) && L_IEXTEN(tty)) {
1309 			ldata->lnext = 1;
1310 			if (L_ECHO(tty)) {
1311 				finish_erasing(ldata);
1312 				if (L_ECHOCTL(tty)) {
1313 					echo_char_raw('^', ldata);
1314 					echo_char_raw('\b', ldata);
1315 					commit_echoes(tty);
1316 				}
1317 			}
1318 			return;
1319 		}
1320 		if (c == REPRINT_CHAR(tty) && L_ECHO(tty) && L_IEXTEN(tty)) {
1321 			size_t tail = ldata->canon_head;
1322 
1323 			finish_erasing(ldata);
1324 			echo_char(c, tty);
1325 			echo_char_raw('\n', ldata);
1326 			while (MASK(tail) != MASK(ldata->read_head)) {
1327 				echo_char(read_buf(ldata, tail), tty);
1328 				tail++;
1329 			}
1330 			commit_echoes(tty);
1331 			return;
1332 		}
1333 		if (c == '\n') {
1334 			if (L_ECHO(tty) || L_ECHONL(tty)) {
1335 				echo_char_raw('\n', ldata);
1336 				commit_echoes(tty);
1337 			}
1338 			goto handle_newline;
1339 		}
1340 		if (c == EOF_CHAR(tty)) {
1341 			c = __DISABLED_CHAR;
1342 			goto handle_newline;
1343 		}
1344 		if ((c == EOL_CHAR(tty)) ||
1345 		    (c == EOL2_CHAR(tty) && L_IEXTEN(tty))) {
1346 			/*
1347 			 * XXX are EOL_CHAR and EOL2_CHAR echoed?!?
1348 			 */
1349 			if (L_ECHO(tty)) {
1350 				/* Record the column of first canon char. */
1351 				if (ldata->canon_head == ldata->read_head)
1352 					echo_set_canon_col(ldata);
1353 				echo_char(c, tty);
1354 				commit_echoes(tty);
1355 			}
1356 			/*
1357 			 * XXX does PARMRK doubling happen for
1358 			 * EOL_CHAR and EOL2_CHAR?
1359 			 */
1360 			if (c == (unsigned char) '\377' && I_PARMRK(tty))
1361 				put_tty_queue(c, ldata);
1362 
1363 handle_newline:
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);
1369 			return;
1370 		}
1371 	}
1372 
1373 	if (L_ECHO(tty)) {
1374 		finish_erasing(ldata);
1375 		if (c == '\n')
1376 			echo_char_raw('\n', ldata);
1377 		else {
1378 			/* Record the column of first canon char. */
1379 			if (ldata->canon_head == ldata->read_head)
1380 				echo_set_canon_col(ldata);
1381 			echo_char(c, tty);
1382 		}
1383 		commit_echoes(tty);
1384 	}
1385 
1386 	/* PARMRK doubling check */
1387 	if (c == (unsigned char) '\377' && I_PARMRK(tty))
1388 		put_tty_queue(c, ldata);
1389 
1390 	put_tty_queue(c, ldata);
1391 }
1392 
1393 /**
1394  * n_tty_receive_char	-	perform processing
1395  * @tty: terminal device
1396  * @c: character
1397  *
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.
1400  *
1401  * Locking: n_tty_receive_buf()/producer path:
1402  *	caller holds non-exclusive %termios_rwsem
1403  *	publishes canon_head if canonical mode is active
1404  */
1405 static void n_tty_receive_char(struct tty_struct *tty, unsigned char c)
1406 {
1407 	struct n_tty_data *ldata = tty->disc_data;
1408 
1409 	if (tty->flow.stopped && !tty->flow.tco_stopped && I_IXON(tty) && I_IXANY(tty)) {
1410 		start_tty(tty);
1411 		process_echoes(tty);
1412 	}
1413 	if (L_ECHO(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);
1418 		echo_char(c, tty);
1419 		commit_echoes(tty);
1420 	}
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);
1425 }
1426 
1427 static void n_tty_receive_char_closing(struct tty_struct *tty, unsigned char c,
1428 				       bool lookahead_done)
1429 {
1430 	if (I_ISTRIP(tty))
1431 		c &= 0x7f;
1432 	if (I_IUCLC(tty) && L_IEXTEN(tty))
1433 		c = tolower(c);
1434 
1435 	if (I_IXON(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)) {
1440 			start_tty(tty);
1441 			process_echoes(tty);
1442 		}
1443 	}
1444 }
1445 
1446 static void
1447 n_tty_receive_char_flagged(struct tty_struct *tty, unsigned char c, char flag)
1448 {
1449 	switch (flag) {
1450 	case TTY_BREAK:
1451 		n_tty_receive_break(tty);
1452 		break;
1453 	case TTY_PARITY:
1454 	case TTY_FRAME:
1455 		n_tty_receive_parity_error(tty, c);
1456 		break;
1457 	case TTY_OVERRUN:
1458 		n_tty_receive_overrun(tty);
1459 		break;
1460 	default:
1461 		tty_err(tty, "unknown flag %d\n", flag);
1462 		break;
1463 	}
1464 }
1465 
1466 static void
1467 n_tty_receive_char_lnext(struct tty_struct *tty, unsigned char c, char flag)
1468 {
1469 	struct n_tty_data *ldata = tty->disc_data;
1470 
1471 	ldata->lnext = 0;
1472 	if (likely(flag == TTY_NORMAL)) {
1473 		if (I_ISTRIP(tty))
1474 			c &= 0x7f;
1475 		if (I_IUCLC(tty) && L_IEXTEN(tty))
1476 			c = tolower(c);
1477 		n_tty_receive_char(tty, c);
1478 	} else
1479 		n_tty_receive_char_flagged(tty, c, flag);
1480 }
1481 
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)
1485 {
1486 	struct n_tty_data *ldata = tty->disc_data;
1487 	unsigned char flag = TTY_NORMAL;
1488 
1489 	ldata->lookahead_count += count;
1490 
1491 	if (!I_IXON(tty))
1492 		return;
1493 
1494 	while (count--) {
1495 		if (fp)
1496 			flag = *fp++;
1497 		if (likely(flag == TTY_NORMAL))
1498 			n_tty_receive_char_flow_ctrl(tty, *cp, false);
1499 		cp++;
1500 	}
1501 }
1502 
1503 static void
1504 n_tty_receive_buf_real_raw(struct tty_struct *tty, const unsigned char *cp,
1505 			   const char *fp, int count)
1506 {
1507 	struct n_tty_data *ldata = tty->disc_data;
1508 	size_t n, head;
1509 
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;
1514 	cp += n;
1515 	count -= n;
1516 
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;
1521 }
1522 
1523 static void
1524 n_tty_receive_buf_raw(struct tty_struct *tty, const unsigned char *cp,
1525 		      const char *fp, int count)
1526 {
1527 	struct n_tty_data *ldata = tty->disc_data;
1528 	char flag = TTY_NORMAL;
1529 
1530 	while (count--) {
1531 		if (fp)
1532 			flag = *fp++;
1533 		if (likely(flag == TTY_NORMAL))
1534 			put_tty_queue(*cp++, ldata);
1535 		else
1536 			n_tty_receive_char_flagged(tty, *cp++, flag);
1537 	}
1538 }
1539 
1540 static void
1541 n_tty_receive_buf_closing(struct tty_struct *tty, const unsigned char *cp,
1542 			  const char *fp, int count, bool lookahead_done)
1543 {
1544 	char flag = TTY_NORMAL;
1545 
1546 	while (count--) {
1547 		if (fp)
1548 			flag = *fp++;
1549 		if (likely(flag == TTY_NORMAL))
1550 			n_tty_receive_char_closing(tty, *cp++, lookahead_done);
1551 	}
1552 }
1553 
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)
1556 {
1557 	struct n_tty_data *ldata = tty->disc_data;
1558 	char flag = TTY_NORMAL;
1559 
1560 	while (count--) {
1561 		unsigned char c = *cp++;
1562 
1563 		if (fp)
1564 			flag = *fp++;
1565 
1566 		if (ldata->lnext) {
1567 			n_tty_receive_char_lnext(tty, c, flag);
1568 			continue;
1569 		}
1570 
1571 		if (unlikely(flag != TTY_NORMAL)) {
1572 			n_tty_receive_char_flagged(tty, c, flag);
1573 			continue;
1574 		}
1575 
1576 		if (I_ISTRIP(tty))
1577 			c &= 0x7f;
1578 		if (I_IUCLC(tty) && L_IEXTEN(tty))
1579 			c = tolower(c);
1580 		if (L_EXTPROC(tty)) {
1581 			put_tty_queue(c, ldata);
1582 			continue;
1583 		}
1584 
1585 		if (test_bit(c, ldata->char_map))
1586 			n_tty_receive_char_special(tty, c, lookahead_done);
1587 		else
1588 			n_tty_receive_char(tty, c);
1589 	}
1590 }
1591 
1592 static void __receive_buf(struct tty_struct *tty, const unsigned char *cp,
1593 			  const char *fp, int count)
1594 {
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);
1598 
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)) {
1604 		if (la_count > 0)
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);
1608 	} else {
1609 		if (la_count > 0)
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);
1613 
1614 		flush_echoes(tty);
1615 		if (tty->ops->flush_chars)
1616 			tty->ops->flush_chars(tty);
1617 	}
1618 
1619 	ldata->lookahead_count -= la_count;
1620 
1621 	if (ldata->icanon && !L_EXTPROC(tty))
1622 		return;
1623 
1624 	/* publish read_head to consumer */
1625 	smp_store_release(&ldata->commit_head, ldata->read_head);
1626 
1627 	if (read_cnt(ldata)) {
1628 		kill_fasync(&tty->fasync, SIGIO, POLL_IN);
1629 		wake_up_interruptible_poll(&tty->read_wait, EPOLLIN | EPOLLRDNORM);
1630 	}
1631 }
1632 
1633 /**
1634  * n_tty_receive_buf_common	-	process input
1635  * @tty: device to receive input
1636  * @cp: input chars
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
1640  *
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()).
1645  *
1646  * Returns: the # of input chars from @cp which were processed.
1647  *
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
1652  * read.
1653  *
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.
1657  *
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.
1661  *
1662  * Locking: n_tty_receive_buf()/producer path:
1663  *	claims non-exclusive %termios_rwsem
1664  *	publishes commit_head or canon_head
1665  */
1666 static int
1667 n_tty_receive_buf_common(struct tty_struct *tty, const unsigned char *cp,
1668 			 const char *fp, int count, int flow)
1669 {
1670 	struct n_tty_data *ldata = tty->disc_data;
1671 	int room, n, rcvd = 0, overflow;
1672 
1673 	down_read(&tty->termios_rwsem);
1674 
1675 	do {
1676 		/*
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
1679 		 *
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.
1684 		 *
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)
1688 		 */
1689 		size_t tail = smp_load_acquire(&ldata->read_tail);
1690 
1691 		room = N_TTY_BUF_SIZE - (ldata->read_head - tail);
1692 		if (I_PARMRK(tty))
1693 			room = DIV_ROUND_UP(room, 3);
1694 		room--;
1695 		if (room <= 0) {
1696 			overflow = ldata->icanon && ldata->canon_head == tail;
1697 			if (overflow && room < 0)
1698 				ldata->read_head--;
1699 			room = overflow;
1700 			WRITE_ONCE(ldata->no_room, flow && !room);
1701 		} else
1702 			overflow = 0;
1703 
1704 		n = min(count, room);
1705 		if (!n)
1706 			break;
1707 
1708 		/* ignore parity errors if handling overflow */
1709 		if (!overflow || !fp || *fp != TTY_PARITY)
1710 			__receive_buf(tty, cp, fp, n);
1711 
1712 		cp += n;
1713 		if (fp)
1714 			fp += n;
1715 		count -= n;
1716 		rcvd += n;
1717 	} while (!test_bit(TTY_LDISC_CHANGING, &tty->flags));
1718 
1719 	tty->receive_room = room;
1720 
1721 	/* Unthrottle if handling overflow on pty */
1722 	if (tty->driver->type == TTY_DRIVER_TYPE_PTY) {
1723 		if (overflow) {
1724 			tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE);
1725 			tty_unthrottle_safe(tty);
1726 			__tty_set_flow_change(tty, 0);
1727 		}
1728 	} else
1729 		n_tty_check_throttle(tty);
1730 
1731 	if (unlikely(ldata->no_room)) {
1732 		/*
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.
1736 		 */
1737 		smp_mb();
1738 		if (!chars_in_buffer(tty))
1739 			n_tty_kick_worker(tty);
1740 	}
1741 
1742 	up_read(&tty->termios_rwsem);
1743 
1744 	return rcvd;
1745 }
1746 
1747 static void n_tty_receive_buf(struct tty_struct *tty, const unsigned char *cp,
1748 			      const char *fp, int count)
1749 {
1750 	n_tty_receive_buf_common(tty, cp, fp, count, 0);
1751 }
1752 
1753 static int n_tty_receive_buf2(struct tty_struct *tty, const unsigned char *cp,
1754 			      const char *fp, int count)
1755 {
1756 	return n_tty_receive_buf_common(tty, cp, fp, count, 1);
1757 }
1758 
1759 /**
1760  * n_tty_set_termios	-	termios data changed
1761  * @tty: terminal
1762  * @old: previous data
1763  *
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.
1768  *
1769  * Locking: Caller holds @tty->termios_rwsem
1770  */
1771 static void n_tty_set_termios(struct tty_struct *tty, const struct ktermios *old)
1772 {
1773 	struct n_tty_data *ldata = tty->disc_data;
1774 
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;
1780 			ldata->push = 0;
1781 		} else {
1782 			set_bit((ldata->read_head - 1) & (N_TTY_BUF_SIZE - 1),
1783 				ldata->read_flags);
1784 			ldata->canon_head = ldata->read_head;
1785 			ldata->push = 1;
1786 		}
1787 		ldata->commit_head = ldata->read_head;
1788 		ldata->erasing = 0;
1789 		ldata->lnext = 0;
1790 	}
1791 
1792 	ldata->icanon = (L_ICANON(tty) != 0);
1793 
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) ||
1797 	    I_PARMRK(tty)) {
1798 		bitmap_zero(ldata->char_map, 256);
1799 
1800 		if (I_IGNCR(tty) || I_ICRNL(tty))
1801 			set_bit('\r', ldata->char_map);
1802 		if (I_INLCR(tty))
1803 			set_bit('\n', ldata->char_map);
1804 
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);
1815 				if (L_ECHO(tty))
1816 					set_bit(REPRINT_CHAR(tty),
1817 						ldata->char_map);
1818 			}
1819 		}
1820 		if (I_IXON(tty)) {
1821 			set_bit(START_CHAR(tty), ldata->char_map);
1822 			set_bit(STOP_CHAR(tty), ldata->char_map);
1823 		}
1824 		if (L_ISIG(tty)) {
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);
1828 		}
1829 		clear_bit(__DISABLED_CHAR, ldata->char_map);
1830 		ldata->raw = 0;
1831 		ldata->real_raw = 0;
1832 	} else {
1833 		ldata->raw = 1;
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;
1838 		else
1839 			ldata->real_raw = 0;
1840 	}
1841 	/*
1842 	 * Fix tty hang when I_IXON(tty) is cleared, but the tty
1843 	 * been stopped by STOP_CHAR(tty) before it.
1844 	 */
1845 	if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow.tco_stopped) {
1846 		start_tty(tty);
1847 		process_echoes(tty);
1848 	}
1849 
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);
1853 }
1854 
1855 /**
1856  * n_tty_close		-	close the ldisc for this tty
1857  * @tty: device
1858  *
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.
1862  */
1863 static void n_tty_close(struct tty_struct *tty)
1864 {
1865 	struct n_tty_data *ldata = tty->disc_data;
1866 
1867 	if (tty->link)
1868 		n_tty_packet_mode_flush(tty);
1869 
1870 	down_write(&tty->termios_rwsem);
1871 	vfree(ldata);
1872 	tty->disc_data = NULL;
1873 	up_write(&tty->termios_rwsem);
1874 }
1875 
1876 /**
1877  * n_tty_open		-	open an ldisc
1878  * @tty: terminal to open
1879  *
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.
1883  */
1884 static int n_tty_open(struct tty_struct *tty)
1885 {
1886 	struct n_tty_data *ldata;
1887 
1888 	/* Currently a malloc failure here can panic */
1889 	ldata = vzalloc(sizeof(*ldata));
1890 	if (!ldata)
1891 		return -ENOMEM;
1892 
1893 	ldata->overrun_time = jiffies;
1894 	mutex_init(&ldata->atomic_read_lock);
1895 	mutex_init(&ldata->output_lock);
1896 
1897 	tty->disc_data = ldata;
1898 	tty->closing = 0;
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);
1903 	return 0;
1904 }
1905 
1906 static inline int input_available_p(struct tty_struct *tty, int poll)
1907 {
1908 	struct n_tty_data *ldata = tty->disc_data;
1909 	int amt = poll && !TIME_CHAR(tty) && MIN_CHAR(tty) ? MIN_CHAR(tty) : 1;
1910 
1911 	if (ldata->icanon && !L_EXTPROC(tty))
1912 		return ldata->canon_head != ldata->read_tail;
1913 	else
1914 		return ldata->commit_head - ldata->read_tail >= amt;
1915 }
1916 
1917 /**
1918  * copy_from_read_buf	-	copy read data directly
1919  * @tty: terminal device
1920  * @kbp: data
1921  * @nr: size of data
1922  *
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.
1925  *
1926  * Returns: true if it successfully copied data, but there is still more data
1927  * to be had.
1928  *
1929  * Locking:
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
1934  */
1935 static bool copy_from_read_buf(struct tty_struct *tty,
1936 				      unsigned char **kbp,
1937 				      size_t *nr)
1938 
1939 {
1940 	struct n_tty_data *ldata = tty->disc_data;
1941 	size_t n;
1942 	bool is_eof;
1943 	size_t head = smp_load_acquire(&ldata->commit_head);
1944 	size_t tail = ldata->read_tail & (N_TTY_BUF_SIZE - 1);
1945 
1946 	n = min(head - ldata->read_tail, N_TTY_BUF_SIZE - tail);
1947 	n = min(*nr, n);
1948 	if (n) {
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))
1958 			return false;
1959 		*kbp += n;
1960 		*nr -= n;
1961 
1962 		/* If we have more to copy, let the caller know */
1963 		return head != ldata->read_tail;
1964 	}
1965 	return false;
1966 }
1967 
1968 /**
1969  * canon_copy_from_read_buf	-	copy read data in canonical mode
1970  * @tty: terminal device
1971  * @kbp: data
1972  * @nr: size of data
1973  *
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.
1977  *
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.
1983  *
1984  * Locking:
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
1989  */
1990 static bool canon_copy_from_read_buf(struct tty_struct *tty,
1991 				     unsigned char **kbp,
1992 				     size_t *nr)
1993 {
1994 	struct n_tty_data *ldata = tty->disc_data;
1995 	size_t n, size, more, c;
1996 	size_t eol;
1997 	size_t tail, canon_head;
1998 	int found = 0;
1999 
2000 	/* N.B. avoid overrun if nr == 0 */
2001 	if (!*nr)
2002 		return false;
2003 
2004 	canon_head = smp_load_acquire(&ldata->canon_head);
2005 	n = min(*nr, canon_head - ldata->read_tail);
2006 
2007 	tail = ldata->read_tail & (N_TTY_BUF_SIZE - 1);
2008 	size = min_t(size_t, tail + n, N_TTY_BUF_SIZE);
2009 
2010 	n_tty_trace("%s: nr:%zu tail:%zu n:%zu size:%zu\n",
2011 		    __func__, *nr, tail, n, size);
2012 
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;
2019 	} else
2020 		found = eol != size;
2021 
2022 	n = eol - tail;
2023 	if (n > N_TTY_BUF_SIZE)
2024 		n += N_TTY_BUF_SIZE;
2025 	c = n + found;
2026 
2027 	if (!found || read_buf(ldata, eol) != __DISABLED_CHAR)
2028 		n = c;
2029 
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);
2032 
2033 	tty_copy(tty, *kbp, tail, n);
2034 	*kbp += n;
2035 	*nr -= n;
2036 
2037 	if (found)
2038 		clear_bit(eol, ldata->read_flags);
2039 	smp_store_release(&ldata->read_tail, ldata->read_tail + c);
2040 
2041 	if (found) {
2042 		if (!ldata->push)
2043 			ldata->line_start = ldata->read_tail;
2044 		else
2045 			ldata->push = 0;
2046 		tty_audit_push();
2047 		return false;
2048 	}
2049 
2050 	/* No EOL found - do a continuation retry if there is more data */
2051 	return ldata->read_tail != canon_head;
2052 }
2053 
2054 /*
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.
2058  */
2059 static void canon_skip_eof(struct tty_struct *tty)
2060 {
2061 	struct n_tty_data *ldata = tty->disc_data;
2062 	size_t tail, canon_head;
2063 
2064 	canon_head = smp_load_acquire(&ldata->canon_head);
2065 	tail = ldata->read_tail;
2066 
2067 	// No data?
2068 	if (tail == canon_head)
2069 		return;
2070 
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))
2074 		return;
2075 	if (read_buf(ldata, tail) != __DISABLED_CHAR)
2076 		return;
2077 
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);
2081 }
2082 
2083 /**
2084  * job_control		-	check job control
2085  * @tty: tty
2086  * @file: file handle
2087  *
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.
2091  *
2092  * Locking:
2093  *  * redirected write test is safe
2094  *  * current->signal->tty check is safe
2095  *  * ctrl.lock to safely reference @tty->ctrl.pgrp
2096  */
2097 static int job_control(struct tty_struct *tty, struct file *file)
2098 {
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)
2105 		return 0;
2106 
2107 	return __tty_check_change(tty, SIGTTIN);
2108 }
2109 
2110 
2111 /**
2112  * n_tty_read		-	read function for tty
2113  * @tty: tty device
2114  * @file: file object
2115  * @kbuf: kernelspace buffer pointer
2116  * @nr: size of I/O
2117  * @cookie: if non-%NULL, this is a continuation read
2118  * @offset: where to continue reading from (unused in n_tty)
2119  *
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.
2124  *
2125  * This code must be sure never to sleep through a hangup.
2126  *
2127  * Locking: n_tty_read()/consumer path:
2128  *	claims non-exclusive termios_rwsem;
2129  *	publishes read_tail
2130  */
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)
2134 {
2135 	struct n_tty_data *ldata = tty->disc_data;
2136 	unsigned char *kb = kbuf;
2137 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
2138 	int c;
2139 	int minimum, time;
2140 	ssize_t retval = 0;
2141 	long timeout;
2142 	bool packet;
2143 	size_t old_tail;
2144 
2145 	/*
2146 	 * Is this a continuation of a read started earler?
2147 	 *
2148 	 * If so, we still hold the atomic_read_lock and the
2149 	 * termios_rwsem, and can just continue to copy data.
2150 	 */
2151 	if (*cookie) {
2152 		if (ldata->icanon && !L_EXTPROC(tty)) {
2153 			/*
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.
2157 			 */
2158 			if (!nr)
2159 				canon_skip_eof(tty);
2160 			else if (canon_copy_from_read_buf(tty, &kb, &nr))
2161 				return kb - kbuf;
2162 		} else {
2163 			if (copy_from_read_buf(tty, &kb, &nr))
2164 				return kb - kbuf;
2165 		}
2166 
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);
2172 		*cookie = NULL;
2173 		return kb - kbuf;
2174 	}
2175 
2176 	c = job_control(tty, file);
2177 	if (c < 0)
2178 		return c;
2179 
2180 	/*
2181 	 *	Internal serialization of reads.
2182 	 */
2183 	if (file->f_flags & O_NONBLOCK) {
2184 		if (!mutex_trylock(&ldata->atomic_read_lock))
2185 			return -EAGAIN;
2186 	} else {
2187 		if (mutex_lock_interruptible(&ldata->atomic_read_lock))
2188 			return -ERESTARTSYS;
2189 	}
2190 
2191 	down_read(&tty->termios_rwsem);
2192 
2193 	minimum = time = 0;
2194 	timeout = MAX_SCHEDULE_TIMEOUT;
2195 	if (!ldata->icanon) {
2196 		minimum = MIN_CHAR(tty);
2197 		if (minimum) {
2198 			time = (HZ / 10) * TIME_CHAR(tty);
2199 		} else {
2200 			timeout = (HZ / 10) * TIME_CHAR(tty);
2201 			minimum = 1;
2202 		}
2203 	}
2204 
2205 	packet = tty->ctrl.packet;
2206 	old_tail = ldata->read_tail;
2207 
2208 	add_wait_queue(&tty->read_wait, &wait);
2209 	while (nr) {
2210 		/* First test for status change. */
2211 		if (packet && tty->link->ctrl.pktstatus) {
2212 			unsigned char cs;
2213 			if (kb != kbuf)
2214 				break;
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);
2219 			*kb++ = cs;
2220 			nr--;
2221 			break;
2222 		}
2223 
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)) {
2230 					retval = -EIO;
2231 					break;
2232 				}
2233 				if (tty_hung_up_p(file))
2234 					break;
2235 				/*
2236 				 * Abort readers for ttys which never actually
2237 				 * get hung up.  See __tty_hangup().
2238 				 */
2239 				if (test_bit(TTY_HUPPING, &tty->flags))
2240 					break;
2241 				if (!timeout)
2242 					break;
2243 				if (tty_io_nonblock(tty, file)) {
2244 					retval = -EAGAIN;
2245 					break;
2246 				}
2247 				if (signal_pending(current)) {
2248 					retval = -ERESTARTSYS;
2249 					break;
2250 				}
2251 				up_read(&tty->termios_rwsem);
2252 
2253 				timeout = wait_woken(&wait, TASK_INTERRUPTIBLE,
2254 						timeout);
2255 
2256 				down_read(&tty->termios_rwsem);
2257 				continue;
2258 			}
2259 		}
2260 
2261 		if (ldata->icanon && !L_EXTPROC(tty)) {
2262 			if (canon_copy_from_read_buf(tty, &kb, &nr))
2263 				goto more_to_be_read;
2264 		} else {
2265 			/* Deal with packet mode. */
2266 			if (packet && kb == kbuf) {
2267 				*kb++ = TIOCPKT_DATA;
2268 				nr--;
2269 			}
2270 
2271 			/*
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.
2275 			 *
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.
2279 			 */
2280 			if (copy_from_read_buf(tty, &kb, &nr) && kb - kbuf >= minimum) {
2281 more_to_be_read:
2282 				remove_wait_queue(&tty->read_wait, &wait);
2283 				*cookie = cookie;
2284 				return kb - kbuf;
2285 			}
2286 		}
2287 
2288 		n_tty_check_unthrottle(tty);
2289 
2290 		if (kb - kbuf >= minimum)
2291 			break;
2292 		if (time)
2293 			timeout = time;
2294 	}
2295 	if (old_tail != ldata->read_tail) {
2296 		/*
2297 		 * Make sure no_room is not read in n_tty_kick_worker()
2298 		 * before setting ldata->read_tail in copy_from_read_buf().
2299 		 */
2300 		smp_mb();
2301 		n_tty_kick_worker(tty);
2302 	}
2303 	up_read(&tty->termios_rwsem);
2304 
2305 	remove_wait_queue(&tty->read_wait, &wait);
2306 	mutex_unlock(&ldata->atomic_read_lock);
2307 
2308 	if (kb - kbuf)
2309 		retval = kb - kbuf;
2310 
2311 	return retval;
2312 }
2313 
2314 /**
2315  * n_tty_write		-	write function for tty
2316  * @tty: tty device
2317  * @file: file object
2318  * @buf: userspace buffer pointer
2319  * @nr: size of I/O
2320  *
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.
2327  *
2328  * This code must be sure never to sleep through a hangup.
2329  *
2330  * Locking: output_lock to protect column state and space left
2331  *	 (note that the process_output*() functions take this lock themselves)
2332  */
2333 
2334 static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
2335 			   const unsigned char *buf, size_t nr)
2336 {
2337 	const unsigned char *b = buf;
2338 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
2339 	int c;
2340 	ssize_t retval = 0;
2341 
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);
2345 		if (retval)
2346 			return retval;
2347 	}
2348 
2349 	down_read(&tty->termios_rwsem);
2350 
2351 	/* Write out any echoed characters that are still pending */
2352 	process_echoes(tty);
2353 
2354 	add_wait_queue(&tty->write_wait, &wait);
2355 	while (1) {
2356 		if (signal_pending(current)) {
2357 			retval = -ERESTARTSYS;
2358 			break;
2359 		}
2360 		if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
2361 			retval = -EIO;
2362 			break;
2363 		}
2364 		if (O_OPOST(tty)) {
2365 			while (nr > 0) {
2366 				ssize_t num = process_output_block(tty, b, nr);
2367 				if (num < 0) {
2368 					if (num == -EAGAIN)
2369 						break;
2370 					retval = num;
2371 					goto break_out;
2372 				}
2373 				b += num;
2374 				nr -= num;
2375 				if (nr == 0)
2376 					break;
2377 				c = *b;
2378 				if (process_output(c, tty) < 0)
2379 					break;
2380 				b++; nr--;
2381 			}
2382 			if (tty->ops->flush_chars)
2383 				tty->ops->flush_chars(tty);
2384 		} else {
2385 			struct n_tty_data *ldata = tty->disc_data;
2386 
2387 			while (nr > 0) {
2388 				mutex_lock(&ldata->output_lock);
2389 				c = tty->ops->write(tty, b, nr);
2390 				mutex_unlock(&ldata->output_lock);
2391 				if (c < 0) {
2392 					retval = c;
2393 					goto break_out;
2394 				}
2395 				if (!c)
2396 					break;
2397 				b += c;
2398 				nr -= c;
2399 			}
2400 		}
2401 		if (!nr)
2402 			break;
2403 		if (tty_io_nonblock(tty, file)) {
2404 			retval = -EAGAIN;
2405 			break;
2406 		}
2407 		up_read(&tty->termios_rwsem);
2408 
2409 		wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
2410 
2411 		down_read(&tty->termios_rwsem);
2412 	}
2413 break_out:
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;
2419 }
2420 
2421 /**
2422  * n_tty_poll		-	poll method for N_TTY
2423  * @tty: terminal device
2424  * @file: file accessing it
2425  * @wait: poll table
2426  *
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
2429  * open/close.
2430  *
2431  * This code must be sure never to sleep through a hangup.
2432  *
2433  * Locking: called without the kernel lock held -- fine.
2434  */
2435 static __poll_t n_tty_poll(struct tty_struct *tty, struct file *file,
2436 							poll_table *wait)
2437 {
2438 	__poll_t mask = 0;
2439 
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;
2444 	else {
2445 		tty_buffer_flush_work(tty->port);
2446 		if (input_available_p(tty, 1))
2447 			mask |= EPOLLIN | EPOLLRDNORM;
2448 	}
2449 	if (tty->ctrl.packet && tty->link->ctrl.pktstatus)
2450 		mask |= EPOLLPRI | EPOLLIN | EPOLLRDNORM;
2451 	if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
2452 		mask |= EPOLLHUP;
2453 	if (tty_hung_up_p(file))
2454 		mask |= EPOLLHUP;
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;
2459 	return mask;
2460 }
2461 
2462 static unsigned long inq_canon(struct n_tty_data *ldata)
2463 {
2464 	size_t nr, head, tail;
2465 
2466 	if (ldata->canon_head == ldata->read_tail)
2467 		return 0;
2468 	head = ldata->canon_head;
2469 	tail = ldata->read_tail;
2470 	nr = head - 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)
2475 			nr--;
2476 		tail++;
2477 	}
2478 	return nr;
2479 }
2480 
2481 static int n_tty_ioctl(struct tty_struct *tty, unsigned int cmd,
2482 		       unsigned long arg)
2483 {
2484 	struct n_tty_data *ldata = tty->disc_data;
2485 	int retval;
2486 
2487 	switch (cmd) {
2488 	case TIOCOUTQ:
2489 		return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
2490 	case TIOCINQ:
2491 		down_write(&tty->termios_rwsem);
2492 		if (L_ICANON(tty) && !L_EXTPROC(tty))
2493 			retval = inq_canon(ldata);
2494 		else
2495 			retval = read_cnt(ldata);
2496 		up_write(&tty->termios_rwsem);
2497 		return put_user(retval, (unsigned int __user *) arg);
2498 	default:
2499 		return n_tty_ioctl_helper(tty, cmd, arg);
2500 	}
2501 }
2502 
2503 static struct tty_ldisc_ops n_tty_ops = {
2504 	.owner		 = THIS_MODULE,
2505 	.num		 = N_TTY,
2506 	.name            = "n_tty",
2507 	.open            = n_tty_open,
2508 	.close           = n_tty_close,
2509 	.flush_buffer    = n_tty_flush_buffer,
2510 	.read            = n_tty_read,
2511 	.write           = n_tty_write,
2512 	.ioctl           = n_tty_ioctl,
2513 	.set_termios     = n_tty_set_termios,
2514 	.poll            = n_tty_poll,
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,
2519 };
2520 
2521 /**
2522  *	n_tty_inherit_ops	-	inherit N_TTY methods
2523  *	@ops: struct tty_ldisc_ops where to save N_TTY methods
2524  *
2525  *	Enables a 'subclass' line discipline to 'inherit' N_TTY methods.
2526  */
2527 
2528 void n_tty_inherit_ops(struct tty_ldisc_ops *ops)
2529 {
2530 	*ops = n_tty_ops;
2531 	ops->owner = NULL;
2532 }
2533 EXPORT_SYMBOL_GPL(n_tty_inherit_ops);
2534 
2535 void __init n_tty_init(void)
2536 {
2537 	tty_register_ldisc(&n_tty_ops);
2538 }
2539