xref: /linux/drivers/tty/n_tty.c (revision ff40b5769a50fab654a70575ff0f49853b799b0e)
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(ldata->no_room)) {
207 		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 			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 	up_read(&tty->termios_rwsem);
1732 
1733 	return rcvd;
1734 }
1735 
1736 static void n_tty_receive_buf(struct tty_struct *tty, const unsigned char *cp,
1737 			      const char *fp, int count)
1738 {
1739 	n_tty_receive_buf_common(tty, cp, fp, count, 0);
1740 }
1741 
1742 static int n_tty_receive_buf2(struct tty_struct *tty, const unsigned char *cp,
1743 			      const char *fp, int count)
1744 {
1745 	return n_tty_receive_buf_common(tty, cp, fp, count, 1);
1746 }
1747 
1748 /**
1749  * n_tty_set_termios	-	termios data changed
1750  * @tty: terminal
1751  * @old: previous data
1752  *
1753  * Called by the tty layer when the user changes termios flags so that the line
1754  * discipline can plan ahead. This function cannot sleep and is protected from
1755  * re-entry by the tty layer. The user is guaranteed that this function will
1756  * not be re-entered or in progress when the ldisc is closed.
1757  *
1758  * Locking: Caller holds @tty->termios_rwsem
1759  */
1760 static void n_tty_set_termios(struct tty_struct *tty, const struct ktermios *old)
1761 {
1762 	struct n_tty_data *ldata = tty->disc_data;
1763 
1764 	if (!old || (old->c_lflag ^ tty->termios.c_lflag) & (ICANON | EXTPROC)) {
1765 		bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
1766 		ldata->line_start = ldata->read_tail;
1767 		if (!L_ICANON(tty) || !read_cnt(ldata)) {
1768 			ldata->canon_head = ldata->read_tail;
1769 			ldata->push = 0;
1770 		} else {
1771 			set_bit((ldata->read_head - 1) & (N_TTY_BUF_SIZE - 1),
1772 				ldata->read_flags);
1773 			ldata->canon_head = ldata->read_head;
1774 			ldata->push = 1;
1775 		}
1776 		ldata->commit_head = ldata->read_head;
1777 		ldata->erasing = 0;
1778 		ldata->lnext = 0;
1779 	}
1780 
1781 	ldata->icanon = (L_ICANON(tty) != 0);
1782 
1783 	if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
1784 	    I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
1785 	    I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
1786 	    I_PARMRK(tty)) {
1787 		bitmap_zero(ldata->char_map, 256);
1788 
1789 		if (I_IGNCR(tty) || I_ICRNL(tty))
1790 			set_bit('\r', ldata->char_map);
1791 		if (I_INLCR(tty))
1792 			set_bit('\n', ldata->char_map);
1793 
1794 		if (L_ICANON(tty)) {
1795 			set_bit(ERASE_CHAR(tty), ldata->char_map);
1796 			set_bit(KILL_CHAR(tty), ldata->char_map);
1797 			set_bit(EOF_CHAR(tty), ldata->char_map);
1798 			set_bit('\n', ldata->char_map);
1799 			set_bit(EOL_CHAR(tty), ldata->char_map);
1800 			if (L_IEXTEN(tty)) {
1801 				set_bit(WERASE_CHAR(tty), ldata->char_map);
1802 				set_bit(LNEXT_CHAR(tty), ldata->char_map);
1803 				set_bit(EOL2_CHAR(tty), ldata->char_map);
1804 				if (L_ECHO(tty))
1805 					set_bit(REPRINT_CHAR(tty),
1806 						ldata->char_map);
1807 			}
1808 		}
1809 		if (I_IXON(tty)) {
1810 			set_bit(START_CHAR(tty), ldata->char_map);
1811 			set_bit(STOP_CHAR(tty), ldata->char_map);
1812 		}
1813 		if (L_ISIG(tty)) {
1814 			set_bit(INTR_CHAR(tty), ldata->char_map);
1815 			set_bit(QUIT_CHAR(tty), ldata->char_map);
1816 			set_bit(SUSP_CHAR(tty), ldata->char_map);
1817 		}
1818 		clear_bit(__DISABLED_CHAR, ldata->char_map);
1819 		ldata->raw = 0;
1820 		ldata->real_raw = 0;
1821 	} else {
1822 		ldata->raw = 1;
1823 		if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
1824 		    (I_IGNPAR(tty) || !I_INPCK(tty)) &&
1825 		    (tty->driver->flags & TTY_DRIVER_REAL_RAW))
1826 			ldata->real_raw = 1;
1827 		else
1828 			ldata->real_raw = 0;
1829 	}
1830 	/*
1831 	 * Fix tty hang when I_IXON(tty) is cleared, but the tty
1832 	 * been stopped by STOP_CHAR(tty) before it.
1833 	 */
1834 	if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow.tco_stopped) {
1835 		start_tty(tty);
1836 		process_echoes(tty);
1837 	}
1838 
1839 	/* The termios change make the tty ready for I/O */
1840 	wake_up_interruptible(&tty->write_wait);
1841 	wake_up_interruptible(&tty->read_wait);
1842 }
1843 
1844 /**
1845  * n_tty_close		-	close the ldisc for this tty
1846  * @tty: device
1847  *
1848  * Called from the terminal layer when this line discipline is being shut down,
1849  * either because of a close or becsuse of a discipline change. The function
1850  * will not be called while other ldisc methods are in progress.
1851  */
1852 static void n_tty_close(struct tty_struct *tty)
1853 {
1854 	struct n_tty_data *ldata = tty->disc_data;
1855 
1856 	if (tty->link)
1857 		n_tty_packet_mode_flush(tty);
1858 
1859 	down_write(&tty->termios_rwsem);
1860 	vfree(ldata);
1861 	tty->disc_data = NULL;
1862 	up_write(&tty->termios_rwsem);
1863 }
1864 
1865 /**
1866  * n_tty_open		-	open an ldisc
1867  * @tty: terminal to open
1868  *
1869  * Called when this line discipline is being attached to the terminal device.
1870  * Can sleep. Called serialized so that no other events will occur in parallel.
1871  * No further open will occur until a close.
1872  */
1873 static int n_tty_open(struct tty_struct *tty)
1874 {
1875 	struct n_tty_data *ldata;
1876 
1877 	/* Currently a malloc failure here can panic */
1878 	ldata = vzalloc(sizeof(*ldata));
1879 	if (!ldata)
1880 		return -ENOMEM;
1881 
1882 	ldata->overrun_time = jiffies;
1883 	mutex_init(&ldata->atomic_read_lock);
1884 	mutex_init(&ldata->output_lock);
1885 
1886 	tty->disc_data = ldata;
1887 	tty->closing = 0;
1888 	/* indicate buffer work may resume */
1889 	clear_bit(TTY_LDISC_HALTED, &tty->flags);
1890 	n_tty_set_termios(tty, NULL);
1891 	tty_unthrottle(tty);
1892 	return 0;
1893 }
1894 
1895 static inline int input_available_p(struct tty_struct *tty, int poll)
1896 {
1897 	struct n_tty_data *ldata = tty->disc_data;
1898 	int amt = poll && !TIME_CHAR(tty) && MIN_CHAR(tty) ? MIN_CHAR(tty) : 1;
1899 
1900 	if (ldata->icanon && !L_EXTPROC(tty))
1901 		return ldata->canon_head != ldata->read_tail;
1902 	else
1903 		return ldata->commit_head - ldata->read_tail >= amt;
1904 }
1905 
1906 /**
1907  * copy_from_read_buf	-	copy read data directly
1908  * @tty: terminal device
1909  * @kbp: data
1910  * @nr: size of data
1911  *
1912  * Helper function to speed up n_tty_read(). It is only called when %ICANON is
1913  * off; it copies characters straight from the tty queue.
1914  *
1915  * Returns: true if it successfully copied data, but there is still more data
1916  * to be had.
1917  *
1918  * Locking:
1919  *  * called under the @ldata->atomic_read_lock sem
1920  *  * n_tty_read()/consumer path:
1921  *		caller holds non-exclusive %termios_rwsem;
1922  *		read_tail published
1923  */
1924 static bool copy_from_read_buf(struct tty_struct *tty,
1925 				      unsigned char **kbp,
1926 				      size_t *nr)
1927 
1928 {
1929 	struct n_tty_data *ldata = tty->disc_data;
1930 	size_t n;
1931 	bool is_eof;
1932 	size_t head = smp_load_acquire(&ldata->commit_head);
1933 	size_t tail = ldata->read_tail & (N_TTY_BUF_SIZE - 1);
1934 
1935 	n = min(head - ldata->read_tail, N_TTY_BUF_SIZE - tail);
1936 	n = min(*nr, n);
1937 	if (n) {
1938 		unsigned char *from = read_buf_addr(ldata, tail);
1939 		memcpy(*kbp, from, n);
1940 		is_eof = n == 1 && *from == EOF_CHAR(tty);
1941 		tty_audit_add_data(tty, from, n);
1942 		zero_buffer(tty, from, n);
1943 		smp_store_release(&ldata->read_tail, ldata->read_tail + n);
1944 		/* Turn single EOF into zero-length read */
1945 		if (L_EXTPROC(tty) && ldata->icanon && is_eof &&
1946 		    (head == ldata->read_tail))
1947 			return false;
1948 		*kbp += n;
1949 		*nr -= n;
1950 
1951 		/* If we have more to copy, let the caller know */
1952 		return head != ldata->read_tail;
1953 	}
1954 	return false;
1955 }
1956 
1957 /**
1958  * canon_copy_from_read_buf	-	copy read data in canonical mode
1959  * @tty: terminal device
1960  * @kbp: data
1961  * @nr: size of data
1962  *
1963  * Helper function for n_tty_read(). It is only called when %ICANON is on; it
1964  * copies one line of input up to and including the line-delimiting character
1965  * into the result buffer.
1966  *
1967  * Note: When termios is changed from non-canonical to canonical mode and the
1968  * read buffer contains data, n_tty_set_termios() simulates an EOF push (as if
1969  * C-d were input) _without_ the %DISABLED_CHAR in the buffer. This causes data
1970  * already processed as input to be immediately available as input although a
1971  * newline has not been received.
1972  *
1973  * Locking:
1974  *  * called under the %atomic_read_lock mutex
1975  *  * n_tty_read()/consumer path:
1976  *	caller holds non-exclusive %termios_rwsem;
1977  *	read_tail published
1978  */
1979 static bool canon_copy_from_read_buf(struct tty_struct *tty,
1980 				     unsigned char **kbp,
1981 				     size_t *nr)
1982 {
1983 	struct n_tty_data *ldata = tty->disc_data;
1984 	size_t n, size, more, c;
1985 	size_t eol;
1986 	size_t tail, canon_head;
1987 	int found = 0;
1988 
1989 	/* N.B. avoid overrun if nr == 0 */
1990 	if (!*nr)
1991 		return false;
1992 
1993 	canon_head = smp_load_acquire(&ldata->canon_head);
1994 	n = min(*nr, canon_head - ldata->read_tail);
1995 
1996 	tail = ldata->read_tail & (N_TTY_BUF_SIZE - 1);
1997 	size = min_t(size_t, tail + n, N_TTY_BUF_SIZE);
1998 
1999 	n_tty_trace("%s: nr:%zu tail:%zu n:%zu size:%zu\n",
2000 		    __func__, *nr, tail, n, size);
2001 
2002 	eol = find_next_bit(ldata->read_flags, size, tail);
2003 	more = n - (size - tail);
2004 	if (eol == N_TTY_BUF_SIZE && more) {
2005 		/* scan wrapped without finding set bit */
2006 		eol = find_first_bit(ldata->read_flags, more);
2007 		found = eol != more;
2008 	} else
2009 		found = eol != size;
2010 
2011 	n = eol - tail;
2012 	if (n > N_TTY_BUF_SIZE)
2013 		n += N_TTY_BUF_SIZE;
2014 	c = n + found;
2015 
2016 	if (!found || read_buf(ldata, eol) != __DISABLED_CHAR)
2017 		n = c;
2018 
2019 	n_tty_trace("%s: eol:%zu found:%d n:%zu c:%zu tail:%zu more:%zu\n",
2020 		    __func__, eol, found, n, c, tail, more);
2021 
2022 	tty_copy(tty, *kbp, tail, n);
2023 	*kbp += n;
2024 	*nr -= n;
2025 
2026 	if (found)
2027 		clear_bit(eol, ldata->read_flags);
2028 	smp_store_release(&ldata->read_tail, ldata->read_tail + c);
2029 
2030 	if (found) {
2031 		if (!ldata->push)
2032 			ldata->line_start = ldata->read_tail;
2033 		else
2034 			ldata->push = 0;
2035 		tty_audit_push();
2036 		return false;
2037 	}
2038 
2039 	/* No EOL found - do a continuation retry if there is more data */
2040 	return ldata->read_tail != canon_head;
2041 }
2042 
2043 /*
2044  * If we finished a read at the exact location of an
2045  * EOF (special EOL character that's a __DISABLED_CHAR)
2046  * in the stream, silently eat the EOF.
2047  */
2048 static void canon_skip_eof(struct tty_struct *tty)
2049 {
2050 	struct n_tty_data *ldata = tty->disc_data;
2051 	size_t tail, canon_head;
2052 
2053 	canon_head = smp_load_acquire(&ldata->canon_head);
2054 	tail = ldata->read_tail;
2055 
2056 	// No data?
2057 	if (tail == canon_head)
2058 		return;
2059 
2060 	// See if the tail position is EOF in the circular buffer
2061 	tail &= (N_TTY_BUF_SIZE - 1);
2062 	if (!test_bit(tail, ldata->read_flags))
2063 		return;
2064 	if (read_buf(ldata, tail) != __DISABLED_CHAR)
2065 		return;
2066 
2067 	// Clear the EOL bit, skip the EOF char.
2068 	clear_bit(tail, ldata->read_flags);
2069 	smp_store_release(&ldata->read_tail, ldata->read_tail + 1);
2070 }
2071 
2072 /**
2073  * job_control		-	check job control
2074  * @tty: tty
2075  * @file: file handle
2076  *
2077  * Perform job control management checks on this @file/@tty descriptor and if
2078  * appropriate send any needed signals and return a negative error code if
2079  * action should be taken.
2080  *
2081  * Locking:
2082  *  * redirected write test is safe
2083  *  * current->signal->tty check is safe
2084  *  * ctrl.lock to safely reference @tty->ctrl.pgrp
2085  */
2086 static int job_control(struct tty_struct *tty, struct file *file)
2087 {
2088 	/* Job control check -- must be done at start and after
2089 	   every sleep (POSIX.1 7.1.1.4). */
2090 	/* NOTE: not yet done after every sleep pending a thorough
2091 	   check of the logic of this change. -- jlc */
2092 	/* don't stop on /dev/console */
2093 	if (file->f_op->write_iter == redirected_tty_write)
2094 		return 0;
2095 
2096 	return __tty_check_change(tty, SIGTTIN);
2097 }
2098 
2099 
2100 /**
2101  * n_tty_read		-	read function for tty
2102  * @tty: tty device
2103  * @file: file object
2104  * @kbuf: kernelspace buffer pointer
2105  * @nr: size of I/O
2106  * @cookie: if non-%NULL, this is a continuation read
2107  * @offset: where to continue reading from (unused in n_tty)
2108  *
2109  * Perform reads for the line discipline. We are guaranteed that the line
2110  * discipline will not be closed under us but we may get multiple parallel
2111  * readers and must handle this ourselves. We may also get a hangup. Always
2112  * called in user context, may sleep.
2113  *
2114  * This code must be sure never to sleep through a hangup.
2115  *
2116  * Locking: n_tty_read()/consumer path:
2117  *	claims non-exclusive termios_rwsem;
2118  *	publishes read_tail
2119  */
2120 static ssize_t n_tty_read(struct tty_struct *tty, struct file *file,
2121 			  unsigned char *kbuf, size_t nr,
2122 			  void **cookie, unsigned long offset)
2123 {
2124 	struct n_tty_data *ldata = tty->disc_data;
2125 	unsigned char *kb = kbuf;
2126 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
2127 	int c;
2128 	int minimum, time;
2129 	ssize_t retval = 0;
2130 	long timeout;
2131 	bool packet;
2132 	size_t old_tail;
2133 
2134 	/*
2135 	 * Is this a continuation of a read started earler?
2136 	 *
2137 	 * If so, we still hold the atomic_read_lock and the
2138 	 * termios_rwsem, and can just continue to copy data.
2139 	 */
2140 	if (*cookie) {
2141 		if (ldata->icanon && !L_EXTPROC(tty)) {
2142 			/*
2143 			 * If we have filled the user buffer, see
2144 			 * if we should skip an EOF character before
2145 			 * releasing the lock and returning done.
2146 			 */
2147 			if (!nr)
2148 				canon_skip_eof(tty);
2149 			else if (canon_copy_from_read_buf(tty, &kb, &nr))
2150 				return kb - kbuf;
2151 		} else {
2152 			if (copy_from_read_buf(tty, &kb, &nr))
2153 				return kb - kbuf;
2154 		}
2155 
2156 		/* No more data - release locks and stop retries */
2157 		n_tty_kick_worker(tty);
2158 		n_tty_check_unthrottle(tty);
2159 		up_read(&tty->termios_rwsem);
2160 		mutex_unlock(&ldata->atomic_read_lock);
2161 		*cookie = NULL;
2162 		return kb - kbuf;
2163 	}
2164 
2165 	c = job_control(tty, file);
2166 	if (c < 0)
2167 		return c;
2168 
2169 	/*
2170 	 *	Internal serialization of reads.
2171 	 */
2172 	if (file->f_flags & O_NONBLOCK) {
2173 		if (!mutex_trylock(&ldata->atomic_read_lock))
2174 			return -EAGAIN;
2175 	} else {
2176 		if (mutex_lock_interruptible(&ldata->atomic_read_lock))
2177 			return -ERESTARTSYS;
2178 	}
2179 
2180 	down_read(&tty->termios_rwsem);
2181 
2182 	minimum = time = 0;
2183 	timeout = MAX_SCHEDULE_TIMEOUT;
2184 	if (!ldata->icanon) {
2185 		minimum = MIN_CHAR(tty);
2186 		if (minimum) {
2187 			time = (HZ / 10) * TIME_CHAR(tty);
2188 		} else {
2189 			timeout = (HZ / 10) * TIME_CHAR(tty);
2190 			minimum = 1;
2191 		}
2192 	}
2193 
2194 	packet = tty->ctrl.packet;
2195 	old_tail = ldata->read_tail;
2196 
2197 	add_wait_queue(&tty->read_wait, &wait);
2198 	while (nr) {
2199 		/* First test for status change. */
2200 		if (packet && tty->link->ctrl.pktstatus) {
2201 			unsigned char cs;
2202 			if (kb != kbuf)
2203 				break;
2204 			spin_lock_irq(&tty->link->ctrl.lock);
2205 			cs = tty->link->ctrl.pktstatus;
2206 			tty->link->ctrl.pktstatus = 0;
2207 			spin_unlock_irq(&tty->link->ctrl.lock);
2208 			*kb++ = cs;
2209 			nr--;
2210 			break;
2211 		}
2212 
2213 		if (!input_available_p(tty, 0)) {
2214 			up_read(&tty->termios_rwsem);
2215 			tty_buffer_flush_work(tty->port);
2216 			down_read(&tty->termios_rwsem);
2217 			if (!input_available_p(tty, 0)) {
2218 				if (test_bit(TTY_OTHER_CLOSED, &tty->flags)) {
2219 					retval = -EIO;
2220 					break;
2221 				}
2222 				if (tty_hung_up_p(file))
2223 					break;
2224 				/*
2225 				 * Abort readers for ttys which never actually
2226 				 * get hung up.  See __tty_hangup().
2227 				 */
2228 				if (test_bit(TTY_HUPPING, &tty->flags))
2229 					break;
2230 				if (!timeout)
2231 					break;
2232 				if (tty_io_nonblock(tty, file)) {
2233 					retval = -EAGAIN;
2234 					break;
2235 				}
2236 				if (signal_pending(current)) {
2237 					retval = -ERESTARTSYS;
2238 					break;
2239 				}
2240 				up_read(&tty->termios_rwsem);
2241 
2242 				timeout = wait_woken(&wait, TASK_INTERRUPTIBLE,
2243 						timeout);
2244 
2245 				down_read(&tty->termios_rwsem);
2246 				continue;
2247 			}
2248 		}
2249 
2250 		if (ldata->icanon && !L_EXTPROC(tty)) {
2251 			if (canon_copy_from_read_buf(tty, &kb, &nr))
2252 				goto more_to_be_read;
2253 		} else {
2254 			/* Deal with packet mode. */
2255 			if (packet && kb == kbuf) {
2256 				*kb++ = TIOCPKT_DATA;
2257 				nr--;
2258 			}
2259 
2260 			/*
2261 			 * Copy data, and if there is more to be had
2262 			 * and we have nothing more to wait for, then
2263 			 * let's mark us for retries.
2264 			 *
2265 			 * NOTE! We return here with both the termios_sem
2266 			 * and atomic_read_lock still held, the retries
2267 			 * will release them when done.
2268 			 */
2269 			if (copy_from_read_buf(tty, &kb, &nr) && kb - kbuf >= minimum) {
2270 more_to_be_read:
2271 				remove_wait_queue(&tty->read_wait, &wait);
2272 				*cookie = cookie;
2273 				return kb - kbuf;
2274 			}
2275 		}
2276 
2277 		n_tty_check_unthrottle(tty);
2278 
2279 		if (kb - kbuf >= minimum)
2280 			break;
2281 		if (time)
2282 			timeout = time;
2283 	}
2284 	if (old_tail != ldata->read_tail)
2285 		n_tty_kick_worker(tty);
2286 	up_read(&tty->termios_rwsem);
2287 
2288 	remove_wait_queue(&tty->read_wait, &wait);
2289 	mutex_unlock(&ldata->atomic_read_lock);
2290 
2291 	if (kb - kbuf)
2292 		retval = kb - kbuf;
2293 
2294 	return retval;
2295 }
2296 
2297 /**
2298  * n_tty_write		-	write function for tty
2299  * @tty: tty device
2300  * @file: file object
2301  * @buf: userspace buffer pointer
2302  * @nr: size of I/O
2303  *
2304  * Write function of the terminal device. This is serialized with respect to
2305  * other write callers but not to termios changes, reads and other such events.
2306  * Since the receive code will echo characters, thus calling driver write
2307  * methods, the %output_lock is used in the output processing functions called
2308  * here as well as in the echo processing function to protect the column state
2309  * and space left in the buffer.
2310  *
2311  * This code must be sure never to sleep through a hangup.
2312  *
2313  * Locking: output_lock to protect column state and space left
2314  *	 (note that the process_output*() functions take this lock themselves)
2315  */
2316 
2317 static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
2318 			   const unsigned char *buf, size_t nr)
2319 {
2320 	const unsigned char *b = buf;
2321 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
2322 	int c;
2323 	ssize_t retval = 0;
2324 
2325 	/* Job control check -- must be done at start (POSIX.1 7.1.1.4). */
2326 	if (L_TOSTOP(tty) && file->f_op->write_iter != redirected_tty_write) {
2327 		retval = tty_check_change(tty);
2328 		if (retval)
2329 			return retval;
2330 	}
2331 
2332 	down_read(&tty->termios_rwsem);
2333 
2334 	/* Write out any echoed characters that are still pending */
2335 	process_echoes(tty);
2336 
2337 	add_wait_queue(&tty->write_wait, &wait);
2338 	while (1) {
2339 		if (signal_pending(current)) {
2340 			retval = -ERESTARTSYS;
2341 			break;
2342 		}
2343 		if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
2344 			retval = -EIO;
2345 			break;
2346 		}
2347 		if (O_OPOST(tty)) {
2348 			while (nr > 0) {
2349 				ssize_t num = process_output_block(tty, b, nr);
2350 				if (num < 0) {
2351 					if (num == -EAGAIN)
2352 						break;
2353 					retval = num;
2354 					goto break_out;
2355 				}
2356 				b += num;
2357 				nr -= num;
2358 				if (nr == 0)
2359 					break;
2360 				c = *b;
2361 				if (process_output(c, tty) < 0)
2362 					break;
2363 				b++; nr--;
2364 			}
2365 			if (tty->ops->flush_chars)
2366 				tty->ops->flush_chars(tty);
2367 		} else {
2368 			struct n_tty_data *ldata = tty->disc_data;
2369 
2370 			while (nr > 0) {
2371 				mutex_lock(&ldata->output_lock);
2372 				c = tty->ops->write(tty, b, nr);
2373 				mutex_unlock(&ldata->output_lock);
2374 				if (c < 0) {
2375 					retval = c;
2376 					goto break_out;
2377 				}
2378 				if (!c)
2379 					break;
2380 				b += c;
2381 				nr -= c;
2382 			}
2383 		}
2384 		if (!nr)
2385 			break;
2386 		if (tty_io_nonblock(tty, file)) {
2387 			retval = -EAGAIN;
2388 			break;
2389 		}
2390 		up_read(&tty->termios_rwsem);
2391 
2392 		wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
2393 
2394 		down_read(&tty->termios_rwsem);
2395 	}
2396 break_out:
2397 	remove_wait_queue(&tty->write_wait, &wait);
2398 	if (nr && tty->fasync)
2399 		set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
2400 	up_read(&tty->termios_rwsem);
2401 	return (b - buf) ? b - buf : retval;
2402 }
2403 
2404 /**
2405  * n_tty_poll		-	poll method for N_TTY
2406  * @tty: terminal device
2407  * @file: file accessing it
2408  * @wait: poll table
2409  *
2410  * Called when the line discipline is asked to poll() for data or for special
2411  * events. This code is not serialized with respect to other events save
2412  * open/close.
2413  *
2414  * This code must be sure never to sleep through a hangup.
2415  *
2416  * Locking: called without the kernel lock held -- fine.
2417  */
2418 static __poll_t n_tty_poll(struct tty_struct *tty, struct file *file,
2419 							poll_table *wait)
2420 {
2421 	__poll_t mask = 0;
2422 
2423 	poll_wait(file, &tty->read_wait, wait);
2424 	poll_wait(file, &tty->write_wait, wait);
2425 	if (input_available_p(tty, 1))
2426 		mask |= EPOLLIN | EPOLLRDNORM;
2427 	else {
2428 		tty_buffer_flush_work(tty->port);
2429 		if (input_available_p(tty, 1))
2430 			mask |= EPOLLIN | EPOLLRDNORM;
2431 	}
2432 	if (tty->ctrl.packet && tty->link->ctrl.pktstatus)
2433 		mask |= EPOLLPRI | EPOLLIN | EPOLLRDNORM;
2434 	if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
2435 		mask |= EPOLLHUP;
2436 	if (tty_hung_up_p(file))
2437 		mask |= EPOLLHUP;
2438 	if (tty->ops->write && !tty_is_writelocked(tty) &&
2439 			tty_chars_in_buffer(tty) < WAKEUP_CHARS &&
2440 			tty_write_room(tty) > 0)
2441 		mask |= EPOLLOUT | EPOLLWRNORM;
2442 	return mask;
2443 }
2444 
2445 static unsigned long inq_canon(struct n_tty_data *ldata)
2446 {
2447 	size_t nr, head, tail;
2448 
2449 	if (ldata->canon_head == ldata->read_tail)
2450 		return 0;
2451 	head = ldata->canon_head;
2452 	tail = ldata->read_tail;
2453 	nr = head - tail;
2454 	/* Skip EOF-chars.. */
2455 	while (MASK(head) != MASK(tail)) {
2456 		if (test_bit(tail & (N_TTY_BUF_SIZE - 1), ldata->read_flags) &&
2457 		    read_buf(ldata, tail) == __DISABLED_CHAR)
2458 			nr--;
2459 		tail++;
2460 	}
2461 	return nr;
2462 }
2463 
2464 static int n_tty_ioctl(struct tty_struct *tty, unsigned int cmd,
2465 		       unsigned long arg)
2466 {
2467 	struct n_tty_data *ldata = tty->disc_data;
2468 	int retval;
2469 
2470 	switch (cmd) {
2471 	case TIOCOUTQ:
2472 		return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
2473 	case TIOCINQ:
2474 		down_write(&tty->termios_rwsem);
2475 		if (L_ICANON(tty) && !L_EXTPROC(tty))
2476 			retval = inq_canon(ldata);
2477 		else
2478 			retval = read_cnt(ldata);
2479 		up_write(&tty->termios_rwsem);
2480 		return put_user(retval, (unsigned int __user *) arg);
2481 	default:
2482 		return n_tty_ioctl_helper(tty, cmd, arg);
2483 	}
2484 }
2485 
2486 static struct tty_ldisc_ops n_tty_ops = {
2487 	.owner		 = THIS_MODULE,
2488 	.num		 = N_TTY,
2489 	.name            = "n_tty",
2490 	.open            = n_tty_open,
2491 	.close           = n_tty_close,
2492 	.flush_buffer    = n_tty_flush_buffer,
2493 	.read            = n_tty_read,
2494 	.write           = n_tty_write,
2495 	.ioctl           = n_tty_ioctl,
2496 	.set_termios     = n_tty_set_termios,
2497 	.poll            = n_tty_poll,
2498 	.receive_buf     = n_tty_receive_buf,
2499 	.write_wakeup    = n_tty_write_wakeup,
2500 	.receive_buf2	 = n_tty_receive_buf2,
2501 	.lookahead_buf	 = n_tty_lookahead_flow_ctrl,
2502 };
2503 
2504 /**
2505  *	n_tty_inherit_ops	-	inherit N_TTY methods
2506  *	@ops: struct tty_ldisc_ops where to save N_TTY methods
2507  *
2508  *	Enables a 'subclass' line discipline to 'inherit' N_TTY methods.
2509  */
2510 
2511 void n_tty_inherit_ops(struct tty_ldisc_ops *ops)
2512 {
2513 	*ops = n_tty_ops;
2514 	ops->owner = NULL;
2515 }
2516 EXPORT_SYMBOL_GPL(n_tty_inherit_ops);
2517 
2518 void __init n_tty_init(void)
2519 {
2520 	tty_register_ldisc(&n_tty_ops);
2521 }
2522