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