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