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