xref: /openbmc/linux/drivers/tty/n_tty.c (revision 0be1511f)
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/types.h>
32 #include <linux/major.h>
33 #include <linux/errno.h>
34 #include <linux/signal.h>
35 #include <linux/fcntl.h>
36 #include <linux/sched.h>
37 #include <linux/interrupt.h>
38 #include <linux/tty.h>
39 #include <linux/timer.h>
40 #include <linux/ctype.h>
41 #include <linux/mm.h>
42 #include <linux/string.h>
43 #include <linux/slab.h>
44 #include <linux/poll.h>
45 #include <linux/bitops.h>
46 #include <linux/audit.h>
47 #include <linux/file.h>
48 #include <linux/uaccess.h>
49 #include <linux/module.h>
50 #include <linux/ratelimit.h>
51 #include <linux/vmalloc.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 	/* protected by output lock */
121 	unsigned int column;
122 	unsigned int canon_column;
123 	size_t echo_tail;
124 
125 	struct mutex atomic_read_lock;
126 	struct mutex output_lock;
127 };
128 
129 #define MASK(x) ((x) & (N_TTY_BUF_SIZE - 1))
130 
131 static inline size_t read_cnt(struct n_tty_data *ldata)
132 {
133 	return ldata->read_head - ldata->read_tail;
134 }
135 
136 static inline unsigned char read_buf(struct n_tty_data *ldata, size_t i)
137 {
138 	return ldata->read_buf[i & (N_TTY_BUF_SIZE - 1)];
139 }
140 
141 static inline unsigned char *read_buf_addr(struct n_tty_data *ldata, size_t i)
142 {
143 	return &ldata->read_buf[i & (N_TTY_BUF_SIZE - 1)];
144 }
145 
146 static inline unsigned char echo_buf(struct n_tty_data *ldata, size_t i)
147 {
148 	smp_rmb(); /* Matches smp_wmb() in add_echo_byte(). */
149 	return ldata->echo_buf[i & (N_TTY_BUF_SIZE - 1)];
150 }
151 
152 static inline unsigned char *echo_buf_addr(struct n_tty_data *ldata, size_t i)
153 {
154 	return &ldata->echo_buf[i & (N_TTY_BUF_SIZE - 1)];
155 }
156 
157 /* If we are not echoing the data, perhaps this is a secret so erase it */
158 static void zero_buffer(struct tty_struct *tty, u8 *buffer, int size)
159 {
160 	bool icanon = !!L_ICANON(tty);
161 	bool no_echo = !L_ECHO(tty);
162 
163 	if (icanon && no_echo)
164 		memset(buffer, 0x00, size);
165 }
166 
167 static int tty_copy_to_user(struct tty_struct *tty, void __user *to,
168 			    size_t tail, size_t n)
169 {
170 	struct n_tty_data *ldata = tty->disc_data;
171 	size_t size = N_TTY_BUF_SIZE - tail;
172 	void *from = read_buf_addr(ldata, tail);
173 	int uncopied;
174 
175 	if (n > size) {
176 		tty_audit_add_data(tty, from, size);
177 		uncopied = copy_to_user(to, from, size);
178 		zero_buffer(tty, from, size - uncopied);
179 		if (uncopied)
180 			return uncopied;
181 		to += size;
182 		n -= size;
183 		from = ldata->read_buf;
184 	}
185 
186 	tty_audit_add_data(tty, from, n);
187 	uncopied = copy_to_user(to, from, n);
188 	zero_buffer(tty, from, n - uncopied);
189 	return uncopied;
190 }
191 
192 /**
193  *	n_tty_kick_worker - start input worker (if required)
194  *	@tty: terminal
195  *
196  *	Re-schedules the flip buffer work if it may have stopped
197  *
198  *	Caller holds exclusive termios_rwsem
199  *	   or
200  *	n_tty_read()/consumer path:
201  *		holds non-exclusive termios_rwsem
202  */
203 
204 static void n_tty_kick_worker(struct tty_struct *tty)
205 {
206 	struct n_tty_data *ldata = tty->disc_data;
207 
208 	/* Did the input worker stop? Restart it */
209 	if (unlikely(ldata->no_room)) {
210 		ldata->no_room = 0;
211 
212 		WARN_RATELIMIT(tty->port->itty == NULL,
213 				"scheduling with invalid itty\n");
214 		/* see if ldisc has been killed - if so, this means that
215 		 * even though the ldisc has been halted and ->buf.work
216 		 * cancelled, ->buf.work is about to be rescheduled
217 		 */
218 		WARN_RATELIMIT(test_bit(TTY_LDISC_HALTED, &tty->flags),
219 			       "scheduling buffer work for halted ldisc\n");
220 		tty_buffer_restart_work(tty->port);
221 	}
222 }
223 
224 static ssize_t chars_in_buffer(struct tty_struct *tty)
225 {
226 	struct n_tty_data *ldata = tty->disc_data;
227 	ssize_t n = 0;
228 
229 	if (!ldata->icanon)
230 		n = ldata->commit_head - ldata->read_tail;
231 	else
232 		n = ldata->canon_head - ldata->read_tail;
233 	return n;
234 }
235 
236 /**
237  *	n_tty_write_wakeup	-	asynchronous I/O notifier
238  *	@tty: tty device
239  *
240  *	Required for the ptys, serial driver etc. since processes
241  *	that attach themselves to the master and rely on ASYNC
242  *	IO must be woken up
243  */
244 
245 static void n_tty_write_wakeup(struct tty_struct *tty)
246 {
247 	clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
248 	kill_fasync(&tty->fasync, SIGIO, POLL_OUT);
249 }
250 
251 static void n_tty_check_throttle(struct tty_struct *tty)
252 {
253 	struct n_tty_data *ldata = tty->disc_data;
254 
255 	/*
256 	 * Check the remaining room for the input canonicalization
257 	 * mode.  We don't want to throttle the driver if we're in
258 	 * canonical mode and don't have a newline yet!
259 	 */
260 	if (ldata->icanon && ldata->canon_head == ldata->read_tail)
261 		return;
262 
263 	while (1) {
264 		int throttled;
265 		tty_set_flow_change(tty, TTY_THROTTLE_SAFE);
266 		if (N_TTY_BUF_SIZE - read_cnt(ldata) >= TTY_THRESHOLD_THROTTLE)
267 			break;
268 		throttled = tty_throttle_safe(tty);
269 		if (!throttled)
270 			break;
271 	}
272 	__tty_set_flow_change(tty, 0);
273 }
274 
275 static void n_tty_check_unthrottle(struct tty_struct *tty)
276 {
277 	if (tty->driver->type == TTY_DRIVER_TYPE_PTY) {
278 		if (chars_in_buffer(tty) > TTY_THRESHOLD_UNTHROTTLE)
279 			return;
280 		n_tty_kick_worker(tty);
281 		tty_wakeup(tty->link);
282 		return;
283 	}
284 
285 	/* If there is enough space in the read buffer now, let the
286 	 * low-level driver know. We use chars_in_buffer() to
287 	 * check the buffer, as it now knows about canonical mode.
288 	 * Otherwise, if the driver is throttled and the line is
289 	 * longer than TTY_THRESHOLD_UNTHROTTLE in canonical mode,
290 	 * we won't get any more characters.
291 	 */
292 
293 	while (1) {
294 		int unthrottled;
295 		tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE);
296 		if (chars_in_buffer(tty) > TTY_THRESHOLD_UNTHROTTLE)
297 			break;
298 		n_tty_kick_worker(tty);
299 		unthrottled = tty_unthrottle_safe(tty);
300 		if (!unthrottled)
301 			break;
302 	}
303 	__tty_set_flow_change(tty, 0);
304 }
305 
306 /**
307  *	put_tty_queue		-	add character to tty
308  *	@c: character
309  *	@ldata: n_tty data
310  *
311  *	Add a character to the tty read_buf queue.
312  *
313  *	n_tty_receive_buf()/producer path:
314  *		caller holds non-exclusive termios_rwsem
315  */
316 
317 static inline void put_tty_queue(unsigned char c, struct n_tty_data *ldata)
318 {
319 	*read_buf_addr(ldata, ldata->read_head) = c;
320 	ldata->read_head++;
321 }
322 
323 /**
324  *	reset_buffer_flags	-	reset buffer state
325  *	@ldata: line disc data to reset
326  *
327  *	Reset the read buffer counters and clear the flags.
328  *	Called from n_tty_open() and n_tty_flush_buffer().
329  *
330  *	Locking: caller holds exclusive termios_rwsem
331  *		 (or locking is not required)
332  */
333 
334 static void reset_buffer_flags(struct n_tty_data *ldata)
335 {
336 	ldata->read_head = ldata->canon_head = ldata->read_tail = 0;
337 	ldata->commit_head = 0;
338 	ldata->line_start = 0;
339 
340 	ldata->erasing = 0;
341 	bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
342 	ldata->push = 0;
343 }
344 
345 static void n_tty_packet_mode_flush(struct tty_struct *tty)
346 {
347 	unsigned long flags;
348 
349 	if (tty->link->packet) {
350 		spin_lock_irqsave(&tty->ctrl_lock, flags);
351 		tty->ctrl_status |= TIOCPKT_FLUSHREAD;
352 		spin_unlock_irqrestore(&tty->ctrl_lock, flags);
353 		wake_up_interruptible(&tty->link->read_wait);
354 	}
355 }
356 
357 /**
358  *	n_tty_flush_buffer	-	clean input queue
359  *	@tty:	terminal device
360  *
361  *	Flush the input buffer. Called when the tty layer wants the
362  *	buffer flushed (eg at hangup) or when the N_TTY line discipline
363  *	internally has to clean the pending queue (for example some signals).
364  *
365  *	Holds termios_rwsem to exclude producer/consumer while
366  *	buffer indices are reset.
367  *
368  *	Locking: ctrl_lock, exclusive termios_rwsem
369  */
370 
371 static void n_tty_flush_buffer(struct tty_struct *tty)
372 {
373 	down_write(&tty->termios_rwsem);
374 	reset_buffer_flags(tty->disc_data);
375 	n_tty_kick_worker(tty);
376 
377 	if (tty->link)
378 		n_tty_packet_mode_flush(tty);
379 	up_write(&tty->termios_rwsem);
380 }
381 
382 /**
383  *	is_utf8_continuation	-	utf8 multibyte check
384  *	@c: byte to check
385  *
386  *	Returns true if the utf8 character 'c' is a multibyte continuation
387  *	character. We use this to correctly compute the on screen size
388  *	of the character when printing
389  */
390 
391 static inline int is_utf8_continuation(unsigned char c)
392 {
393 	return (c & 0xc0) == 0x80;
394 }
395 
396 /**
397  *	is_continuation		-	multibyte check
398  *	@c: byte to check
399  *	@tty: terminal device
400  *
401  *	Returns true if the utf8 character 'c' is a multibyte continuation
402  *	character and the terminal is in unicode mode.
403  */
404 
405 static inline int is_continuation(unsigned char c, struct tty_struct *tty)
406 {
407 	return I_IUTF8(tty) && is_utf8_continuation(c);
408 }
409 
410 /**
411  *	do_output_char			-	output one character
412  *	@c: character (or partial unicode symbol)
413  *	@tty: terminal device
414  *	@space: space available in tty driver write buffer
415  *
416  *	This is a helper function that handles one output character
417  *	(including special characters like TAB, CR, LF, etc.),
418  *	doing OPOST processing and putting the results in the
419  *	tty driver's write buffer.
420  *
421  *	Note that Linux currently ignores TABDLY, CRDLY, VTDLY, FFDLY
422  *	and NLDLY.  They simply aren't relevant in the world today.
423  *	If you ever need them, add them here.
424  *
425  *	Returns the number of bytes of buffer space used or -1 if
426  *	no space left.
427  *
428  *	Locking: should be called under the output_lock to protect
429  *		 the column state and space left in the buffer
430  */
431 
432 static int do_output_char(unsigned char c, struct tty_struct *tty, int space)
433 {
434 	struct n_tty_data *ldata = tty->disc_data;
435 	int	spaces;
436 
437 	if (!space)
438 		return -1;
439 
440 	switch (c) {
441 	case '\n':
442 		if (O_ONLRET(tty))
443 			ldata->column = 0;
444 		if (O_ONLCR(tty)) {
445 			if (space < 2)
446 				return -1;
447 			ldata->canon_column = ldata->column = 0;
448 			tty->ops->write(tty, "\r\n", 2);
449 			return 2;
450 		}
451 		ldata->canon_column = ldata->column;
452 		break;
453 	case '\r':
454 		if (O_ONOCR(tty) && ldata->column == 0)
455 			return 0;
456 		if (O_OCRNL(tty)) {
457 			c = '\n';
458 			if (O_ONLRET(tty))
459 				ldata->canon_column = ldata->column = 0;
460 			break;
461 		}
462 		ldata->canon_column = ldata->column = 0;
463 		break;
464 	case '\t':
465 		spaces = 8 - (ldata->column & 7);
466 		if (O_TABDLY(tty) == XTABS) {
467 			if (space < spaces)
468 				return -1;
469 			ldata->column += spaces;
470 			tty->ops->write(tty, "        ", spaces);
471 			return spaces;
472 		}
473 		ldata->column += spaces;
474 		break;
475 	case '\b':
476 		if (ldata->column > 0)
477 			ldata->column--;
478 		break;
479 	default:
480 		if (!iscntrl(c)) {
481 			if (O_OLCUC(tty))
482 				c = toupper(c);
483 			if (!is_continuation(c, tty))
484 				ldata->column++;
485 		}
486 		break;
487 	}
488 
489 	tty_put_char(tty, c);
490 	return 1;
491 }
492 
493 /**
494  *	process_output			-	output post processor
495  *	@c: character (or partial unicode symbol)
496  *	@tty: terminal device
497  *
498  *	Output one character with OPOST processing.
499  *	Returns -1 when the output device is full and the character
500  *	must be retried.
501  *
502  *	Locking: output_lock to protect column state and space left
503  *		 (also, this is called from n_tty_write under the
504  *		  tty layer write lock)
505  */
506 
507 static int process_output(unsigned char c, struct tty_struct *tty)
508 {
509 	struct n_tty_data *ldata = tty->disc_data;
510 	int	space, retval;
511 
512 	mutex_lock(&ldata->output_lock);
513 
514 	space = tty_write_room(tty);
515 	retval = do_output_char(c, tty, space);
516 
517 	mutex_unlock(&ldata->output_lock);
518 	if (retval < 0)
519 		return -1;
520 	else
521 		return 0;
522 }
523 
524 /**
525  *	process_output_block		-	block post processor
526  *	@tty: terminal device
527  *	@buf: character buffer
528  *	@nr: number of bytes to output
529  *
530  *	Output a block of characters with OPOST processing.
531  *	Returns the number of characters output.
532  *
533  *	This path is used to speed up block console writes, among other
534  *	things when processing blocks of output data. It handles only
535  *	the simple cases normally found and helps to generate blocks of
536  *	symbols for the console driver and thus improve performance.
537  *
538  *	Locking: output_lock to protect column state and space left
539  *		 (also, this is called from n_tty_write under the
540  *		  tty layer write lock)
541  */
542 
543 static ssize_t process_output_block(struct tty_struct *tty,
544 				    const unsigned char *buf, unsigned int nr)
545 {
546 	struct n_tty_data *ldata = tty->disc_data;
547 	int	space;
548 	int	i;
549 	const unsigned char *cp;
550 
551 	mutex_lock(&ldata->output_lock);
552 
553 	space = tty_write_room(tty);
554 	if (space <= 0) {
555 		mutex_unlock(&ldata->output_lock);
556 		return space;
557 	}
558 	if (nr > space)
559 		nr = space;
560 
561 	for (i = 0, cp = buf; i < nr; i++, cp++) {
562 		unsigned char c = *cp;
563 
564 		switch (c) {
565 		case '\n':
566 			if (O_ONLRET(tty))
567 				ldata->column = 0;
568 			if (O_ONLCR(tty))
569 				goto break_out;
570 			ldata->canon_column = ldata->column;
571 			break;
572 		case '\r':
573 			if (O_ONOCR(tty) && ldata->column == 0)
574 				goto break_out;
575 			if (O_OCRNL(tty))
576 				goto break_out;
577 			ldata->canon_column = ldata->column = 0;
578 			break;
579 		case '\t':
580 			goto break_out;
581 		case '\b':
582 			if (ldata->column > 0)
583 				ldata->column--;
584 			break;
585 		default:
586 			if (!iscntrl(c)) {
587 				if (O_OLCUC(tty))
588 					goto break_out;
589 				if (!is_continuation(c, tty))
590 					ldata->column++;
591 			}
592 			break;
593 		}
594 	}
595 break_out:
596 	i = tty->ops->write(tty, buf, i);
597 
598 	mutex_unlock(&ldata->output_lock);
599 	return i;
600 }
601 
602 /**
603  *	process_echoes	-	write pending echo characters
604  *	@tty: terminal device
605  *
606  *	Write previously buffered echo (and other ldisc-generated)
607  *	characters to the tty.
608  *
609  *	Characters generated by the ldisc (including echoes) need to
610  *	be buffered because the driver's write buffer can fill during
611  *	heavy program output.  Echoing straight to the driver will
612  *	often fail under these conditions, causing lost characters and
613  *	resulting mismatches of ldisc state information.
614  *
615  *	Since the ldisc state must represent the characters actually sent
616  *	to the driver at the time of the write, operations like certain
617  *	changes in column state are also saved in the buffer and executed
618  *	here.
619  *
620  *	A circular fifo buffer is used so that the most recent characters
621  *	are prioritized.  Also, when control characters are echoed with a
622  *	prefixed "^", the pair is treated atomically and thus not separated.
623  *
624  *	Locking: callers must hold output_lock
625  */
626 
627 static size_t __process_echoes(struct tty_struct *tty)
628 {
629 	struct n_tty_data *ldata = tty->disc_data;
630 	int	space, old_space;
631 	size_t tail;
632 	unsigned char c;
633 
634 	old_space = space = tty_write_room(tty);
635 
636 	tail = ldata->echo_tail;
637 	while (MASK(ldata->echo_commit) != MASK(tail)) {
638 		c = echo_buf(ldata, tail);
639 		if (c == ECHO_OP_START) {
640 			unsigned char op;
641 			int no_space_left = 0;
642 
643 			/*
644 			 * Since add_echo_byte() is called without holding
645 			 * output_lock, we might see only portion of multi-byte
646 			 * operation.
647 			 */
648 			if (MASK(ldata->echo_commit) == MASK(tail + 1))
649 				goto not_yet_stored;
650 			/*
651 			 * If the buffer byte is the start of a multi-byte
652 			 * operation, get the next byte, which is either the
653 			 * op code or a control character value.
654 			 */
655 			op = echo_buf(ldata, tail + 1);
656 
657 			switch (op) {
658 			case ECHO_OP_ERASE_TAB: {
659 				unsigned int num_chars, num_bs;
660 
661 				if (MASK(ldata->echo_commit) == MASK(tail + 2))
662 					goto not_yet_stored;
663 				num_chars = echo_buf(ldata, tail + 2);
664 
665 				/*
666 				 * Determine how many columns to go back
667 				 * in order to erase the tab.
668 				 * This depends on the number of columns
669 				 * used by other characters within the tab
670 				 * area.  If this (modulo 8) count is from
671 				 * the start of input rather than from a
672 				 * previous tab, we offset by canon column.
673 				 * Otherwise, tab spacing is normal.
674 				 */
675 				if (!(num_chars & 0x80))
676 					num_chars += ldata->canon_column;
677 				num_bs = 8 - (num_chars & 7);
678 
679 				if (num_bs > space) {
680 					no_space_left = 1;
681 					break;
682 				}
683 				space -= num_bs;
684 				while (num_bs--) {
685 					tty_put_char(tty, '\b');
686 					if (ldata->column > 0)
687 						ldata->column--;
688 				}
689 				tail += 3;
690 				break;
691 			}
692 			case ECHO_OP_SET_CANON_COL:
693 				ldata->canon_column = ldata->column;
694 				tail += 2;
695 				break;
696 
697 			case ECHO_OP_MOVE_BACK_COL:
698 				if (ldata->column > 0)
699 					ldata->column--;
700 				tail += 2;
701 				break;
702 
703 			case ECHO_OP_START:
704 				/* This is an escaped echo op start code */
705 				if (!space) {
706 					no_space_left = 1;
707 					break;
708 				}
709 				tty_put_char(tty, ECHO_OP_START);
710 				ldata->column++;
711 				space--;
712 				tail += 2;
713 				break;
714 
715 			default:
716 				/*
717 				 * If the op is not a special byte code,
718 				 * it is a ctrl char tagged to be echoed
719 				 * as "^X" (where X is the letter
720 				 * representing the control char).
721 				 * Note that we must ensure there is
722 				 * enough space for the whole ctrl pair.
723 				 *
724 				 */
725 				if (space < 2) {
726 					no_space_left = 1;
727 					break;
728 				}
729 				tty_put_char(tty, '^');
730 				tty_put_char(tty, op ^ 0100);
731 				ldata->column += 2;
732 				space -= 2;
733 				tail += 2;
734 			}
735 
736 			if (no_space_left)
737 				break;
738 		} else {
739 			if (O_OPOST(tty)) {
740 				int retval = do_output_char(c, tty, space);
741 				if (retval < 0)
742 					break;
743 				space -= retval;
744 			} else {
745 				if (!space)
746 					break;
747 				tty_put_char(tty, c);
748 				space -= 1;
749 			}
750 			tail += 1;
751 		}
752 	}
753 
754 	/* If the echo buffer is nearly full (so that the possibility exists
755 	 * of echo overrun before the next commit), then discard enough
756 	 * data at the tail to prevent a subsequent overrun */
757 	while (ldata->echo_commit > tail &&
758 	       ldata->echo_commit - tail >= ECHO_DISCARD_WATERMARK) {
759 		if (echo_buf(ldata, tail) == ECHO_OP_START) {
760 			if (echo_buf(ldata, tail + 1) == ECHO_OP_ERASE_TAB)
761 				tail += 3;
762 			else
763 				tail += 2;
764 		} else
765 			tail++;
766 	}
767 
768  not_yet_stored:
769 	ldata->echo_tail = tail;
770 	return old_space - space;
771 }
772 
773 static void commit_echoes(struct tty_struct *tty)
774 {
775 	struct n_tty_data *ldata = tty->disc_data;
776 	size_t nr, old, echoed;
777 	size_t head;
778 
779 	mutex_lock(&ldata->output_lock);
780 	head = ldata->echo_head;
781 	ldata->echo_mark = head;
782 	old = ldata->echo_commit - ldata->echo_tail;
783 
784 	/* Process committed echoes if the accumulated # of bytes
785 	 * is over the threshold (and try again each time another
786 	 * block is accumulated) */
787 	nr = head - ldata->echo_tail;
788 	if (nr < ECHO_COMMIT_WATERMARK ||
789 	    (nr % ECHO_BLOCK > old % ECHO_BLOCK)) {
790 		mutex_unlock(&ldata->output_lock);
791 		return;
792 	}
793 
794 	ldata->echo_commit = head;
795 	echoed = __process_echoes(tty);
796 	mutex_unlock(&ldata->output_lock);
797 
798 	if (echoed && tty->ops->flush_chars)
799 		tty->ops->flush_chars(tty);
800 }
801 
802 static void process_echoes(struct tty_struct *tty)
803 {
804 	struct n_tty_data *ldata = tty->disc_data;
805 	size_t echoed;
806 
807 	if (ldata->echo_mark == ldata->echo_tail)
808 		return;
809 
810 	mutex_lock(&ldata->output_lock);
811 	ldata->echo_commit = ldata->echo_mark;
812 	echoed = __process_echoes(tty);
813 	mutex_unlock(&ldata->output_lock);
814 
815 	if (echoed && tty->ops->flush_chars)
816 		tty->ops->flush_chars(tty);
817 }
818 
819 /* NB: echo_mark and echo_head should be equivalent here */
820 static void flush_echoes(struct tty_struct *tty)
821 {
822 	struct n_tty_data *ldata = tty->disc_data;
823 
824 	if ((!L_ECHO(tty) && !L_ECHONL(tty)) ||
825 	    ldata->echo_commit == ldata->echo_head)
826 		return;
827 
828 	mutex_lock(&ldata->output_lock);
829 	ldata->echo_commit = ldata->echo_head;
830 	__process_echoes(tty);
831 	mutex_unlock(&ldata->output_lock);
832 }
833 
834 /**
835  *	add_echo_byte	-	add a byte to the echo buffer
836  *	@c: unicode byte to echo
837  *	@ldata: n_tty data
838  *
839  *	Add a character or operation byte to the echo buffer.
840  */
841 
842 static inline void add_echo_byte(unsigned char c, struct n_tty_data *ldata)
843 {
844 	*echo_buf_addr(ldata, ldata->echo_head) = c;
845 	smp_wmb(); /* Matches smp_rmb() in echo_buf(). */
846 	ldata->echo_head++;
847 }
848 
849 /**
850  *	echo_move_back_col	-	add operation to move back a column
851  *	@ldata: n_tty data
852  *
853  *	Add an operation to the echo buffer to move back one column.
854  */
855 
856 static void echo_move_back_col(struct n_tty_data *ldata)
857 {
858 	add_echo_byte(ECHO_OP_START, ldata);
859 	add_echo_byte(ECHO_OP_MOVE_BACK_COL, ldata);
860 }
861 
862 /**
863  *	echo_set_canon_col	-	add operation to set the canon column
864  *	@ldata: n_tty data
865  *
866  *	Add an operation to the echo buffer to set the canon column
867  *	to the current column.
868  */
869 
870 static void echo_set_canon_col(struct n_tty_data *ldata)
871 {
872 	add_echo_byte(ECHO_OP_START, ldata);
873 	add_echo_byte(ECHO_OP_SET_CANON_COL, ldata);
874 }
875 
876 /**
877  *	echo_erase_tab	-	add operation to erase a tab
878  *	@num_chars: number of character columns already used
879  *	@after_tab: true if num_chars starts after a previous tab
880  *	@ldata: n_tty data
881  *
882  *	Add an operation to the echo buffer to erase a tab.
883  *
884  *	Called by the eraser function, which knows how many character
885  *	columns have been used since either a previous tab or the start
886  *	of input.  This information will be used later, along with
887  *	canon column (if applicable), to go back the correct number
888  *	of columns.
889  */
890 
891 static void echo_erase_tab(unsigned int num_chars, int after_tab,
892 			   struct n_tty_data *ldata)
893 {
894 	add_echo_byte(ECHO_OP_START, ldata);
895 	add_echo_byte(ECHO_OP_ERASE_TAB, ldata);
896 
897 	/* We only need to know this modulo 8 (tab spacing) */
898 	num_chars &= 7;
899 
900 	/* Set the high bit as a flag if num_chars is after a previous tab */
901 	if (after_tab)
902 		num_chars |= 0x80;
903 
904 	add_echo_byte(num_chars, ldata);
905 }
906 
907 /**
908  *	echo_char_raw	-	echo a character raw
909  *	@c: unicode byte to echo
910  *	@ldata: line disc data
911  *
912  *	Echo user input back onto the screen. This must be called only when
913  *	L_ECHO(tty) is true. Called from the driver receive_buf path.
914  *
915  *	This variant does not treat control characters specially.
916  */
917 
918 static void echo_char_raw(unsigned char c, struct n_tty_data *ldata)
919 {
920 	if (c == ECHO_OP_START) {
921 		add_echo_byte(ECHO_OP_START, ldata);
922 		add_echo_byte(ECHO_OP_START, ldata);
923 	} else {
924 		add_echo_byte(c, ldata);
925 	}
926 }
927 
928 /**
929  *	echo_char	-	echo a character
930  *	@c: unicode byte to echo
931  *	@tty: terminal device
932  *
933  *	Echo user input back onto the screen. This must be called only when
934  *	L_ECHO(tty) is true. Called from the driver receive_buf path.
935  *
936  *	This variant tags control characters to be echoed as "^X"
937  *	(where X is the letter representing the control char).
938  */
939 
940 static void echo_char(unsigned char c, struct tty_struct *tty)
941 {
942 	struct n_tty_data *ldata = tty->disc_data;
943 
944 	if (c == ECHO_OP_START) {
945 		add_echo_byte(ECHO_OP_START, ldata);
946 		add_echo_byte(ECHO_OP_START, ldata);
947 	} else {
948 		if (L_ECHOCTL(tty) && iscntrl(c) && c != '\t')
949 			add_echo_byte(ECHO_OP_START, ldata);
950 		add_echo_byte(c, ldata);
951 	}
952 }
953 
954 /**
955  *	finish_erasing		-	complete erase
956  *	@ldata: n_tty data
957  */
958 
959 static inline void finish_erasing(struct n_tty_data *ldata)
960 {
961 	if (ldata->erasing) {
962 		echo_char_raw('/', ldata);
963 		ldata->erasing = 0;
964 	}
965 }
966 
967 /**
968  *	eraser		-	handle erase function
969  *	@c: character input
970  *	@tty: terminal device
971  *
972  *	Perform erase and necessary output when an erase character is
973  *	present in the stream from the driver layer. Handles the complexities
974  *	of UTF-8 multibyte symbols.
975  *
976  *	n_tty_receive_buf()/producer path:
977  *		caller holds non-exclusive termios_rwsem
978  */
979 
980 static void eraser(unsigned char c, struct tty_struct *tty)
981 {
982 	struct n_tty_data *ldata = tty->disc_data;
983 	enum { ERASE, WERASE, KILL } kill_type;
984 	size_t head;
985 	size_t cnt;
986 	int seen_alnums;
987 
988 	if (ldata->read_head == ldata->canon_head) {
989 		/* process_output('\a', tty); */ /* what do you think? */
990 		return;
991 	}
992 	if (c == ERASE_CHAR(tty))
993 		kill_type = ERASE;
994 	else if (c == WERASE_CHAR(tty))
995 		kill_type = WERASE;
996 	else {
997 		if (!L_ECHO(tty)) {
998 			ldata->read_head = ldata->canon_head;
999 			return;
1000 		}
1001 		if (!L_ECHOK(tty) || !L_ECHOKE(tty) || !L_ECHOE(tty)) {
1002 			ldata->read_head = ldata->canon_head;
1003 			finish_erasing(ldata);
1004 			echo_char(KILL_CHAR(tty), tty);
1005 			/* Add a newline if ECHOK is on and ECHOKE is off. */
1006 			if (L_ECHOK(tty))
1007 				echo_char_raw('\n', ldata);
1008 			return;
1009 		}
1010 		kill_type = KILL;
1011 	}
1012 
1013 	seen_alnums = 0;
1014 	while (MASK(ldata->read_head) != MASK(ldata->canon_head)) {
1015 		head = ldata->read_head;
1016 
1017 		/* erase a single possibly multibyte character */
1018 		do {
1019 			head--;
1020 			c = read_buf(ldata, head);
1021 		} while (is_continuation(c, tty) &&
1022 			 MASK(head) != MASK(ldata->canon_head));
1023 
1024 		/* do not partially erase */
1025 		if (is_continuation(c, tty))
1026 			break;
1027 
1028 		if (kill_type == WERASE) {
1029 			/* Equivalent to BSD's ALTWERASE. */
1030 			if (isalnum(c) || c == '_')
1031 				seen_alnums++;
1032 			else if (seen_alnums)
1033 				break;
1034 		}
1035 		cnt = ldata->read_head - head;
1036 		ldata->read_head = head;
1037 		if (L_ECHO(tty)) {
1038 			if (L_ECHOPRT(tty)) {
1039 				if (!ldata->erasing) {
1040 					echo_char_raw('\\', ldata);
1041 					ldata->erasing = 1;
1042 				}
1043 				/* if cnt > 1, output a multi-byte character */
1044 				echo_char(c, tty);
1045 				while (--cnt > 0) {
1046 					head++;
1047 					echo_char_raw(read_buf(ldata, head), ldata);
1048 					echo_move_back_col(ldata);
1049 				}
1050 			} else if (kill_type == ERASE && !L_ECHOE(tty)) {
1051 				echo_char(ERASE_CHAR(tty), tty);
1052 			} else if (c == '\t') {
1053 				unsigned int num_chars = 0;
1054 				int after_tab = 0;
1055 				size_t tail = ldata->read_head;
1056 
1057 				/*
1058 				 * Count the columns used for characters
1059 				 * since the start of input or after a
1060 				 * previous tab.
1061 				 * This info is used to go back the correct
1062 				 * number of columns.
1063 				 */
1064 				while (MASK(tail) != MASK(ldata->canon_head)) {
1065 					tail--;
1066 					c = read_buf(ldata, tail);
1067 					if (c == '\t') {
1068 						after_tab = 1;
1069 						break;
1070 					} else if (iscntrl(c)) {
1071 						if (L_ECHOCTL(tty))
1072 							num_chars += 2;
1073 					} else if (!is_continuation(c, tty)) {
1074 						num_chars++;
1075 					}
1076 				}
1077 				echo_erase_tab(num_chars, after_tab, ldata);
1078 			} else {
1079 				if (iscntrl(c) && L_ECHOCTL(tty)) {
1080 					echo_char_raw('\b', ldata);
1081 					echo_char_raw(' ', ldata);
1082 					echo_char_raw('\b', ldata);
1083 				}
1084 				if (!iscntrl(c) || L_ECHOCTL(tty)) {
1085 					echo_char_raw('\b', ldata);
1086 					echo_char_raw(' ', ldata);
1087 					echo_char_raw('\b', ldata);
1088 				}
1089 			}
1090 		}
1091 		if (kill_type == ERASE)
1092 			break;
1093 	}
1094 	if (ldata->read_head == ldata->canon_head && L_ECHO(tty))
1095 		finish_erasing(ldata);
1096 }
1097 
1098 /**
1099  *	isig		-	handle the ISIG optio
1100  *	@sig: signal
1101  *	@tty: terminal
1102  *
1103  *	Called when a signal is being sent due to terminal input.
1104  *	Called from the driver receive_buf path so serialized.
1105  *
1106  *	Performs input and output flush if !NOFLSH. In this context, the echo
1107  *	buffer is 'output'. The signal is processed first to alert any current
1108  *	readers or writers to discontinue and exit their i/o loops.
1109  *
1110  *	Locking: ctrl_lock
1111  */
1112 
1113 static void __isig(int sig, struct tty_struct *tty)
1114 {
1115 	struct pid *tty_pgrp = tty_get_pgrp(tty);
1116 	if (tty_pgrp) {
1117 		kill_pgrp(tty_pgrp, sig, 1);
1118 		put_pid(tty_pgrp);
1119 	}
1120 }
1121 
1122 static void isig(int sig, struct tty_struct *tty)
1123 {
1124 	struct n_tty_data *ldata = tty->disc_data;
1125 
1126 	if (L_NOFLSH(tty)) {
1127 		/* signal only */
1128 		__isig(sig, tty);
1129 
1130 	} else { /* signal and flush */
1131 		up_read(&tty->termios_rwsem);
1132 		down_write(&tty->termios_rwsem);
1133 
1134 		__isig(sig, tty);
1135 
1136 		/* clear echo buffer */
1137 		mutex_lock(&ldata->output_lock);
1138 		ldata->echo_head = ldata->echo_tail = 0;
1139 		ldata->echo_mark = ldata->echo_commit = 0;
1140 		mutex_unlock(&ldata->output_lock);
1141 
1142 		/* clear output buffer */
1143 		tty_driver_flush_buffer(tty);
1144 
1145 		/* clear input buffer */
1146 		reset_buffer_flags(tty->disc_data);
1147 
1148 		/* notify pty master of flush */
1149 		if (tty->link)
1150 			n_tty_packet_mode_flush(tty);
1151 
1152 		up_write(&tty->termios_rwsem);
1153 		down_read(&tty->termios_rwsem);
1154 	}
1155 }
1156 
1157 /**
1158  *	n_tty_receive_break	-	handle break
1159  *	@tty: terminal
1160  *
1161  *	An RS232 break event has been hit in the incoming bitstream. This
1162  *	can cause a variety of events depending upon the termios settings.
1163  *
1164  *	n_tty_receive_buf()/producer path:
1165  *		caller holds non-exclusive termios_rwsem
1166  *
1167  *	Note: may get exclusive termios_rwsem if flushing input buffer
1168  */
1169 
1170 static void n_tty_receive_break(struct tty_struct *tty)
1171 {
1172 	struct n_tty_data *ldata = tty->disc_data;
1173 
1174 	if (I_IGNBRK(tty))
1175 		return;
1176 	if (I_BRKINT(tty)) {
1177 		isig(SIGINT, tty);
1178 		return;
1179 	}
1180 	if (I_PARMRK(tty)) {
1181 		put_tty_queue('\377', ldata);
1182 		put_tty_queue('\0', ldata);
1183 	}
1184 	put_tty_queue('\0', ldata);
1185 }
1186 
1187 /**
1188  *	n_tty_receive_overrun	-	handle overrun reporting
1189  *	@tty: terminal
1190  *
1191  *	Data arrived faster than we could process it. While the tty
1192  *	driver has flagged this the bits that were missed are gone
1193  *	forever.
1194  *
1195  *	Called from the receive_buf path so single threaded. Does not
1196  *	need locking as num_overrun and overrun_time are function
1197  *	private.
1198  */
1199 
1200 static void n_tty_receive_overrun(struct tty_struct *tty)
1201 {
1202 	struct n_tty_data *ldata = tty->disc_data;
1203 
1204 	ldata->num_overrun++;
1205 	if (time_after(jiffies, ldata->overrun_time + HZ) ||
1206 			time_after(ldata->overrun_time, jiffies)) {
1207 		tty_warn(tty, "%d input overrun(s)\n", ldata->num_overrun);
1208 		ldata->overrun_time = jiffies;
1209 		ldata->num_overrun = 0;
1210 	}
1211 }
1212 
1213 /**
1214  *	n_tty_receive_parity_error	-	error notifier
1215  *	@tty: terminal device
1216  *	@c: character
1217  *
1218  *	Process a parity error and queue the right data to indicate
1219  *	the error case if necessary.
1220  *
1221  *	n_tty_receive_buf()/producer path:
1222  *		caller holds non-exclusive termios_rwsem
1223  */
1224 static void n_tty_receive_parity_error(struct tty_struct *tty, unsigned char c)
1225 {
1226 	struct n_tty_data *ldata = tty->disc_data;
1227 
1228 	if (I_INPCK(tty)) {
1229 		if (I_IGNPAR(tty))
1230 			return;
1231 		if (I_PARMRK(tty)) {
1232 			put_tty_queue('\377', ldata);
1233 			put_tty_queue('\0', ldata);
1234 			put_tty_queue(c, ldata);
1235 		} else
1236 			put_tty_queue('\0', ldata);
1237 	} else
1238 		put_tty_queue(c, ldata);
1239 }
1240 
1241 static void
1242 n_tty_receive_signal_char(struct tty_struct *tty, int signal, unsigned char c)
1243 {
1244 	isig(signal, tty);
1245 	if (I_IXON(tty))
1246 		start_tty(tty);
1247 	if (L_ECHO(tty)) {
1248 		echo_char(c, tty);
1249 		commit_echoes(tty);
1250 	} else
1251 		process_echoes(tty);
1252 	return;
1253 }
1254 
1255 /**
1256  *	n_tty_receive_char	-	perform processing
1257  *	@tty: terminal device
1258  *	@c: character
1259  *
1260  *	Process an individual character of input received from the driver.
1261  *	This is serialized with respect to itself by the rules for the
1262  *	driver above.
1263  *
1264  *	n_tty_receive_buf()/producer path:
1265  *		caller holds non-exclusive termios_rwsem
1266  *		publishes canon_head if canonical mode is active
1267  *
1268  *	Returns 1 if LNEXT was received, else returns 0
1269  */
1270 
1271 static int
1272 n_tty_receive_char_special(struct tty_struct *tty, unsigned char c)
1273 {
1274 	struct n_tty_data *ldata = tty->disc_data;
1275 
1276 	if (I_IXON(tty)) {
1277 		if (c == START_CHAR(tty)) {
1278 			start_tty(tty);
1279 			process_echoes(tty);
1280 			return 0;
1281 		}
1282 		if (c == STOP_CHAR(tty)) {
1283 			stop_tty(tty);
1284 			return 0;
1285 		}
1286 	}
1287 
1288 	if (L_ISIG(tty)) {
1289 		if (c == INTR_CHAR(tty)) {
1290 			n_tty_receive_signal_char(tty, SIGINT, c);
1291 			return 0;
1292 		} else if (c == QUIT_CHAR(tty)) {
1293 			n_tty_receive_signal_char(tty, SIGQUIT, c);
1294 			return 0;
1295 		} else if (c == SUSP_CHAR(tty)) {
1296 			n_tty_receive_signal_char(tty, SIGTSTP, c);
1297 			return 0;
1298 		}
1299 	}
1300 
1301 	if (tty->stopped && !tty->flow_stopped && I_IXON(tty) && I_IXANY(tty)) {
1302 		start_tty(tty);
1303 		process_echoes(tty);
1304 	}
1305 
1306 	if (c == '\r') {
1307 		if (I_IGNCR(tty))
1308 			return 0;
1309 		if (I_ICRNL(tty))
1310 			c = '\n';
1311 	} else if (c == '\n' && I_INLCR(tty))
1312 		c = '\r';
1313 
1314 	if (ldata->icanon) {
1315 		if (c == ERASE_CHAR(tty) || c == KILL_CHAR(tty) ||
1316 		    (c == WERASE_CHAR(tty) && L_IEXTEN(tty))) {
1317 			eraser(c, tty);
1318 			commit_echoes(tty);
1319 			return 0;
1320 		}
1321 		if (c == LNEXT_CHAR(tty) && L_IEXTEN(tty)) {
1322 			ldata->lnext = 1;
1323 			if (L_ECHO(tty)) {
1324 				finish_erasing(ldata);
1325 				if (L_ECHOCTL(tty)) {
1326 					echo_char_raw('^', ldata);
1327 					echo_char_raw('\b', ldata);
1328 					commit_echoes(tty);
1329 				}
1330 			}
1331 			return 1;
1332 		}
1333 		if (c == REPRINT_CHAR(tty) && L_ECHO(tty) && L_IEXTEN(tty)) {
1334 			size_t tail = ldata->canon_head;
1335 
1336 			finish_erasing(ldata);
1337 			echo_char(c, tty);
1338 			echo_char_raw('\n', ldata);
1339 			while (MASK(tail) != MASK(ldata->read_head)) {
1340 				echo_char(read_buf(ldata, tail), tty);
1341 				tail++;
1342 			}
1343 			commit_echoes(tty);
1344 			return 0;
1345 		}
1346 		if (c == '\n') {
1347 			if (L_ECHO(tty) || L_ECHONL(tty)) {
1348 				echo_char_raw('\n', ldata);
1349 				commit_echoes(tty);
1350 			}
1351 			goto handle_newline;
1352 		}
1353 		if (c == EOF_CHAR(tty)) {
1354 			c = __DISABLED_CHAR;
1355 			goto handle_newline;
1356 		}
1357 		if ((c == EOL_CHAR(tty)) ||
1358 		    (c == EOL2_CHAR(tty) && L_IEXTEN(tty))) {
1359 			/*
1360 			 * XXX are EOL_CHAR and EOL2_CHAR echoed?!?
1361 			 */
1362 			if (L_ECHO(tty)) {
1363 				/* Record the column of first canon char. */
1364 				if (ldata->canon_head == ldata->read_head)
1365 					echo_set_canon_col(ldata);
1366 				echo_char(c, tty);
1367 				commit_echoes(tty);
1368 			}
1369 			/*
1370 			 * XXX does PARMRK doubling happen for
1371 			 * EOL_CHAR and EOL2_CHAR?
1372 			 */
1373 			if (c == (unsigned char) '\377' && I_PARMRK(tty))
1374 				put_tty_queue(c, ldata);
1375 
1376 handle_newline:
1377 			set_bit(ldata->read_head & (N_TTY_BUF_SIZE - 1), ldata->read_flags);
1378 			put_tty_queue(c, ldata);
1379 			smp_store_release(&ldata->canon_head, ldata->read_head);
1380 			kill_fasync(&tty->fasync, SIGIO, POLL_IN);
1381 			wake_up_interruptible_poll(&tty->read_wait, EPOLLIN);
1382 			return 0;
1383 		}
1384 	}
1385 
1386 	if (L_ECHO(tty)) {
1387 		finish_erasing(ldata);
1388 		if (c == '\n')
1389 			echo_char_raw('\n', ldata);
1390 		else {
1391 			/* Record the column of first canon char. */
1392 			if (ldata->canon_head == ldata->read_head)
1393 				echo_set_canon_col(ldata);
1394 			echo_char(c, tty);
1395 		}
1396 		commit_echoes(tty);
1397 	}
1398 
1399 	/* PARMRK doubling check */
1400 	if (c == (unsigned char) '\377' && I_PARMRK(tty))
1401 		put_tty_queue(c, ldata);
1402 
1403 	put_tty_queue(c, ldata);
1404 	return 0;
1405 }
1406 
1407 static inline void
1408 n_tty_receive_char_inline(struct tty_struct *tty, unsigned char c)
1409 {
1410 	struct n_tty_data *ldata = tty->disc_data;
1411 
1412 	if (tty->stopped && !tty->flow_stopped && I_IXON(tty) && I_IXANY(tty)) {
1413 		start_tty(tty);
1414 		process_echoes(tty);
1415 	}
1416 	if (L_ECHO(tty)) {
1417 		finish_erasing(ldata);
1418 		/* Record the column of first canon char. */
1419 		if (ldata->canon_head == ldata->read_head)
1420 			echo_set_canon_col(ldata);
1421 		echo_char(c, tty);
1422 		commit_echoes(tty);
1423 	}
1424 	/* PARMRK doubling check */
1425 	if (c == (unsigned char) '\377' && I_PARMRK(tty))
1426 		put_tty_queue(c, ldata);
1427 	put_tty_queue(c, ldata);
1428 }
1429 
1430 static void n_tty_receive_char(struct tty_struct *tty, unsigned char c)
1431 {
1432 	n_tty_receive_char_inline(tty, c);
1433 }
1434 
1435 static inline void
1436 n_tty_receive_char_fast(struct tty_struct *tty, unsigned char c)
1437 {
1438 	struct n_tty_data *ldata = tty->disc_data;
1439 
1440 	if (tty->stopped && !tty->flow_stopped && I_IXON(tty) && I_IXANY(tty)) {
1441 		start_tty(tty);
1442 		process_echoes(tty);
1443 	}
1444 	if (L_ECHO(tty)) {
1445 		finish_erasing(ldata);
1446 		/* Record the column of first canon char. */
1447 		if (ldata->canon_head == ldata->read_head)
1448 			echo_set_canon_col(ldata);
1449 		echo_char(c, tty);
1450 		commit_echoes(tty);
1451 	}
1452 	put_tty_queue(c, ldata);
1453 }
1454 
1455 static void n_tty_receive_char_closing(struct tty_struct *tty, unsigned char c)
1456 {
1457 	if (I_ISTRIP(tty))
1458 		c &= 0x7f;
1459 	if (I_IUCLC(tty) && L_IEXTEN(tty))
1460 		c = tolower(c);
1461 
1462 	if (I_IXON(tty)) {
1463 		if (c == STOP_CHAR(tty))
1464 			stop_tty(tty);
1465 		else if (c == START_CHAR(tty) ||
1466 			 (tty->stopped && !tty->flow_stopped && I_IXANY(tty) &&
1467 			  c != INTR_CHAR(tty) && c != QUIT_CHAR(tty) &&
1468 			  c != SUSP_CHAR(tty))) {
1469 			start_tty(tty);
1470 			process_echoes(tty);
1471 		}
1472 	}
1473 }
1474 
1475 static void
1476 n_tty_receive_char_flagged(struct tty_struct *tty, unsigned char c, char flag)
1477 {
1478 	switch (flag) {
1479 	case TTY_BREAK:
1480 		n_tty_receive_break(tty);
1481 		break;
1482 	case TTY_PARITY:
1483 	case TTY_FRAME:
1484 		n_tty_receive_parity_error(tty, c);
1485 		break;
1486 	case TTY_OVERRUN:
1487 		n_tty_receive_overrun(tty);
1488 		break;
1489 	default:
1490 		tty_err(tty, "unknown flag %d\n", flag);
1491 		break;
1492 	}
1493 }
1494 
1495 static void
1496 n_tty_receive_char_lnext(struct tty_struct *tty, unsigned char c, char flag)
1497 {
1498 	struct n_tty_data *ldata = tty->disc_data;
1499 
1500 	ldata->lnext = 0;
1501 	if (likely(flag == TTY_NORMAL)) {
1502 		if (I_ISTRIP(tty))
1503 			c &= 0x7f;
1504 		if (I_IUCLC(tty) && L_IEXTEN(tty))
1505 			c = tolower(c);
1506 		n_tty_receive_char(tty, c);
1507 	} else
1508 		n_tty_receive_char_flagged(tty, c, flag);
1509 }
1510 
1511 static void
1512 n_tty_receive_buf_real_raw(struct tty_struct *tty, const unsigned char *cp,
1513 			   char *fp, int count)
1514 {
1515 	struct n_tty_data *ldata = tty->disc_data;
1516 	size_t n, head;
1517 
1518 	head = ldata->read_head & (N_TTY_BUF_SIZE - 1);
1519 	n = min_t(size_t, count, N_TTY_BUF_SIZE - head);
1520 	memcpy(read_buf_addr(ldata, head), cp, n);
1521 	ldata->read_head += n;
1522 	cp += n;
1523 	count -= n;
1524 
1525 	head = ldata->read_head & (N_TTY_BUF_SIZE - 1);
1526 	n = min_t(size_t, count, N_TTY_BUF_SIZE - head);
1527 	memcpy(read_buf_addr(ldata, head), cp, n);
1528 	ldata->read_head += n;
1529 }
1530 
1531 static void
1532 n_tty_receive_buf_raw(struct tty_struct *tty, const unsigned char *cp,
1533 		      char *fp, int count)
1534 {
1535 	struct n_tty_data *ldata = tty->disc_data;
1536 	char flag = TTY_NORMAL;
1537 
1538 	while (count--) {
1539 		if (fp)
1540 			flag = *fp++;
1541 		if (likely(flag == TTY_NORMAL))
1542 			put_tty_queue(*cp++, ldata);
1543 		else
1544 			n_tty_receive_char_flagged(tty, *cp++, flag);
1545 	}
1546 }
1547 
1548 static void
1549 n_tty_receive_buf_closing(struct tty_struct *tty, const unsigned char *cp,
1550 			  char *fp, int count)
1551 {
1552 	char flag = TTY_NORMAL;
1553 
1554 	while (count--) {
1555 		if (fp)
1556 			flag = *fp++;
1557 		if (likely(flag == TTY_NORMAL))
1558 			n_tty_receive_char_closing(tty, *cp++);
1559 	}
1560 }
1561 
1562 static void
1563 n_tty_receive_buf_standard(struct tty_struct *tty, const unsigned char *cp,
1564 			  char *fp, int count)
1565 {
1566 	struct n_tty_data *ldata = tty->disc_data;
1567 	char flag = TTY_NORMAL;
1568 
1569 	while (count--) {
1570 		if (fp)
1571 			flag = *fp++;
1572 		if (likely(flag == TTY_NORMAL)) {
1573 			unsigned char c = *cp++;
1574 
1575 			if (I_ISTRIP(tty))
1576 				c &= 0x7f;
1577 			if (I_IUCLC(tty) && L_IEXTEN(tty))
1578 				c = tolower(c);
1579 			if (L_EXTPROC(tty)) {
1580 				put_tty_queue(c, ldata);
1581 				continue;
1582 			}
1583 			if (!test_bit(c, ldata->char_map))
1584 				n_tty_receive_char_inline(tty, c);
1585 			else if (n_tty_receive_char_special(tty, c) && count) {
1586 				if (fp)
1587 					flag = *fp++;
1588 				n_tty_receive_char_lnext(tty, *cp++, flag);
1589 				count--;
1590 			}
1591 		} else
1592 			n_tty_receive_char_flagged(tty, *cp++, flag);
1593 	}
1594 }
1595 
1596 static void
1597 n_tty_receive_buf_fast(struct tty_struct *tty, const unsigned char *cp,
1598 		       char *fp, int count)
1599 {
1600 	struct n_tty_data *ldata = tty->disc_data;
1601 	char flag = TTY_NORMAL;
1602 
1603 	while (count--) {
1604 		if (fp)
1605 			flag = *fp++;
1606 		if (likely(flag == TTY_NORMAL)) {
1607 			unsigned char c = *cp++;
1608 
1609 			if (!test_bit(c, ldata->char_map))
1610 				n_tty_receive_char_fast(tty, c);
1611 			else if (n_tty_receive_char_special(tty, c) && count) {
1612 				if (fp)
1613 					flag = *fp++;
1614 				n_tty_receive_char_lnext(tty, *cp++, flag);
1615 				count--;
1616 			}
1617 		} else
1618 			n_tty_receive_char_flagged(tty, *cp++, flag);
1619 	}
1620 }
1621 
1622 static void __receive_buf(struct tty_struct *tty, const unsigned char *cp,
1623 			  char *fp, int count)
1624 {
1625 	struct n_tty_data *ldata = tty->disc_data;
1626 	bool preops = I_ISTRIP(tty) || (I_IUCLC(tty) && L_IEXTEN(tty));
1627 
1628 	if (ldata->real_raw)
1629 		n_tty_receive_buf_real_raw(tty, cp, fp, count);
1630 	else if (ldata->raw || (L_EXTPROC(tty) && !preops))
1631 		n_tty_receive_buf_raw(tty, cp, fp, count);
1632 	else if (tty->closing && !L_EXTPROC(tty))
1633 		n_tty_receive_buf_closing(tty, cp, fp, count);
1634 	else {
1635 		if (ldata->lnext) {
1636 			char flag = TTY_NORMAL;
1637 
1638 			if (fp)
1639 				flag = *fp++;
1640 			n_tty_receive_char_lnext(tty, *cp++, flag);
1641 			count--;
1642 		}
1643 
1644 		if (!preops && !I_PARMRK(tty))
1645 			n_tty_receive_buf_fast(tty, cp, fp, count);
1646 		else
1647 			n_tty_receive_buf_standard(tty, cp, fp, count);
1648 
1649 		flush_echoes(tty);
1650 		if (tty->ops->flush_chars)
1651 			tty->ops->flush_chars(tty);
1652 	}
1653 
1654 	if (ldata->icanon && !L_EXTPROC(tty))
1655 		return;
1656 
1657 	/* publish read_head to consumer */
1658 	smp_store_release(&ldata->commit_head, ldata->read_head);
1659 
1660 	if (read_cnt(ldata)) {
1661 		kill_fasync(&tty->fasync, SIGIO, POLL_IN);
1662 		wake_up_interruptible_poll(&tty->read_wait, EPOLLIN);
1663 	}
1664 }
1665 
1666 /**
1667  *	n_tty_receive_buf_common	-	process input
1668  *	@tty: device to receive input
1669  *	@cp: input chars
1670  *	@fp: flags for each char (if NULL, all chars are TTY_NORMAL)
1671  *	@count: number of input chars in @cp
1672  *	@flow: enable flow control
1673  *
1674  *	Called by the terminal driver when a block of characters has
1675  *	been received. This function must be called from soft contexts
1676  *	not from interrupt context. The driver is responsible for making
1677  *	calls one at a time and in order (or using flush_to_ldisc)
1678  *
1679  *	Returns the # of input chars from @cp which were processed.
1680  *
1681  *	In canonical mode, the maximum line length is 4096 chars (including
1682  *	the line termination char); lines longer than 4096 chars are
1683  *	truncated. After 4095 chars, input data is still processed but
1684  *	not stored. Overflow processing ensures the tty can always
1685  *	receive more input until at least one line can be read.
1686  *
1687  *	In non-canonical mode, the read buffer will only accept 4095 chars;
1688  *	this provides the necessary space for a newline char if the input
1689  *	mode is switched to canonical.
1690  *
1691  *	Note it is possible for the read buffer to _contain_ 4096 chars
1692  *	in non-canonical mode: the read buffer could already contain the
1693  *	maximum canon line of 4096 chars when the mode is switched to
1694  *	non-canonical.
1695  *
1696  *	n_tty_receive_buf()/producer path:
1697  *		claims non-exclusive termios_rwsem
1698  *		publishes commit_head or canon_head
1699  */
1700 static int
1701 n_tty_receive_buf_common(struct tty_struct *tty, const unsigned char *cp,
1702 			 char *fp, int count, int flow)
1703 {
1704 	struct n_tty_data *ldata = tty->disc_data;
1705 	int room, n, rcvd = 0, overflow;
1706 
1707 	down_read(&tty->termios_rwsem);
1708 
1709 	do {
1710 		/*
1711 		 * When PARMRK is set, each input char may take up to 3 chars
1712 		 * in the read buf; reduce the buffer space avail by 3x
1713 		 *
1714 		 * If we are doing input canonicalization, and there are no
1715 		 * pending newlines, let characters through without limit, so
1716 		 * that erase characters will be handled.  Other excess
1717 		 * characters will be beeped.
1718 		 *
1719 		 * paired with store in *_copy_from_read_buf() -- guarantees
1720 		 * the consumer has loaded the data in read_buf up to the new
1721 		 * read_tail (so this producer will not overwrite unread data)
1722 		 */
1723 		size_t tail = smp_load_acquire(&ldata->read_tail);
1724 
1725 		room = N_TTY_BUF_SIZE - (ldata->read_head - tail);
1726 		if (I_PARMRK(tty))
1727 			room = (room + 2) / 3;
1728 		room--;
1729 		if (room <= 0) {
1730 			overflow = ldata->icanon && ldata->canon_head == tail;
1731 			if (overflow && room < 0)
1732 				ldata->read_head--;
1733 			room = overflow;
1734 			ldata->no_room = flow && !room;
1735 		} else
1736 			overflow = 0;
1737 
1738 		n = min(count, room);
1739 		if (!n)
1740 			break;
1741 
1742 		/* ignore parity errors if handling overflow */
1743 		if (!overflow || !fp || *fp != TTY_PARITY)
1744 			__receive_buf(tty, cp, fp, n);
1745 
1746 		cp += n;
1747 		if (fp)
1748 			fp += n;
1749 		count -= n;
1750 		rcvd += n;
1751 	} while (!test_bit(TTY_LDISC_CHANGING, &tty->flags));
1752 
1753 	tty->receive_room = room;
1754 
1755 	/* Unthrottle if handling overflow on pty */
1756 	if (tty->driver->type == TTY_DRIVER_TYPE_PTY) {
1757 		if (overflow) {
1758 			tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE);
1759 			tty_unthrottle_safe(tty);
1760 			__tty_set_flow_change(tty, 0);
1761 		}
1762 	} else
1763 		n_tty_check_throttle(tty);
1764 
1765 	up_read(&tty->termios_rwsem);
1766 
1767 	return rcvd;
1768 }
1769 
1770 static void n_tty_receive_buf(struct tty_struct *tty, const unsigned char *cp,
1771 			      char *fp, int count)
1772 {
1773 	n_tty_receive_buf_common(tty, cp, fp, count, 0);
1774 }
1775 
1776 static int n_tty_receive_buf2(struct tty_struct *tty, const unsigned char *cp,
1777 			      char *fp, int count)
1778 {
1779 	return n_tty_receive_buf_common(tty, cp, fp, count, 1);
1780 }
1781 
1782 /**
1783  *	n_tty_set_termios	-	termios data changed
1784  *	@tty: terminal
1785  *	@old: previous data
1786  *
1787  *	Called by the tty layer when the user changes termios flags so
1788  *	that the line discipline can plan ahead. This function cannot sleep
1789  *	and is protected from re-entry by the tty layer. The user is
1790  *	guaranteed that this function will not be re-entered or in progress
1791  *	when the ldisc is closed.
1792  *
1793  *	Locking: Caller holds tty->termios_rwsem
1794  */
1795 
1796 static void n_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
1797 {
1798 	struct n_tty_data *ldata = tty->disc_data;
1799 
1800 	if (!old || (old->c_lflag ^ tty->termios.c_lflag) & (ICANON | EXTPROC)) {
1801 		bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
1802 		ldata->line_start = ldata->read_tail;
1803 		if (!L_ICANON(tty) || !read_cnt(ldata)) {
1804 			ldata->canon_head = ldata->read_tail;
1805 			ldata->push = 0;
1806 		} else {
1807 			set_bit((ldata->read_head - 1) & (N_TTY_BUF_SIZE - 1),
1808 				ldata->read_flags);
1809 			ldata->canon_head = ldata->read_head;
1810 			ldata->push = 1;
1811 		}
1812 		ldata->commit_head = ldata->read_head;
1813 		ldata->erasing = 0;
1814 		ldata->lnext = 0;
1815 	}
1816 
1817 	ldata->icanon = (L_ICANON(tty) != 0);
1818 
1819 	if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
1820 	    I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
1821 	    I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
1822 	    I_PARMRK(tty)) {
1823 		bitmap_zero(ldata->char_map, 256);
1824 
1825 		if (I_IGNCR(tty) || I_ICRNL(tty))
1826 			set_bit('\r', ldata->char_map);
1827 		if (I_INLCR(tty))
1828 			set_bit('\n', ldata->char_map);
1829 
1830 		if (L_ICANON(tty)) {
1831 			set_bit(ERASE_CHAR(tty), ldata->char_map);
1832 			set_bit(KILL_CHAR(tty), ldata->char_map);
1833 			set_bit(EOF_CHAR(tty), ldata->char_map);
1834 			set_bit('\n', ldata->char_map);
1835 			set_bit(EOL_CHAR(tty), ldata->char_map);
1836 			if (L_IEXTEN(tty)) {
1837 				set_bit(WERASE_CHAR(tty), ldata->char_map);
1838 				set_bit(LNEXT_CHAR(tty), ldata->char_map);
1839 				set_bit(EOL2_CHAR(tty), ldata->char_map);
1840 				if (L_ECHO(tty))
1841 					set_bit(REPRINT_CHAR(tty),
1842 						ldata->char_map);
1843 			}
1844 		}
1845 		if (I_IXON(tty)) {
1846 			set_bit(START_CHAR(tty), ldata->char_map);
1847 			set_bit(STOP_CHAR(tty), ldata->char_map);
1848 		}
1849 		if (L_ISIG(tty)) {
1850 			set_bit(INTR_CHAR(tty), ldata->char_map);
1851 			set_bit(QUIT_CHAR(tty), ldata->char_map);
1852 			set_bit(SUSP_CHAR(tty), ldata->char_map);
1853 		}
1854 		clear_bit(__DISABLED_CHAR, ldata->char_map);
1855 		ldata->raw = 0;
1856 		ldata->real_raw = 0;
1857 	} else {
1858 		ldata->raw = 1;
1859 		if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
1860 		    (I_IGNPAR(tty) || !I_INPCK(tty)) &&
1861 		    (tty->driver->flags & TTY_DRIVER_REAL_RAW))
1862 			ldata->real_raw = 1;
1863 		else
1864 			ldata->real_raw = 0;
1865 	}
1866 	/*
1867 	 * Fix tty hang when I_IXON(tty) is cleared, but the tty
1868 	 * been stopped by STOP_CHAR(tty) before it.
1869 	 */
1870 	if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow_stopped) {
1871 		start_tty(tty);
1872 		process_echoes(tty);
1873 	}
1874 
1875 	/* The termios change make the tty ready for I/O */
1876 	wake_up_interruptible(&tty->write_wait);
1877 	wake_up_interruptible(&tty->read_wait);
1878 }
1879 
1880 /**
1881  *	n_tty_close		-	close the ldisc for this tty
1882  *	@tty: device
1883  *
1884  *	Called from the terminal layer when this line discipline is
1885  *	being shut down, either because of a close or becsuse of a
1886  *	discipline change. The function will not be called while other
1887  *	ldisc methods are in progress.
1888  */
1889 
1890 static void n_tty_close(struct tty_struct *tty)
1891 {
1892 	struct n_tty_data *ldata = tty->disc_data;
1893 
1894 	if (tty->link)
1895 		n_tty_packet_mode_flush(tty);
1896 
1897 	vfree(ldata);
1898 	tty->disc_data = NULL;
1899 }
1900 
1901 /**
1902  *	n_tty_open		-	open an ldisc
1903  *	@tty: terminal to open
1904  *
1905  *	Called when this line discipline is being attached to the
1906  *	terminal device. Can sleep. Called serialized so that no
1907  *	other events will occur in parallel. No further open will occur
1908  *	until a close.
1909  */
1910 
1911 static int n_tty_open(struct tty_struct *tty)
1912 {
1913 	struct n_tty_data *ldata;
1914 
1915 	/* Currently a malloc failure here can panic */
1916 	ldata = vzalloc(sizeof(*ldata));
1917 	if (!ldata)
1918 		return -ENOMEM;
1919 
1920 	ldata->overrun_time = jiffies;
1921 	mutex_init(&ldata->atomic_read_lock);
1922 	mutex_init(&ldata->output_lock);
1923 
1924 	tty->disc_data = ldata;
1925 	tty->closing = 0;
1926 	/* indicate buffer work may resume */
1927 	clear_bit(TTY_LDISC_HALTED, &tty->flags);
1928 	n_tty_set_termios(tty, NULL);
1929 	tty_unthrottle(tty);
1930 	return 0;
1931 }
1932 
1933 static inline int input_available_p(struct tty_struct *tty, int poll)
1934 {
1935 	struct n_tty_data *ldata = tty->disc_data;
1936 	int amt = poll && !TIME_CHAR(tty) && MIN_CHAR(tty) ? MIN_CHAR(tty) : 1;
1937 
1938 	if (ldata->icanon && !L_EXTPROC(tty))
1939 		return ldata->canon_head != ldata->read_tail;
1940 	else
1941 		return ldata->commit_head - ldata->read_tail >= amt;
1942 }
1943 
1944 /**
1945  *	copy_from_read_buf	-	copy read data directly
1946  *	@tty: terminal device
1947  *	@b: user data
1948  *	@nr: size of data
1949  *
1950  *	Helper function to speed up n_tty_read.  It is only called when
1951  *	ICANON is off; it copies characters straight from the tty queue to
1952  *	user space directly.  It can be profitably called twice; once to
1953  *	drain the space from the tail pointer to the (physical) end of the
1954  *	buffer, and once to drain the space from the (physical) beginning of
1955  *	the buffer to head pointer.
1956  *
1957  *	Called under the ldata->atomic_read_lock sem
1958  *
1959  *	n_tty_read()/consumer path:
1960  *		caller holds non-exclusive termios_rwsem
1961  *		read_tail published
1962  */
1963 
1964 static int copy_from_read_buf(struct tty_struct *tty,
1965 				      unsigned char __user **b,
1966 				      size_t *nr)
1967 
1968 {
1969 	struct n_tty_data *ldata = tty->disc_data;
1970 	int retval;
1971 	size_t n;
1972 	bool is_eof;
1973 	size_t head = smp_load_acquire(&ldata->commit_head);
1974 	size_t tail = ldata->read_tail & (N_TTY_BUF_SIZE - 1);
1975 
1976 	retval = 0;
1977 	n = min(head - ldata->read_tail, N_TTY_BUF_SIZE - tail);
1978 	n = min(*nr, n);
1979 	if (n) {
1980 		unsigned char *from = read_buf_addr(ldata, tail);
1981 		retval = copy_to_user(*b, from, n);
1982 		n -= retval;
1983 		is_eof = n == 1 && *from == EOF_CHAR(tty);
1984 		tty_audit_add_data(tty, from, n);
1985 		zero_buffer(tty, from, n);
1986 		smp_store_release(&ldata->read_tail, ldata->read_tail + n);
1987 		/* Turn single EOF into zero-length read */
1988 		if (L_EXTPROC(tty) && ldata->icanon && is_eof &&
1989 		    (head == ldata->read_tail))
1990 			n = 0;
1991 		*b += n;
1992 		*nr -= n;
1993 	}
1994 	return retval;
1995 }
1996 
1997 /**
1998  *	canon_copy_from_read_buf	-	copy read data in canonical mode
1999  *	@tty: terminal device
2000  *	@b: user data
2001  *	@nr: size of data
2002  *
2003  *	Helper function for n_tty_read.  It is only called when ICANON is on;
2004  *	it copies one line of input up to and including the line-delimiting
2005  *	character into the user-space buffer.
2006  *
2007  *	NB: When termios is changed from non-canonical to canonical mode and
2008  *	the read buffer contains data, n_tty_set_termios() simulates an EOF
2009  *	push (as if C-d were input) _without_ the DISABLED_CHAR in the buffer.
2010  *	This causes data already processed as input to be immediately available
2011  *	as input although a newline has not been received.
2012  *
2013  *	Called under the atomic_read_lock mutex
2014  *
2015  *	n_tty_read()/consumer path:
2016  *		caller holds non-exclusive termios_rwsem
2017  *		read_tail published
2018  */
2019 
2020 static int canon_copy_from_read_buf(struct tty_struct *tty,
2021 				    unsigned char __user **b,
2022 				    size_t *nr)
2023 {
2024 	struct n_tty_data *ldata = tty->disc_data;
2025 	size_t n, size, more, c;
2026 	size_t eol;
2027 	size_t tail;
2028 	int ret, found = 0;
2029 
2030 	/* N.B. avoid overrun if nr == 0 */
2031 	if (!*nr)
2032 		return 0;
2033 
2034 	n = min(*nr + 1, smp_load_acquire(&ldata->canon_head) - ldata->read_tail);
2035 
2036 	tail = ldata->read_tail & (N_TTY_BUF_SIZE - 1);
2037 	size = min_t(size_t, tail + n, N_TTY_BUF_SIZE);
2038 
2039 	n_tty_trace("%s: nr:%zu tail:%zu n:%zu size:%zu\n",
2040 		    __func__, *nr, tail, n, size);
2041 
2042 	eol = find_next_bit(ldata->read_flags, size, tail);
2043 	more = n - (size - tail);
2044 	if (eol == N_TTY_BUF_SIZE && more) {
2045 		/* scan wrapped without finding set bit */
2046 		eol = find_next_bit(ldata->read_flags, more, 0);
2047 		found = eol != more;
2048 	} else
2049 		found = eol != size;
2050 
2051 	n = eol - tail;
2052 	if (n > N_TTY_BUF_SIZE)
2053 		n += N_TTY_BUF_SIZE;
2054 	c = n + found;
2055 
2056 	if (!found || read_buf(ldata, eol) != __DISABLED_CHAR) {
2057 		c = min(*nr, c);
2058 		n = c;
2059 	}
2060 
2061 	n_tty_trace("%s: eol:%zu found:%d n:%zu c:%zu tail:%zu more:%zu\n",
2062 		    __func__, eol, found, n, c, tail, more);
2063 
2064 	ret = tty_copy_to_user(tty, *b, tail, n);
2065 	if (ret)
2066 		return -EFAULT;
2067 	*b += n;
2068 	*nr -= n;
2069 
2070 	if (found)
2071 		clear_bit(eol, ldata->read_flags);
2072 	smp_store_release(&ldata->read_tail, ldata->read_tail + c);
2073 
2074 	if (found) {
2075 		if (!ldata->push)
2076 			ldata->line_start = ldata->read_tail;
2077 		else
2078 			ldata->push = 0;
2079 		tty_audit_push();
2080 	}
2081 	return 0;
2082 }
2083 
2084 extern ssize_t redirected_tty_write(struct file *, const char __user *,
2085 							size_t, loff_t *);
2086 
2087 /**
2088  *	job_control		-	check job control
2089  *	@tty: tty
2090  *	@file: file handle
2091  *
2092  *	Perform job control management checks on this file/tty descriptor
2093  *	and if appropriate send any needed signals and return a negative
2094  *	error code if action should be taken.
2095  *
2096  *	Locking: redirected write test is safe
2097  *		 current->signal->tty check is safe
2098  *		 ctrl_lock to safely reference tty->pgrp
2099  */
2100 
2101 static int job_control(struct tty_struct *tty, struct file *file)
2102 {
2103 	/* Job control check -- must be done at start and after
2104 	   every sleep (POSIX.1 7.1.1.4). */
2105 	/* NOTE: not yet done after every sleep pending a thorough
2106 	   check of the logic of this change. -- jlc */
2107 	/* don't stop on /dev/console */
2108 	if (file->f_op->write == redirected_tty_write)
2109 		return 0;
2110 
2111 	return __tty_check_change(tty, SIGTTIN);
2112 }
2113 
2114 
2115 /**
2116  *	n_tty_read		-	read function for tty
2117  *	@tty: tty device
2118  *	@file: file object
2119  *	@buf: userspace buffer pointer
2120  *	@nr: size of I/O
2121  *
2122  *	Perform reads for the line discipline. We are guaranteed that the
2123  *	line discipline will not be closed under us but we may get multiple
2124  *	parallel readers and must handle this ourselves. We may also get
2125  *	a hangup. Always called in user context, may sleep.
2126  *
2127  *	This code must be sure never to sleep through a hangup.
2128  *
2129  *	n_tty_read()/consumer path:
2130  *		claims non-exclusive termios_rwsem
2131  *		publishes read_tail
2132  */
2133 
2134 static ssize_t n_tty_read(struct tty_struct *tty, struct file *file,
2135 			 unsigned char __user *buf, size_t nr)
2136 {
2137 	struct n_tty_data *ldata = tty->disc_data;
2138 	unsigned char __user *b = buf;
2139 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
2140 	int c;
2141 	int minimum, time;
2142 	ssize_t retval = 0;
2143 	long timeout;
2144 	int packet;
2145 	size_t tail;
2146 
2147 	c = job_control(tty, file);
2148 	if (c < 0)
2149 		return c;
2150 
2151 	/*
2152 	 *	Internal serialization of reads.
2153 	 */
2154 	if (file->f_flags & O_NONBLOCK) {
2155 		if (!mutex_trylock(&ldata->atomic_read_lock))
2156 			return -EAGAIN;
2157 	} else {
2158 		if (mutex_lock_interruptible(&ldata->atomic_read_lock))
2159 			return -ERESTARTSYS;
2160 	}
2161 
2162 	down_read(&tty->termios_rwsem);
2163 
2164 	minimum = time = 0;
2165 	timeout = MAX_SCHEDULE_TIMEOUT;
2166 	if (!ldata->icanon) {
2167 		minimum = MIN_CHAR(tty);
2168 		if (minimum) {
2169 			time = (HZ / 10) * TIME_CHAR(tty);
2170 		} else {
2171 			timeout = (HZ / 10) * TIME_CHAR(tty);
2172 			minimum = 1;
2173 		}
2174 	}
2175 
2176 	packet = tty->packet;
2177 	tail = ldata->read_tail;
2178 
2179 	add_wait_queue(&tty->read_wait, &wait);
2180 	while (nr) {
2181 		/* First test for status change. */
2182 		if (packet && tty->link->ctrl_status) {
2183 			unsigned char cs;
2184 			if (b != buf)
2185 				break;
2186 			spin_lock_irq(&tty->link->ctrl_lock);
2187 			cs = tty->link->ctrl_status;
2188 			tty->link->ctrl_status = 0;
2189 			spin_unlock_irq(&tty->link->ctrl_lock);
2190 			if (put_user(cs, b)) {
2191 				retval = -EFAULT;
2192 				break;
2193 			}
2194 			b++;
2195 			nr--;
2196 			break;
2197 		}
2198 
2199 		if (!input_available_p(tty, 0)) {
2200 			up_read(&tty->termios_rwsem);
2201 			tty_buffer_flush_work(tty->port);
2202 			down_read(&tty->termios_rwsem);
2203 			if (!input_available_p(tty, 0)) {
2204 				if (test_bit(TTY_OTHER_CLOSED, &tty->flags)) {
2205 					retval = -EIO;
2206 					break;
2207 				}
2208 				if (tty_hung_up_p(file))
2209 					break;
2210 				/*
2211 				 * Abort readers for ttys which never actually
2212 				 * get hung up.  See __tty_hangup().
2213 				 */
2214 				if (test_bit(TTY_HUPPING, &tty->flags))
2215 					break;
2216 				if (!timeout)
2217 					break;
2218 				if (tty_io_nonblock(tty, file)) {
2219 					retval = -EAGAIN;
2220 					break;
2221 				}
2222 				if (signal_pending(current)) {
2223 					retval = -ERESTARTSYS;
2224 					break;
2225 				}
2226 				up_read(&tty->termios_rwsem);
2227 
2228 				timeout = wait_woken(&wait, TASK_INTERRUPTIBLE,
2229 						timeout);
2230 
2231 				down_read(&tty->termios_rwsem);
2232 				continue;
2233 			}
2234 		}
2235 
2236 		if (ldata->icanon && !L_EXTPROC(tty)) {
2237 			retval = canon_copy_from_read_buf(tty, &b, &nr);
2238 			if (retval)
2239 				break;
2240 		} else {
2241 			int uncopied;
2242 
2243 			/* Deal with packet mode. */
2244 			if (packet && b == buf) {
2245 				if (put_user(TIOCPKT_DATA, b)) {
2246 					retval = -EFAULT;
2247 					break;
2248 				}
2249 				b++;
2250 				nr--;
2251 			}
2252 
2253 			uncopied = copy_from_read_buf(tty, &b, &nr);
2254 			uncopied += copy_from_read_buf(tty, &b, &nr);
2255 			if (uncopied) {
2256 				retval = -EFAULT;
2257 				break;
2258 			}
2259 		}
2260 
2261 		n_tty_check_unthrottle(tty);
2262 
2263 		if (b - buf >= minimum)
2264 			break;
2265 		if (time)
2266 			timeout = time;
2267 	}
2268 	if (tail != ldata->read_tail)
2269 		n_tty_kick_worker(tty);
2270 	up_read(&tty->termios_rwsem);
2271 
2272 	remove_wait_queue(&tty->read_wait, &wait);
2273 	mutex_unlock(&ldata->atomic_read_lock);
2274 
2275 	if (b - buf)
2276 		retval = b - buf;
2277 
2278 	return retval;
2279 }
2280 
2281 /**
2282  *	n_tty_write		-	write function for tty
2283  *	@tty: tty device
2284  *	@file: file object
2285  *	@buf: userspace buffer pointer
2286  *	@nr: size of I/O
2287  *
2288  *	Write function of the terminal device.  This is serialized with
2289  *	respect to other write callers but not to termios changes, reads
2290  *	and other such events.  Since the receive code will echo characters,
2291  *	thus calling driver write methods, the output_lock is used in
2292  *	the output processing functions called here as well as in the
2293  *	echo processing function to protect the column state and space
2294  *	left in the buffer.
2295  *
2296  *	This code must be sure never to sleep through a hangup.
2297  *
2298  *	Locking: output_lock to protect column state and space left
2299  *		 (note that the process_output*() functions take this
2300  *		  lock themselves)
2301  */
2302 
2303 static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
2304 			   const unsigned char *buf, size_t nr)
2305 {
2306 	const unsigned char *b = buf;
2307 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
2308 	int c;
2309 	ssize_t retval = 0;
2310 
2311 	/* Job control check -- must be done at start (POSIX.1 7.1.1.4). */
2312 	if (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) {
2313 		retval = tty_check_change(tty);
2314 		if (retval)
2315 			return retval;
2316 	}
2317 
2318 	down_read(&tty->termios_rwsem);
2319 
2320 	/* Write out any echoed characters that are still pending */
2321 	process_echoes(tty);
2322 
2323 	add_wait_queue(&tty->write_wait, &wait);
2324 	while (1) {
2325 		if (signal_pending(current)) {
2326 			retval = -ERESTARTSYS;
2327 			break;
2328 		}
2329 		if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
2330 			retval = -EIO;
2331 			break;
2332 		}
2333 		if (O_OPOST(tty)) {
2334 			while (nr > 0) {
2335 				ssize_t num = process_output_block(tty, b, nr);
2336 				if (num < 0) {
2337 					if (num == -EAGAIN)
2338 						break;
2339 					retval = num;
2340 					goto break_out;
2341 				}
2342 				b += num;
2343 				nr -= num;
2344 				if (nr == 0)
2345 					break;
2346 				c = *b;
2347 				if (process_output(c, tty) < 0)
2348 					break;
2349 				b++; nr--;
2350 			}
2351 			if (tty->ops->flush_chars)
2352 				tty->ops->flush_chars(tty);
2353 		} else {
2354 			struct n_tty_data *ldata = tty->disc_data;
2355 
2356 			while (nr > 0) {
2357 				mutex_lock(&ldata->output_lock);
2358 				c = tty->ops->write(tty, b, nr);
2359 				mutex_unlock(&ldata->output_lock);
2360 				if (c < 0) {
2361 					retval = c;
2362 					goto break_out;
2363 				}
2364 				if (!c)
2365 					break;
2366 				b += c;
2367 				nr -= c;
2368 			}
2369 		}
2370 		if (!nr)
2371 			break;
2372 		if (tty_io_nonblock(tty, file)) {
2373 			retval = -EAGAIN;
2374 			break;
2375 		}
2376 		up_read(&tty->termios_rwsem);
2377 
2378 		wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
2379 
2380 		down_read(&tty->termios_rwsem);
2381 	}
2382 break_out:
2383 	remove_wait_queue(&tty->write_wait, &wait);
2384 	if (nr && tty->fasync)
2385 		set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
2386 	up_read(&tty->termios_rwsem);
2387 	return (b - buf) ? b - buf : retval;
2388 }
2389 
2390 /**
2391  *	n_tty_poll		-	poll method for N_TTY
2392  *	@tty: terminal device
2393  *	@file: file accessing it
2394  *	@wait: poll table
2395  *
2396  *	Called when the line discipline is asked to poll() for data or
2397  *	for special events. This code is not serialized with respect to
2398  *	other events save open/close.
2399  *
2400  *	This code must be sure never to sleep through a hangup.
2401  *	Called without the kernel lock held - fine
2402  */
2403 
2404 static __poll_t n_tty_poll(struct tty_struct *tty, struct file *file,
2405 							poll_table *wait)
2406 {
2407 	__poll_t mask = 0;
2408 
2409 	poll_wait(file, &tty->read_wait, wait);
2410 	poll_wait(file, &tty->write_wait, wait);
2411 	if (input_available_p(tty, 1))
2412 		mask |= EPOLLIN | EPOLLRDNORM;
2413 	else {
2414 		tty_buffer_flush_work(tty->port);
2415 		if (input_available_p(tty, 1))
2416 			mask |= EPOLLIN | EPOLLRDNORM;
2417 	}
2418 	if (tty->packet && tty->link->ctrl_status)
2419 		mask |= EPOLLPRI | EPOLLIN | EPOLLRDNORM;
2420 	if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
2421 		mask |= EPOLLHUP;
2422 	if (tty_hung_up_p(file))
2423 		mask |= EPOLLHUP;
2424 	if (tty->ops->write && !tty_is_writelocked(tty) &&
2425 			tty_chars_in_buffer(tty) < WAKEUP_CHARS &&
2426 			tty_write_room(tty) > 0)
2427 		mask |= EPOLLOUT | EPOLLWRNORM;
2428 	return mask;
2429 }
2430 
2431 static unsigned long inq_canon(struct n_tty_data *ldata)
2432 {
2433 	size_t nr, head, tail;
2434 
2435 	if (ldata->canon_head == ldata->read_tail)
2436 		return 0;
2437 	head = ldata->canon_head;
2438 	tail = ldata->read_tail;
2439 	nr = head - tail;
2440 	/* Skip EOF-chars.. */
2441 	while (MASK(head) != MASK(tail)) {
2442 		if (test_bit(tail & (N_TTY_BUF_SIZE - 1), ldata->read_flags) &&
2443 		    read_buf(ldata, tail) == __DISABLED_CHAR)
2444 			nr--;
2445 		tail++;
2446 	}
2447 	return nr;
2448 }
2449 
2450 static int n_tty_ioctl(struct tty_struct *tty, struct file *file,
2451 		       unsigned int cmd, unsigned long arg)
2452 {
2453 	struct n_tty_data *ldata = tty->disc_data;
2454 	int retval;
2455 
2456 	switch (cmd) {
2457 	case TIOCOUTQ:
2458 		return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
2459 	case TIOCINQ:
2460 		down_write(&tty->termios_rwsem);
2461 		if (L_ICANON(tty) && !L_EXTPROC(tty))
2462 			retval = inq_canon(ldata);
2463 		else
2464 			retval = read_cnt(ldata);
2465 		up_write(&tty->termios_rwsem);
2466 		return put_user(retval, (unsigned int __user *) arg);
2467 	default:
2468 		return n_tty_ioctl_helper(tty, file, cmd, arg);
2469 	}
2470 }
2471 
2472 static struct tty_ldisc_ops n_tty_ops = {
2473 	.magic           = TTY_LDISC_MAGIC,
2474 	.name            = "n_tty",
2475 	.open            = n_tty_open,
2476 	.close           = n_tty_close,
2477 	.flush_buffer    = n_tty_flush_buffer,
2478 	.read            = n_tty_read,
2479 	.write           = n_tty_write,
2480 	.ioctl           = n_tty_ioctl,
2481 	.set_termios     = n_tty_set_termios,
2482 	.poll            = n_tty_poll,
2483 	.receive_buf     = n_tty_receive_buf,
2484 	.write_wakeup    = n_tty_write_wakeup,
2485 	.receive_buf2	 = n_tty_receive_buf2,
2486 };
2487 
2488 /**
2489  *	n_tty_inherit_ops	-	inherit N_TTY methods
2490  *	@ops: struct tty_ldisc_ops where to save N_TTY methods
2491  *
2492  *	Enables a 'subclass' line discipline to 'inherit' N_TTY methods.
2493  */
2494 
2495 void n_tty_inherit_ops(struct tty_ldisc_ops *ops)
2496 {
2497 	*ops = n_tty_ops;
2498 	ops->owner = NULL;
2499 	ops->refcount = ops->flags = 0;
2500 }
2501 EXPORT_SYMBOL_GPL(n_tty_inherit_ops);
2502 
2503 void __init n_tty_init(void)
2504 {
2505 	tty_register_ldisc(N_TTY, &n_tty_ops);
2506 }
2507