ath9k: Use GFP_ATOMIC when allocating TX private area
[linux-2.6] / drivers / char / 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
51 #include <asm/uaccess.h>
52 #include <asm/system.h>
53
54 /* number of characters left in xmit buffer before select has we have room */
55 #define WAKEUP_CHARS 256
56
57 /*
58  * This defines the low- and high-watermarks for throttling and
59  * unthrottling the TTY driver.  These watermarks are used for
60  * controlling the space in the read buffer.
61  */
62 #define TTY_THRESHOLD_THROTTLE          128 /* now based on remaining room */
63 #define TTY_THRESHOLD_UNTHROTTLE        128
64
65 static inline unsigned char *alloc_buf(void)
66 {
67         gfp_t prio = in_interrupt() ? GFP_ATOMIC : GFP_KERNEL;
68
69         if (PAGE_SIZE != N_TTY_BUF_SIZE)
70                 return kmalloc(N_TTY_BUF_SIZE, prio);
71         else
72                 return (unsigned char *)__get_free_page(prio);
73 }
74
75 static inline void free_buf(unsigned char *buf)
76 {
77         if (PAGE_SIZE != N_TTY_BUF_SIZE)
78                 kfree(buf);
79         else
80                 free_page((unsigned long) buf);
81 }
82
83 static inline int tty_put_user(struct tty_struct *tty, unsigned char x,
84                                unsigned char __user *ptr)
85 {
86         tty_audit_add_data(tty, &x, 1);
87         return put_user(x, ptr);
88 }
89
90 /**
91  *      n_tty_set__room -       receive space
92  *      @tty: terminal
93  *
94  *      Called by the driver to find out how much data it is
95  *      permitted to feed to the line discipline without any being lost
96  *      and thus to manage flow control. Not serialized. Answers for the
97  *      "instant".
98  */
99
100 static void n_tty_set_room(struct tty_struct *tty)
101 {
102         /* tty->read_cnt is not read locked ? */
103         int     left = N_TTY_BUF_SIZE - tty->read_cnt - 1;
104
105         /*
106          * If we are doing input canonicalization, and there are no
107          * pending newlines, let characters through without limit, so
108          * that erase characters will be handled.  Other excess
109          * characters will be beeped.
110          */
111         if (left <= 0)
112                 left = tty->icanon && !tty->canon_data;
113         tty->receive_room = left;
114 }
115
116 static void put_tty_queue_nolock(unsigned char c, struct tty_struct *tty)
117 {
118         if (tty->read_cnt < N_TTY_BUF_SIZE) {
119                 tty->read_buf[tty->read_head] = c;
120                 tty->read_head = (tty->read_head + 1) & (N_TTY_BUF_SIZE-1);
121                 tty->read_cnt++;
122         }
123 }
124
125 /**
126  *      put_tty_queue           -       add character to tty
127  *      @c: character
128  *      @tty: tty device
129  *
130  *      Add a character to the tty read_buf queue. This is done under the
131  *      read_lock to serialize character addition and also to protect us
132  *      against parallel reads or flushes
133  */
134
135 static void put_tty_queue(unsigned char c, struct tty_struct *tty)
136 {
137         unsigned long flags;
138         /*
139          *      The problem of stomping on the buffers ends here.
140          *      Why didn't anyone see this one coming? --AJK
141         */
142         spin_lock_irqsave(&tty->read_lock, flags);
143         put_tty_queue_nolock(c, tty);
144         spin_unlock_irqrestore(&tty->read_lock, flags);
145 }
146
147 /**
148  *      check_unthrottle        -       allow new receive data
149  *      @tty; tty device
150  *
151  *      Check whether to call the driver unthrottle functions
152  *
153  *      Can sleep, may be called under the atomic_read_lock mutex but
154  *      this is not guaranteed.
155  */
156 static void check_unthrottle(struct tty_struct *tty)
157 {
158         if (tty->count)
159                 tty_unthrottle(tty);
160 }
161
162 /**
163  *      reset_buffer_flags      -       reset buffer state
164  *      @tty: terminal to reset
165  *
166  *      Reset the read buffer counters, clear the flags,
167  *      and make sure the driver is unthrottled. Called
168  *      from n_tty_open() and n_tty_flush_buffer().
169  *
170  *      Locking: tty_read_lock for read fields.
171  */
172 static void reset_buffer_flags(struct tty_struct *tty)
173 {
174         unsigned long flags;
175
176         spin_lock_irqsave(&tty->read_lock, flags);
177         tty->read_head = tty->read_tail = tty->read_cnt = 0;
178         spin_unlock_irqrestore(&tty->read_lock, flags);
179         tty->canon_head = tty->canon_data = tty->erasing = 0;
180         memset(&tty->read_flags, 0, sizeof tty->read_flags);
181         n_tty_set_room(tty);
182         check_unthrottle(tty);
183 }
184
185 /**
186  *      n_tty_flush_buffer      -       clean input queue
187  *      @tty:   terminal device
188  *
189  *      Flush the input buffer. Called when the line discipline is
190  *      being closed, when the tty layer wants the buffer flushed (eg
191  *      at hangup) or when the N_TTY line discipline internally has to
192  *      clean the pending queue (for example some signals).
193  *
194  *      Locking: ctrl_lock, read_lock.
195  */
196
197 static void n_tty_flush_buffer(struct tty_struct *tty)
198 {
199         unsigned long flags;
200         /* clear everything and unthrottle the driver */
201         reset_buffer_flags(tty);
202
203         if (!tty->link)
204                 return;
205
206         spin_lock_irqsave(&tty->ctrl_lock, flags);
207         if (tty->link->packet) {
208                 tty->ctrl_status |= TIOCPKT_FLUSHREAD;
209                 wake_up_interruptible(&tty->link->read_wait);
210         }
211         spin_unlock_irqrestore(&tty->ctrl_lock, flags);
212 }
213
214 /**
215  *      n_tty_chars_in_buffer   -       report available bytes
216  *      @tty: tty device
217  *
218  *      Report the number of characters buffered to be delivered to user
219  *      at this instant in time.
220  *
221  *      Locking: read_lock
222  */
223
224 static ssize_t n_tty_chars_in_buffer(struct tty_struct *tty)
225 {
226         unsigned long flags;
227         ssize_t n = 0;
228
229         spin_lock_irqsave(&tty->read_lock, flags);
230         if (!tty->icanon) {
231                 n = tty->read_cnt;
232         } else if (tty->canon_data) {
233                 n = (tty->canon_head > tty->read_tail) ?
234                         tty->canon_head - tty->read_tail :
235                         tty->canon_head + (N_TTY_BUF_SIZE - tty->read_tail);
236         }
237         spin_unlock_irqrestore(&tty->read_lock, flags);
238         return n;
239 }
240
241 /**
242  *      is_utf8_continuation    -       utf8 multibyte check
243  *      @c: byte to check
244  *
245  *      Returns true if the utf8 character 'c' is a multibyte continuation
246  *      character. We use this to correctly compute the on screen size
247  *      of the character when printing
248  */
249
250 static inline int is_utf8_continuation(unsigned char c)
251 {
252         return (c & 0xc0) == 0x80;
253 }
254
255 /**
256  *      is_continuation         -       multibyte check
257  *      @c: byte to check
258  *
259  *      Returns true if the utf8 character 'c' is a multibyte continuation
260  *      character and the terminal is in unicode mode.
261  */
262
263 static inline int is_continuation(unsigned char c, struct tty_struct *tty)
264 {
265         return I_IUTF8(tty) && is_utf8_continuation(c);
266 }
267
268 /**
269  *      opost                   -       output post processor
270  *      @c: character (or partial unicode symbol)
271  *      @tty: terminal device
272  *
273  *      Perform OPOST processing.  Returns -1 when the output device is
274  *      full and the character must be retried. Note that Linux currently
275  *      ignores TABDLY, CRDLY, VTDLY, FFDLY and NLDLY. They simply aren't
276  *      relevant in the world today. If you ever need them, add them here.
277  *
278  *      Called from both the receive and transmit sides and can be called
279  *      re-entrantly. Relies on lock_kernel() for tty->column state.
280  */
281
282 static int opost(unsigned char c, struct tty_struct *tty)
283 {
284         int     space, spaces;
285
286         space = tty_write_room(tty);
287         if (!space)
288                 return -1;
289
290         lock_kernel();
291         if (O_OPOST(tty)) {
292                 switch (c) {
293                 case '\n':
294                         if (O_ONLRET(tty))
295                                 tty->column = 0;
296                         if (O_ONLCR(tty)) {
297                                 if (space < 2) {
298                                         unlock_kernel();
299                                         return -1;
300                                 }
301                                 tty_put_char(tty, '\r');
302                                 tty->column = 0;
303                         }
304                         tty->canon_column = tty->column;
305                         break;
306                 case '\r':
307                         if (O_ONOCR(tty) && tty->column == 0) {
308                                 unlock_kernel();
309                                 return 0;
310                         }
311                         if (O_OCRNL(tty)) {
312                                 c = '\n';
313                                 if (O_ONLRET(tty))
314                                         tty->canon_column = tty->column = 0;
315                                 break;
316                         }
317                         tty->canon_column = tty->column = 0;
318                         break;
319                 case '\t':
320                         spaces = 8 - (tty->column & 7);
321                         if (O_TABDLY(tty) == XTABS) {
322                                 if (space < spaces) {
323                                         unlock_kernel();
324                                         return -1;
325                                 }
326                                 tty->column += spaces;
327                                 tty->ops->write(tty, "        ", spaces);
328                                 unlock_kernel();
329                                 return 0;
330                         }
331                         tty->column += spaces;
332                         break;
333                 case '\b':
334                         if (tty->column > 0)
335                                 tty->column--;
336                         break;
337                 default:
338                         if (O_OLCUC(tty))
339                                 c = toupper(c);
340                         if (!iscntrl(c) && !is_continuation(c, tty))
341                                 tty->column++;
342                         break;
343                 }
344         }
345         tty_put_char(tty, c);
346         unlock_kernel();
347         return 0;
348 }
349
350 /**
351  *      opost_block             -       block postprocess
352  *      @tty: terminal device
353  *      @inbuf: user buffer
354  *      @nr: number of bytes
355  *
356  *      This path is used to speed up block console writes, among other
357  *      things when processing blocks of output data. It handles only
358  *      the simple cases normally found and helps to generate blocks of
359  *      symbols for the console driver and thus improve performance.
360  *
361  *      Called from n_tty_write under the tty layer write lock. Relies
362  *      on lock_kernel for the tty->column state.
363  */
364
365 static ssize_t opost_block(struct tty_struct *tty,
366                        const unsigned char *buf, unsigned int nr)
367 {
368         int     space;
369         int     i;
370         const unsigned char *cp;
371
372         space = tty_write_room(tty);
373         if (!space)
374                 return 0;
375         if (nr > space)
376                 nr = space;
377
378         lock_kernel();
379         for (i = 0, cp = buf; i < nr; i++, cp++) {
380                 switch (*cp) {
381                 case '\n':
382                         if (O_ONLRET(tty))
383                                 tty->column = 0;
384                         if (O_ONLCR(tty))
385                                 goto break_out;
386                         tty->canon_column = tty->column;
387                         break;
388                 case '\r':
389                         if (O_ONOCR(tty) && tty->column == 0)
390                                 goto break_out;
391                         if (O_OCRNL(tty))
392                                 goto break_out;
393                         tty->canon_column = tty->column = 0;
394                         break;
395                 case '\t':
396                         goto break_out;
397                 case '\b':
398                         if (tty->column > 0)
399                                 tty->column--;
400                         break;
401                 default:
402                         if (O_OLCUC(tty))
403                                 goto break_out;
404                         if (!iscntrl(*cp))
405                                 tty->column++;
406                         break;
407                 }
408         }
409 break_out:
410         if (tty->ops->flush_chars)
411                 tty->ops->flush_chars(tty);
412         i = tty->ops->write(tty, buf, i);
413         unlock_kernel();
414         return i;
415 }
416
417
418 /**
419  *      echo_char       -       echo characters
420  *      @c: unicode byte to echo
421  *      @tty: terminal device
422  *
423  *      Echo user input back onto the screen. This must be called only when
424  *      L_ECHO(tty) is true. Called from the driver receive_buf path.
425  *
426  *      Relies on BKL for tty column locking
427  */
428
429 static void echo_char(unsigned char c, struct tty_struct *tty)
430 {
431         if (L_ECHOCTL(tty) && iscntrl(c) && c != '\t') {
432                 tty_put_char(tty, '^');
433                 tty_put_char(tty, c ^ 0100);
434                 tty->column += 2;
435         } else
436                 opost(c, tty);
437 }
438
439 /**
440  *      finsh_erasing           -       complete erase
441  *      @tty: tty doing the erase
442  *
443  *      Relies on BKL for tty column locking
444  */
445 static inline void finish_erasing(struct tty_struct *tty)
446 {
447         if (tty->erasing) {
448                 tty_put_char(tty, '/');
449                 tty->column++;
450                 tty->erasing = 0;
451         }
452 }
453
454 /**
455  *      eraser          -       handle erase function
456  *      @c: character input
457  *      @tty: terminal device
458  *
459  *      Perform erase and necessary output when an erase character is
460  *      present in the stream from the driver layer. Handles the complexities
461  *      of UTF-8 multibyte symbols.
462  *
463  *      Locking: read_lock for tty buffers, BKL for column/erasing state
464  */
465
466 static void eraser(unsigned char c, struct tty_struct *tty)
467 {
468         enum { ERASE, WERASE, KILL } kill_type;
469         int head, seen_alnums, cnt;
470         unsigned long flags;
471
472         /* FIXME: locking needed ? */
473         if (tty->read_head == tty->canon_head) {
474                 /* opost('\a', tty); */         /* what do you think? */
475                 return;
476         }
477         if (c == ERASE_CHAR(tty))
478                 kill_type = ERASE;
479         else if (c == WERASE_CHAR(tty))
480                 kill_type = WERASE;
481         else {
482                 if (!L_ECHO(tty)) {
483                         spin_lock_irqsave(&tty->read_lock, flags);
484                         tty->read_cnt -= ((tty->read_head - tty->canon_head) &
485                                           (N_TTY_BUF_SIZE - 1));
486                         tty->read_head = tty->canon_head;
487                         spin_unlock_irqrestore(&tty->read_lock, flags);
488                         return;
489                 }
490                 if (!L_ECHOK(tty) || !L_ECHOKE(tty) || !L_ECHOE(tty)) {
491                         spin_lock_irqsave(&tty->read_lock, flags);
492                         tty->read_cnt -= ((tty->read_head - tty->canon_head) &
493                                           (N_TTY_BUF_SIZE - 1));
494                         tty->read_head = tty->canon_head;
495                         spin_unlock_irqrestore(&tty->read_lock, flags);
496                         finish_erasing(tty);
497                         echo_char(KILL_CHAR(tty), tty);
498                         /* Add a newline if ECHOK is on and ECHOKE is off. */
499                         if (L_ECHOK(tty))
500                                 opost('\n', tty);
501                         return;
502                 }
503                 kill_type = KILL;
504         }
505
506         seen_alnums = 0;
507         /* FIXME: Locking ?? */
508         while (tty->read_head != tty->canon_head) {
509                 head = tty->read_head;
510
511                 /* erase a single possibly multibyte character */
512                 do {
513                         head = (head - 1) & (N_TTY_BUF_SIZE-1);
514                         c = tty->read_buf[head];
515                 } while (is_continuation(c, tty) && head != tty->canon_head);
516
517                 /* do not partially erase */
518                 if (is_continuation(c, tty))
519                         break;
520
521                 if (kill_type == WERASE) {
522                         /* Equivalent to BSD's ALTWERASE. */
523                         if (isalnum(c) || c == '_')
524                                 seen_alnums++;
525                         else if (seen_alnums)
526                                 break;
527                 }
528                 cnt = (tty->read_head - head) & (N_TTY_BUF_SIZE-1);
529                 spin_lock_irqsave(&tty->read_lock, flags);
530                 tty->read_head = head;
531                 tty->read_cnt -= cnt;
532                 spin_unlock_irqrestore(&tty->read_lock, flags);
533                 if (L_ECHO(tty)) {
534                         if (L_ECHOPRT(tty)) {
535                                 if (!tty->erasing) {
536                                         tty_put_char(tty, '\\');
537                                         tty->column++;
538                                         tty->erasing = 1;
539                                 }
540                                 /* if cnt > 1, output a multi-byte character */
541                                 echo_char(c, tty);
542                                 while (--cnt > 0) {
543                                         head = (head+1) & (N_TTY_BUF_SIZE-1);
544                                         tty_put_char(tty, tty->read_buf[head]);
545                                 }
546                         } else if (kill_type == ERASE && !L_ECHOE(tty)) {
547                                 echo_char(ERASE_CHAR(tty), tty);
548                         } else if (c == '\t') {
549                                 unsigned int col = tty->canon_column;
550                                 unsigned long tail = tty->canon_head;
551
552                                 /* Find the column of the last char. */
553                                 while (tail != tty->read_head) {
554                                         c = tty->read_buf[tail];
555                                         if (c == '\t')
556                                                 col = (col | 7) + 1;
557                                         else if (iscntrl(c)) {
558                                                 if (L_ECHOCTL(tty))
559                                                         col += 2;
560                                         } else if (!is_continuation(c, tty))
561                                                 col++;
562                                         tail = (tail+1) & (N_TTY_BUF_SIZE-1);
563                                 }
564
565                                 /* should never happen */
566                                 if (tty->column > 0x80000000)
567                                         tty->column = 0;
568
569                                 /* Now backup to that column. */
570                                 while (tty->column > col) {
571                                         /* Can't use opost here. */
572                                         tty_put_char(tty, '\b');
573                                         if (tty->column > 0)
574                                                 tty->column--;
575                                 }
576                         } else {
577                                 if (iscntrl(c) && L_ECHOCTL(tty)) {
578                                         tty_put_char(tty, '\b');
579                                         tty_put_char(tty, ' ');
580                                         tty_put_char(tty, '\b');
581                                         if (tty->column > 0)
582                                                 tty->column--;
583                                 }
584                                 if (!iscntrl(c) || L_ECHOCTL(tty)) {
585                                         tty_put_char(tty, '\b');
586                                         tty_put_char(tty, ' ');
587                                         tty_put_char(tty, '\b');
588                                         if (tty->column > 0)
589                                                 tty->column--;
590                                 }
591                         }
592                 }
593                 if (kill_type == ERASE)
594                         break;
595         }
596         if (tty->read_head == tty->canon_head)
597                 finish_erasing(tty);
598 }
599
600 /**
601  *      isig            -       handle the ISIG optio
602  *      @sig: signal
603  *      @tty: terminal
604  *      @flush: force flush
605  *
606  *      Called when a signal is being sent due to terminal input. This
607  *      may caus terminal flushing to take place according to the termios
608  *      settings and character used. Called from the driver receive_buf
609  *      path so serialized.
610  *
611  *      Locking: ctrl_lock, read_lock (both via flush buffer)
612  */
613
614 static inline void isig(int sig, struct tty_struct *tty, int flush)
615 {
616         if (tty->pgrp)
617                 kill_pgrp(tty->pgrp, sig, 1);
618         if (flush || !L_NOFLSH(tty)) {
619                 n_tty_flush_buffer(tty);
620                 tty_driver_flush_buffer(tty);
621         }
622 }
623
624 /**
625  *      n_tty_receive_break     -       handle break
626  *      @tty: terminal
627  *
628  *      An RS232 break event has been hit in the incoming bitstream. This
629  *      can cause a variety of events depending upon the termios settings.
630  *
631  *      Called from the receive_buf path so single threaded.
632  */
633
634 static inline void n_tty_receive_break(struct tty_struct *tty)
635 {
636         if (I_IGNBRK(tty))
637                 return;
638         if (I_BRKINT(tty)) {
639                 isig(SIGINT, tty, 1);
640                 return;
641         }
642         if (I_PARMRK(tty)) {
643                 put_tty_queue('\377', tty);
644                 put_tty_queue('\0', tty);
645         }
646         put_tty_queue('\0', tty);
647         wake_up_interruptible(&tty->read_wait);
648 }
649
650 /**
651  *      n_tty_receive_overrun   -       handle overrun reporting
652  *      @tty: terminal
653  *
654  *      Data arrived faster than we could process it. While the tty
655  *      driver has flagged this the bits that were missed are gone
656  *      forever.
657  *
658  *      Called from the receive_buf path so single threaded. Does not
659  *      need locking as num_overrun and overrun_time are function
660  *      private.
661  */
662
663 static inline void n_tty_receive_overrun(struct tty_struct *tty)
664 {
665         char buf[64];
666
667         tty->num_overrun++;
668         if (time_before(tty->overrun_time, jiffies - HZ) ||
669                         time_after(tty->overrun_time, jiffies)) {
670                 printk(KERN_WARNING "%s: %d input overrun(s)\n",
671                         tty_name(tty, buf),
672                         tty->num_overrun);
673                 tty->overrun_time = jiffies;
674                 tty->num_overrun = 0;
675         }
676 }
677
678 /**
679  *      n_tty_receive_parity_error      -       error notifier
680  *      @tty: terminal device
681  *      @c: character
682  *
683  *      Process a parity error and queue the right data to indicate
684  *      the error case if necessary. Locking as per n_tty_receive_buf.
685  */
686 static inline void n_tty_receive_parity_error(struct tty_struct *tty,
687                                               unsigned char c)
688 {
689         if (I_IGNPAR(tty))
690                 return;
691         if (I_PARMRK(tty)) {
692                 put_tty_queue('\377', tty);
693                 put_tty_queue('\0', tty);
694                 put_tty_queue(c, tty);
695         } else  if (I_INPCK(tty))
696                 put_tty_queue('\0', tty);
697         else
698                 put_tty_queue(c, tty);
699         wake_up_interruptible(&tty->read_wait);
700 }
701
702 /**
703  *      n_tty_receive_char      -       perform processing
704  *      @tty: terminal device
705  *      @c: character
706  *
707  *      Process an individual character of input received from the driver.
708  *      This is serialized with respect to itself by the rules for the
709  *      driver above.
710  */
711
712 static inline void n_tty_receive_char(struct tty_struct *tty, unsigned char c)
713 {
714         unsigned long flags;
715
716         if (tty->raw) {
717                 put_tty_queue(c, tty);
718                 return;
719         }
720
721         if (I_ISTRIP(tty))
722                 c &= 0x7f;
723         if (I_IUCLC(tty) && L_IEXTEN(tty))
724                 c=tolower(c);
725
726         if (tty->stopped && !tty->flow_stopped && I_IXON(tty) &&
727             ((I_IXANY(tty) && c != START_CHAR(tty) && c != STOP_CHAR(tty)) ||
728              c == INTR_CHAR(tty) || c == QUIT_CHAR(tty) || c == SUSP_CHAR(tty)))
729                 start_tty(tty);
730
731         if (tty->closing) {
732                 if (I_IXON(tty)) {
733                         if (c == START_CHAR(tty))
734                                 start_tty(tty);
735                         else if (c == STOP_CHAR(tty))
736                                 stop_tty(tty);
737                 }
738                 return;
739         }
740
741         /*
742          * If the previous character was LNEXT, or we know that this
743          * character is not one of the characters that we'll have to
744          * handle specially, do shortcut processing to speed things
745          * up.
746          */
747         if (!test_bit(c, tty->process_char_map) || tty->lnext) {
748                 finish_erasing(tty);
749                 tty->lnext = 0;
750                 if (L_ECHO(tty)) {
751                         if (tty->read_cnt >= N_TTY_BUF_SIZE-1) {
752                                 tty_put_char(tty, '\a'); /* beep if no space */
753                                 return;
754                         }
755                         /* Record the column of first canon char. */
756                         if (tty->canon_head == tty->read_head)
757                                 tty->canon_column = tty->column;
758                         echo_char(c, tty);
759                 }
760                 if (I_PARMRK(tty) && c == (unsigned char) '\377')
761                         put_tty_queue(c, tty);
762                 put_tty_queue(c, tty);
763                 return;
764         }
765
766         if (I_IXON(tty)) {
767                 if (c == START_CHAR(tty)) {
768                         start_tty(tty);
769                         return;
770                 }
771                 if (c == STOP_CHAR(tty)) {
772                         stop_tty(tty);
773                         return;
774                 }
775         }
776
777         if (L_ISIG(tty)) {
778                 int signal;
779                 signal = SIGINT;
780                 if (c == INTR_CHAR(tty))
781                         goto send_signal;
782                 signal = SIGQUIT;
783                 if (c == QUIT_CHAR(tty))
784                         goto send_signal;
785                 signal = SIGTSTP;
786                 if (c == SUSP_CHAR(tty)) {
787 send_signal:
788                         /*
789                          * Echo character, and then send the signal.
790                          * Note that we do not use isig() here because we want
791                          * the order to be:
792                          * 1) flush, 2) echo, 3) signal
793                          */
794                         if (!L_NOFLSH(tty)) {
795                                 n_tty_flush_buffer(tty);
796                                 tty_driver_flush_buffer(tty);
797                         }
798                         if (L_ECHO(tty))
799                                 echo_char(c, tty);
800                         if (tty->pgrp)
801                                 kill_pgrp(tty->pgrp, signal, 1);
802                         return;
803                 }
804         }
805
806         if (c == '\r') {
807                 if (I_IGNCR(tty))
808                         return;
809                 if (I_ICRNL(tty))
810                         c = '\n';
811         } else if (c == '\n' && I_INLCR(tty))
812                 c = '\r';
813
814         if (tty->icanon) {
815                 if (c == ERASE_CHAR(tty) || c == KILL_CHAR(tty) ||
816                     (c == WERASE_CHAR(tty) && L_IEXTEN(tty))) {
817                         eraser(c, tty);
818                         return;
819                 }
820                 if (c == LNEXT_CHAR(tty) && L_IEXTEN(tty)) {
821                         tty->lnext = 1;
822                         if (L_ECHO(tty)) {
823                                 finish_erasing(tty);
824                                 if (L_ECHOCTL(tty)) {
825                                         tty_put_char(tty, '^');
826                                         tty_put_char(tty, '\b');
827                                 }
828                         }
829                         return;
830                 }
831                 if (c == REPRINT_CHAR(tty) && L_ECHO(tty) &&
832                     L_IEXTEN(tty)) {
833                         unsigned long tail = tty->canon_head;
834
835                         finish_erasing(tty);
836                         echo_char(c, tty);
837                         opost('\n', tty);
838                         while (tail != tty->read_head) {
839                                 echo_char(tty->read_buf[tail], tty);
840                                 tail = (tail+1) & (N_TTY_BUF_SIZE-1);
841                         }
842                         return;
843                 }
844                 if (c == '\n') {
845                         if (L_ECHO(tty) || L_ECHONL(tty)) {
846                                 if (tty->read_cnt >= N_TTY_BUF_SIZE-1)
847                                         tty_put_char(tty, '\a');
848                                 opost('\n', tty);
849                         }
850                         goto handle_newline;
851                 }
852                 if (c == EOF_CHAR(tty)) {
853                         if (tty->canon_head != tty->read_head)
854                                 set_bit(TTY_PUSH, &tty->flags);
855                         c = __DISABLED_CHAR;
856                         goto handle_newline;
857                 }
858                 if ((c == EOL_CHAR(tty)) ||
859                     (c == EOL2_CHAR(tty) && L_IEXTEN(tty))) {
860                         /*
861                          * XXX are EOL_CHAR and EOL2_CHAR echoed?!?
862                          */
863                         if (L_ECHO(tty)) {
864                                 if (tty->read_cnt >= N_TTY_BUF_SIZE-1)
865                                         tty_put_char(tty, '\a');
866                                 /* Record the column of first canon char. */
867                                 if (tty->canon_head == tty->read_head)
868                                         tty->canon_column = tty->column;
869                                 echo_char(c, tty);
870                         }
871                         /*
872                          * XXX does PARMRK doubling happen for
873                          * EOL_CHAR and EOL2_CHAR?
874                          */
875                         if (I_PARMRK(tty) && c == (unsigned char) '\377')
876                                 put_tty_queue(c, tty);
877
878 handle_newline:
879                         spin_lock_irqsave(&tty->read_lock, flags);
880                         set_bit(tty->read_head, tty->read_flags);
881                         put_tty_queue_nolock(c, tty);
882                         tty->canon_head = tty->read_head;
883                         tty->canon_data++;
884                         spin_unlock_irqrestore(&tty->read_lock, flags);
885                         kill_fasync(&tty->fasync, SIGIO, POLL_IN);
886                         if (waitqueue_active(&tty->read_wait))
887                                 wake_up_interruptible(&tty->read_wait);
888                         return;
889                 }
890         }
891
892         finish_erasing(tty);
893         if (L_ECHO(tty)) {
894                 if (tty->read_cnt >= N_TTY_BUF_SIZE-1) {
895                         tty_put_char(tty, '\a'); /* beep if no space */
896                         return;
897                 }
898                 if (c == '\n')
899                         opost('\n', tty);
900                 else {
901                         /* Record the column of first canon char. */
902                         if (tty->canon_head == tty->read_head)
903                                 tty->canon_column = tty->column;
904                         echo_char(c, tty);
905                 }
906         }
907
908         if (I_PARMRK(tty) && c == (unsigned char) '\377')
909                 put_tty_queue(c, tty);
910
911         put_tty_queue(c, tty);
912 }
913
914
915 /**
916  *      n_tty_write_wakeup      -       asynchronous I/O notifier
917  *      @tty: tty device
918  *
919  *      Required for the ptys, serial driver etc. since processes
920  *      that attach themselves to the master and rely on ASYNC
921  *      IO must be woken up
922  */
923
924 static void n_tty_write_wakeup(struct tty_struct *tty)
925 {
926         if (tty->fasync) {
927                 set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
928                 kill_fasync(&tty->fasync, SIGIO, POLL_OUT);
929         }
930 }
931
932 /**
933  *      n_tty_receive_buf       -       data receive
934  *      @tty: terminal device
935  *      @cp: buffer
936  *      @fp: flag buffer
937  *      @count: characters
938  *
939  *      Called by the terminal driver when a block of characters has
940  *      been received. This function must be called from soft contexts
941  *      not from interrupt context. The driver is responsible for making
942  *      calls one at a time and in order (or using flush_to_ldisc)
943  */
944
945 static void n_tty_receive_buf(struct tty_struct *tty, const unsigned char *cp,
946                               char *fp, int count)
947 {
948         const unsigned char *p;
949         char *f, flags = TTY_NORMAL;
950         int     i;
951         char    buf[64];
952         unsigned long cpuflags;
953
954         if (!tty->read_buf)
955                 return;
956
957         if (tty->real_raw) {
958                 spin_lock_irqsave(&tty->read_lock, cpuflags);
959                 i = min(N_TTY_BUF_SIZE - tty->read_cnt,
960                         N_TTY_BUF_SIZE - tty->read_head);
961                 i = min(count, i);
962                 memcpy(tty->read_buf + tty->read_head, cp, i);
963                 tty->read_head = (tty->read_head + i) & (N_TTY_BUF_SIZE-1);
964                 tty->read_cnt += i;
965                 cp += i;
966                 count -= i;
967
968                 i = min(N_TTY_BUF_SIZE - tty->read_cnt,
969                         N_TTY_BUF_SIZE - tty->read_head);
970                 i = min(count, i);
971                 memcpy(tty->read_buf + tty->read_head, cp, i);
972                 tty->read_head = (tty->read_head + i) & (N_TTY_BUF_SIZE-1);
973                 tty->read_cnt += i;
974                 spin_unlock_irqrestore(&tty->read_lock, cpuflags);
975         } else {
976                 for (i = count, p = cp, f = fp; i; i--, p++) {
977                         if (f)
978                                 flags = *f++;
979                         switch (flags) {
980                         case TTY_NORMAL:
981                                 n_tty_receive_char(tty, *p);
982                                 break;
983                         case TTY_BREAK:
984                                 n_tty_receive_break(tty);
985                                 break;
986                         case TTY_PARITY:
987                         case TTY_FRAME:
988                                 n_tty_receive_parity_error(tty, *p);
989                                 break;
990                         case TTY_OVERRUN:
991                                 n_tty_receive_overrun(tty);
992                                 break;
993                         default:
994                                 printk(KERN_ERR "%s: unknown flag %d\n",
995                                        tty_name(tty, buf), flags);
996                                 break;
997                         }
998                 }
999                 if (tty->ops->flush_chars)
1000                         tty->ops->flush_chars(tty);
1001         }
1002
1003         n_tty_set_room(tty);
1004
1005         if (!tty->icanon && (tty->read_cnt >= tty->minimum_to_wake)) {
1006                 kill_fasync(&tty->fasync, SIGIO, POLL_IN);
1007                 if (waitqueue_active(&tty->read_wait))
1008                         wake_up_interruptible(&tty->read_wait);
1009         }
1010
1011         /*
1012          * Check the remaining room for the input canonicalization
1013          * mode.  We don't want to throttle the driver if we're in
1014          * canonical mode and don't have a newline yet!
1015          */
1016         if (tty->receive_room < TTY_THRESHOLD_THROTTLE)
1017                 tty_throttle(tty);
1018 }
1019
1020 int is_ignored(int sig)
1021 {
1022         return (sigismember(&current->blocked, sig) ||
1023                 current->sighand->action[sig-1].sa.sa_handler == SIG_IGN);
1024 }
1025
1026 /**
1027  *      n_tty_set_termios       -       termios data changed
1028  *      @tty: terminal
1029  *      @old: previous data
1030  *
1031  *      Called by the tty layer when the user changes termios flags so
1032  *      that the line discipline can plan ahead. This function cannot sleep
1033  *      and is protected from re-entry by the tty layer. The user is
1034  *      guaranteed that this function will not be re-entered or in progress
1035  *      when the ldisc is closed.
1036  *
1037  *      Locking: Caller holds tty->termios_mutex
1038  */
1039
1040 static void n_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
1041 {
1042         int canon_change = 1;
1043         BUG_ON(!tty);
1044
1045         if (old)
1046                 canon_change = (old->c_lflag ^ tty->termios->c_lflag) & ICANON;
1047         if (canon_change) {
1048                 memset(&tty->read_flags, 0, sizeof tty->read_flags);
1049                 tty->canon_head = tty->read_tail;
1050                 tty->canon_data = 0;
1051                 tty->erasing = 0;
1052         }
1053
1054         if (canon_change && !L_ICANON(tty) && tty->read_cnt)
1055                 wake_up_interruptible(&tty->read_wait);
1056
1057         tty->icanon = (L_ICANON(tty) != 0);
1058         if (test_bit(TTY_HW_COOK_IN, &tty->flags)) {
1059                 tty->raw = 1;
1060                 tty->real_raw = 1;
1061                 n_tty_set_room(tty);
1062                 return;
1063         }
1064         if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
1065             I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
1066             I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
1067             I_PARMRK(tty)) {
1068                 memset(tty->process_char_map, 0, 256/8);
1069
1070                 if (I_IGNCR(tty) || I_ICRNL(tty))
1071                         set_bit('\r', tty->process_char_map);
1072                 if (I_INLCR(tty))
1073                         set_bit('\n', tty->process_char_map);
1074
1075                 if (L_ICANON(tty)) {
1076                         set_bit(ERASE_CHAR(tty), tty->process_char_map);
1077                         set_bit(KILL_CHAR(tty), tty->process_char_map);
1078                         set_bit(EOF_CHAR(tty), tty->process_char_map);
1079                         set_bit('\n', tty->process_char_map);
1080                         set_bit(EOL_CHAR(tty), tty->process_char_map);
1081                         if (L_IEXTEN(tty)) {
1082                                 set_bit(WERASE_CHAR(tty),
1083                                         tty->process_char_map);
1084                                 set_bit(LNEXT_CHAR(tty),
1085                                         tty->process_char_map);
1086                                 set_bit(EOL2_CHAR(tty),
1087                                         tty->process_char_map);
1088                                 if (L_ECHO(tty))
1089                                         set_bit(REPRINT_CHAR(tty),
1090                                                 tty->process_char_map);
1091                         }
1092                 }
1093                 if (I_IXON(tty)) {
1094                         set_bit(START_CHAR(tty), tty->process_char_map);
1095                         set_bit(STOP_CHAR(tty), tty->process_char_map);
1096                 }
1097                 if (L_ISIG(tty)) {
1098                         set_bit(INTR_CHAR(tty), tty->process_char_map);
1099                         set_bit(QUIT_CHAR(tty), tty->process_char_map);
1100                         set_bit(SUSP_CHAR(tty), tty->process_char_map);
1101                 }
1102                 clear_bit(__DISABLED_CHAR, tty->process_char_map);
1103                 tty->raw = 0;
1104                 tty->real_raw = 0;
1105         } else {
1106                 tty->raw = 1;
1107                 if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
1108                     (I_IGNPAR(tty) || !I_INPCK(tty)) &&
1109                     (tty->driver->flags & TTY_DRIVER_REAL_RAW))
1110                         tty->real_raw = 1;
1111                 else
1112                         tty->real_raw = 0;
1113         }
1114         n_tty_set_room(tty);
1115         /* The termios change make the tty ready for I/O */
1116         wake_up_interruptible(&tty->write_wait);
1117         wake_up_interruptible(&tty->read_wait);
1118 }
1119
1120 /**
1121  *      n_tty_close             -       close the ldisc for this tty
1122  *      @tty: device
1123  *
1124  *      Called from the terminal layer when this line discipline is
1125  *      being shut down, either because of a close or becsuse of a
1126  *      discipline change. The function will not be called while other
1127  *      ldisc methods are in progress.
1128  */
1129
1130 static void n_tty_close(struct tty_struct *tty)
1131 {
1132         n_tty_flush_buffer(tty);
1133         if (tty->read_buf) {
1134                 free_buf(tty->read_buf);
1135                 tty->read_buf = NULL;
1136         }
1137 }
1138
1139 /**
1140  *      n_tty_open              -       open an ldisc
1141  *      @tty: terminal to open
1142  *
1143  *      Called when this line discipline is being attached to the
1144  *      terminal device. Can sleep. Called serialized so that no
1145  *      other events will occur in parallel. No further open will occur
1146  *      until a close.
1147  */
1148
1149 static int n_tty_open(struct tty_struct *tty)
1150 {
1151         if (!tty)
1152                 return -EINVAL;
1153
1154         /* This one is ugly. Currently a malloc failure here can panic */
1155         if (!tty->read_buf) {
1156                 tty->read_buf = alloc_buf();
1157                 if (!tty->read_buf)
1158                         return -ENOMEM;
1159         }
1160         memset(tty->read_buf, 0, N_TTY_BUF_SIZE);
1161         reset_buffer_flags(tty);
1162         tty->column = 0;
1163         n_tty_set_termios(tty, NULL);
1164         tty->minimum_to_wake = 1;
1165         tty->closing = 0;
1166         return 0;
1167 }
1168
1169 static inline int input_available_p(struct tty_struct *tty, int amt)
1170 {
1171         if (tty->icanon) {
1172                 if (tty->canon_data)
1173                         return 1;
1174         } else if (tty->read_cnt >= (amt ? amt : 1))
1175                 return 1;
1176
1177         return 0;
1178 }
1179
1180 /**
1181  *      copy_from_read_buf      -       copy read data directly
1182  *      @tty: terminal device
1183  *      @b: user data
1184  *      @nr: size of data
1185  *
1186  *      Helper function to speed up n_tty_read.  It is only called when
1187  *      ICANON is off; it copies characters straight from the tty queue to
1188  *      user space directly.  It can be profitably called twice; once to
1189  *      drain the space from the tail pointer to the (physical) end of the
1190  *      buffer, and once to drain the space from the (physical) beginning of
1191  *      the buffer to head pointer.
1192  *
1193  *      Called under the tty->atomic_read_lock sem
1194  *
1195  */
1196
1197 static int copy_from_read_buf(struct tty_struct *tty,
1198                                       unsigned char __user **b,
1199                                       size_t *nr)
1200
1201 {
1202         int retval;
1203         size_t n;
1204         unsigned long flags;
1205
1206         retval = 0;
1207         spin_lock_irqsave(&tty->read_lock, flags);
1208         n = min(tty->read_cnt, N_TTY_BUF_SIZE - tty->read_tail);
1209         n = min(*nr, n);
1210         spin_unlock_irqrestore(&tty->read_lock, flags);
1211         if (n) {
1212                 retval = copy_to_user(*b, &tty->read_buf[tty->read_tail], n);
1213                 n -= retval;
1214                 tty_audit_add_data(tty, &tty->read_buf[tty->read_tail], n);
1215                 spin_lock_irqsave(&tty->read_lock, flags);
1216                 tty->read_tail = (tty->read_tail + n) & (N_TTY_BUF_SIZE-1);
1217                 tty->read_cnt -= n;
1218                 spin_unlock_irqrestore(&tty->read_lock, flags);
1219                 *b += n;
1220                 *nr -= n;
1221         }
1222         return retval;
1223 }
1224
1225 extern ssize_t redirected_tty_write(struct file *, const char __user *,
1226                                                         size_t, loff_t *);
1227
1228 /**
1229  *      job_control             -       check job control
1230  *      @tty: tty
1231  *      @file: file handle
1232  *
1233  *      Perform job control management checks on this file/tty descriptor
1234  *      and if appropriate send any needed signals and return a negative
1235  *      error code if action should be taken.
1236  *
1237  *      FIXME:
1238  *      Locking: None - redirected write test is safe, testing
1239  *      current->signal should possibly lock current->sighand
1240  *      pgrp locking ?
1241  */
1242
1243 static int job_control(struct tty_struct *tty, struct file *file)
1244 {
1245         /* Job control check -- must be done at start and after
1246            every sleep (POSIX.1 7.1.1.4). */
1247         /* NOTE: not yet done after every sleep pending a thorough
1248            check of the logic of this change. -- jlc */
1249         /* don't stop on /dev/console */
1250         if (file->f_op->write != redirected_tty_write &&
1251             current->signal->tty == tty) {
1252                 if (!tty->pgrp)
1253                         printk(KERN_ERR "n_tty_read: no tty->pgrp!\n");
1254                 else if (task_pgrp(current) != tty->pgrp) {
1255                         if (is_ignored(SIGTTIN) ||
1256                             is_current_pgrp_orphaned())
1257                                 return -EIO;
1258                         kill_pgrp(task_pgrp(current), SIGTTIN, 1);
1259                         set_thread_flag(TIF_SIGPENDING);
1260                         return -ERESTARTSYS;
1261                 }
1262         }
1263         return 0;
1264 }
1265
1266
1267 /**
1268  *      n_tty_read              -       read function for tty
1269  *      @tty: tty device
1270  *      @file: file object
1271  *      @buf: userspace buffer pointer
1272  *      @nr: size of I/O
1273  *
1274  *      Perform reads for the line discipline. We are guaranteed that the
1275  *      line discipline will not be closed under us but we may get multiple
1276  *      parallel readers and must handle this ourselves. We may also get
1277  *      a hangup. Always called in user context, may sleep.
1278  *
1279  *      This code must be sure never to sleep through a hangup.
1280  */
1281
1282 static ssize_t n_tty_read(struct tty_struct *tty, struct file *file,
1283                          unsigned char __user *buf, size_t nr)
1284 {
1285         unsigned char __user *b = buf;
1286         DECLARE_WAITQUEUE(wait, current);
1287         int c;
1288         int minimum, time;
1289         ssize_t retval = 0;
1290         ssize_t size;
1291         long timeout;
1292         unsigned long flags;
1293         int packet;
1294
1295 do_it_again:
1296
1297         BUG_ON(!tty->read_buf);
1298
1299         c = job_control(tty, file);
1300         if (c < 0)
1301                 return c;
1302
1303         minimum = time = 0;
1304         timeout = MAX_SCHEDULE_TIMEOUT;
1305         if (!tty->icanon) {
1306                 time = (HZ / 10) * TIME_CHAR(tty);
1307                 minimum = MIN_CHAR(tty);
1308                 if (minimum) {
1309                         if (time)
1310                                 tty->minimum_to_wake = 1;
1311                         else if (!waitqueue_active(&tty->read_wait) ||
1312                                  (tty->minimum_to_wake > minimum))
1313                                 tty->minimum_to_wake = minimum;
1314                 } else {
1315                         timeout = 0;
1316                         if (time) {
1317                                 timeout = time;
1318                                 time = 0;
1319                         }
1320                         tty->minimum_to_wake = minimum = 1;
1321                 }
1322         }
1323
1324         /*
1325          *      Internal serialization of reads.
1326          */
1327         if (file->f_flags & O_NONBLOCK) {
1328                 if (!mutex_trylock(&tty->atomic_read_lock))
1329                         return -EAGAIN;
1330         } else {
1331                 if (mutex_lock_interruptible(&tty->atomic_read_lock))
1332                         return -ERESTARTSYS;
1333         }
1334         packet = tty->packet;
1335
1336         add_wait_queue(&tty->read_wait, &wait);
1337         while (nr) {
1338                 /* First test for status change. */
1339                 if (packet && tty->link->ctrl_status) {
1340                         unsigned char cs;
1341                         if (b != buf)
1342                                 break;
1343                         spin_lock_irqsave(&tty->link->ctrl_lock, flags);
1344                         cs = tty->link->ctrl_status;
1345                         tty->link->ctrl_status = 0;
1346                         spin_unlock_irqrestore(&tty->link->ctrl_lock, flags);
1347                         if (tty_put_user(tty, cs, b++)) {
1348                                 retval = -EFAULT;
1349                                 b--;
1350                                 break;
1351                         }
1352                         nr--;
1353                         break;
1354                 }
1355                 /* This statement must be first before checking for input
1356                    so that any interrupt will set the state back to
1357                    TASK_RUNNING. */
1358                 set_current_state(TASK_INTERRUPTIBLE);
1359
1360                 if (((minimum - (b - buf)) < tty->minimum_to_wake) &&
1361                     ((minimum - (b - buf)) >= 1))
1362                         tty->minimum_to_wake = (minimum - (b - buf));
1363
1364                 if (!input_available_p(tty, 0)) {
1365                         if (test_bit(TTY_OTHER_CLOSED, &tty->flags)) {
1366                                 retval = -EIO;
1367                                 break;
1368                         }
1369                         if (tty_hung_up_p(file))
1370                                 break;
1371                         if (!timeout)
1372                                 break;
1373                         if (file->f_flags & O_NONBLOCK) {
1374                                 retval = -EAGAIN;
1375                                 break;
1376                         }
1377                         if (signal_pending(current)) {
1378                                 retval = -ERESTARTSYS;
1379                                 break;
1380                         }
1381                         /* FIXME: does n_tty_set_room need locking ? */
1382                         n_tty_set_room(tty);
1383                         timeout = schedule_timeout(timeout);
1384                         continue;
1385                 }
1386                 __set_current_state(TASK_RUNNING);
1387
1388                 /* Deal with packet mode. */
1389                 if (packet && b == buf) {
1390                         if (tty_put_user(tty, TIOCPKT_DATA, b++)) {
1391                                 retval = -EFAULT;
1392                                 b--;
1393                                 break;
1394                         }
1395                         nr--;
1396                 }
1397
1398                 if (tty->icanon) {
1399                         /* N.B. avoid overrun if nr == 0 */
1400                         while (nr && tty->read_cnt) {
1401                                 int eol;
1402
1403                                 eol = test_and_clear_bit(tty->read_tail,
1404                                                 tty->read_flags);
1405                                 c = tty->read_buf[tty->read_tail];
1406                                 spin_lock_irqsave(&tty->read_lock, flags);
1407                                 tty->read_tail = ((tty->read_tail+1) &
1408                                                   (N_TTY_BUF_SIZE-1));
1409                                 tty->read_cnt--;
1410                                 if (eol) {
1411                                         /* this test should be redundant:
1412                                          * we shouldn't be reading data if
1413                                          * canon_data is 0
1414                                          */
1415                                         if (--tty->canon_data < 0)
1416                                                 tty->canon_data = 0;
1417                                 }
1418                                 spin_unlock_irqrestore(&tty->read_lock, flags);
1419
1420                                 if (!eol || (c != __DISABLED_CHAR)) {
1421                                         if (tty_put_user(tty, c, b++)) {
1422                                                 retval = -EFAULT;
1423                                                 b--;
1424                                                 break;
1425                                         }
1426                                         nr--;
1427                                 }
1428                                 if (eol) {
1429                                         tty_audit_push(tty);
1430                                         break;
1431                                 }
1432                         }
1433                         if (retval)
1434                                 break;
1435                 } else {
1436                         int uncopied;
1437                         /* The copy function takes the read lock and handles
1438                            locking internally for this case */
1439                         uncopied = copy_from_read_buf(tty, &b, &nr);
1440                         uncopied += copy_from_read_buf(tty, &b, &nr);
1441                         if (uncopied) {
1442                                 retval = -EFAULT;
1443                                 break;
1444                         }
1445                 }
1446
1447                 /* If there is enough space in the read buffer now, let the
1448                  * low-level driver know. We use n_tty_chars_in_buffer() to
1449                  * check the buffer, as it now knows about canonical mode.
1450                  * Otherwise, if the driver is throttled and the line is
1451                  * longer than TTY_THRESHOLD_UNTHROTTLE in canonical mode,
1452                  * we won't get any more characters.
1453                  */
1454                 if (n_tty_chars_in_buffer(tty) <= TTY_THRESHOLD_UNTHROTTLE) {
1455                         n_tty_set_room(tty);
1456                         check_unthrottle(tty);
1457                 }
1458
1459                 if (b - buf >= minimum)
1460                         break;
1461                 if (time)
1462                         timeout = time;
1463         }
1464         mutex_unlock(&tty->atomic_read_lock);
1465         remove_wait_queue(&tty->read_wait, &wait);
1466
1467         if (!waitqueue_active(&tty->read_wait))
1468                 tty->minimum_to_wake = minimum;
1469
1470         __set_current_state(TASK_RUNNING);
1471         size = b - buf;
1472         if (size) {
1473                 retval = size;
1474                 if (nr)
1475                         clear_bit(TTY_PUSH, &tty->flags);
1476         } else if (test_and_clear_bit(TTY_PUSH, &tty->flags))
1477                  goto do_it_again;
1478
1479         n_tty_set_room(tty);
1480         return retval;
1481 }
1482
1483 /**
1484  *      n_tty_write             -       write function for tty
1485  *      @tty: tty device
1486  *      @file: file object
1487  *      @buf: userspace buffer pointer
1488  *      @nr: size of I/O
1489  *
1490  *      Write function of the terminal device. This is serialized with
1491  *      respect to other write callers but not to termios changes, reads
1492  *      and other such events. We must be careful with N_TTY as the receive
1493  *      code will echo characters, thus calling driver write methods.
1494  *
1495  *      This code must be sure never to sleep through a hangup.
1496  */
1497
1498 static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
1499                           const unsigned char *buf, size_t nr)
1500 {
1501         const unsigned char *b = buf;
1502         DECLARE_WAITQUEUE(wait, current);
1503         int c;
1504         ssize_t retval = 0;
1505
1506         /* Job control check -- must be done at start (POSIX.1 7.1.1.4). */
1507         if (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) {
1508                 retval = tty_check_change(tty);
1509                 if (retval)
1510                         return retval;
1511         }
1512
1513         add_wait_queue(&tty->write_wait, &wait);
1514         while (1) {
1515                 set_current_state(TASK_INTERRUPTIBLE);
1516                 if (signal_pending(current)) {
1517                         retval = -ERESTARTSYS;
1518                         break;
1519                 }
1520                 if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
1521                         retval = -EIO;
1522                         break;
1523                 }
1524                 if (O_OPOST(tty) && !(test_bit(TTY_HW_COOK_OUT, &tty->flags))) {
1525                         while (nr > 0) {
1526                                 ssize_t num = opost_block(tty, b, nr);
1527                                 if (num < 0) {
1528                                         if (num == -EAGAIN)
1529                                                 break;
1530                                         retval = num;
1531                                         goto break_out;
1532                                 }
1533                                 b += num;
1534                                 nr -= num;
1535                                 if (nr == 0)
1536                                         break;
1537                                 c = *b;
1538                                 if (opost(c, tty) < 0)
1539                                         break;
1540                                 b++; nr--;
1541                         }
1542                         if (tty->ops->flush_chars)
1543                                 tty->ops->flush_chars(tty);
1544                 } else {
1545                         while (nr > 0) {
1546                                 c = tty->ops->write(tty, b, nr);
1547                                 if (c < 0) {
1548                                         retval = c;
1549                                         goto break_out;
1550                                 }
1551                                 if (!c)
1552                                         break;
1553                                 b += c;
1554                                 nr -= c;
1555                         }
1556                 }
1557                 if (!nr)
1558                         break;
1559                 if (file->f_flags & O_NONBLOCK) {
1560                         retval = -EAGAIN;
1561                         break;
1562                 }
1563                 schedule();
1564         }
1565 break_out:
1566         __set_current_state(TASK_RUNNING);
1567         remove_wait_queue(&tty->write_wait, &wait);
1568         return (b - buf) ? b - buf : retval;
1569 }
1570
1571 /**
1572  *      n_tty_poll              -       poll method for N_TTY
1573  *      @tty: terminal device
1574  *      @file: file accessing it
1575  *      @wait: poll table
1576  *
1577  *      Called when the line discipline is asked to poll() for data or
1578  *      for special events. This code is not serialized with respect to
1579  *      other events save open/close.
1580  *
1581  *      This code must be sure never to sleep through a hangup.
1582  *      Called without the kernel lock held - fine
1583  */
1584
1585 static unsigned int n_tty_poll(struct tty_struct *tty, struct file *file,
1586                                                         poll_table *wait)
1587 {
1588         unsigned int mask = 0;
1589
1590         poll_wait(file, &tty->read_wait, wait);
1591         poll_wait(file, &tty->write_wait, wait);
1592         if (input_available_p(tty, TIME_CHAR(tty) ? 0 : MIN_CHAR(tty)))
1593                 mask |= POLLIN | POLLRDNORM;
1594         if (tty->packet && tty->link->ctrl_status)
1595                 mask |= POLLPRI | POLLIN | POLLRDNORM;
1596         if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
1597                 mask |= POLLHUP;
1598         if (tty_hung_up_p(file))
1599                 mask |= POLLHUP;
1600         if (!(mask & (POLLHUP | POLLIN | POLLRDNORM))) {
1601                 if (MIN_CHAR(tty) && !TIME_CHAR(tty))
1602                         tty->minimum_to_wake = MIN_CHAR(tty);
1603                 else
1604                         tty->minimum_to_wake = 1;
1605         }
1606         if (tty->ops->write && !tty_is_writelocked(tty) &&
1607                         tty_chars_in_buffer(tty) < WAKEUP_CHARS &&
1608                         tty_write_room(tty) > 0)
1609                 mask |= POLLOUT | POLLWRNORM;
1610         return mask;
1611 }
1612
1613 static unsigned long inq_canon(struct tty_struct *tty)
1614 {
1615         int nr, head, tail;
1616
1617         if (!tty->canon_data)
1618                 return 0;
1619         head = tty->canon_head;
1620         tail = tty->read_tail;
1621         nr = (head - tail) & (N_TTY_BUF_SIZE-1);
1622         /* Skip EOF-chars.. */
1623         while (head != tail) {
1624                 if (test_bit(tail, tty->read_flags) &&
1625                     tty->read_buf[tail] == __DISABLED_CHAR)
1626                         nr--;
1627                 tail = (tail+1) & (N_TTY_BUF_SIZE-1);
1628         }
1629         return nr;
1630 }
1631
1632 static int n_tty_ioctl(struct tty_struct *tty, struct file *file,
1633                        unsigned int cmd, unsigned long arg)
1634 {
1635         int retval;
1636
1637         switch (cmd) {
1638         case TIOCOUTQ:
1639                 return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
1640         case TIOCINQ:
1641                 /* FIXME: Locking */
1642                 retval = tty->read_cnt;
1643                 if (L_ICANON(tty))
1644                         retval = inq_canon(tty);
1645                 return put_user(retval, (unsigned int __user *) arg);
1646         default:
1647                 return n_tty_ioctl_helper(tty, file, cmd, arg);
1648         }
1649 }
1650
1651 struct tty_ldisc_ops tty_ldisc_N_TTY = {
1652         .magic           = TTY_LDISC_MAGIC,
1653         .name            = "n_tty",
1654         .open            = n_tty_open,
1655         .close           = n_tty_close,
1656         .flush_buffer    = n_tty_flush_buffer,
1657         .chars_in_buffer = n_tty_chars_in_buffer,
1658         .read            = n_tty_read,
1659         .write           = n_tty_write,
1660         .ioctl           = n_tty_ioctl,
1661         .set_termios     = n_tty_set_termios,
1662         .poll            = n_tty_poll,
1663         .receive_buf     = n_tty_receive_buf,
1664         .write_wakeup    = n_tty_write_wakeup
1665 };
1666