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