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