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