[PATCH] tty locking on resize
[pandora-kernel.git] / drivers / char / tty_io.c
1 /*
2  *  linux/drivers/char/tty_io.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 /*
8  * 'tty_io.c' gives an orthogonal feeling to tty's, be they consoles
9  * or rs-channels. It also implements echoing, cooked mode etc.
10  *
11  * Kill-line thanks to John T Kohl, who also corrected VMIN = VTIME = 0.
12  *
13  * Modified by Theodore Ts'o, 9/14/92, to dynamically allocate the
14  * tty_struct and tty_queue structures.  Previously there was an array
15  * of 256 tty_struct's which was statically allocated, and the
16  * tty_queue structures were allocated at boot time.  Both are now
17  * dynamically allocated only when the tty is open.
18  *
19  * Also restructured routines so that there is more of a separation
20  * between the high-level tty routines (tty_io.c and tty_ioctl.c) and
21  * the low-level tty routines (serial.c, pty.c, console.c).  This
22  * makes for cleaner and more compact code.  -TYT, 9/17/92 
23  *
24  * Modified by Fred N. van Kempen, 01/29/93, to add line disciplines
25  * which can be dynamically activated and de-activated by the line
26  * discipline handling modules (like SLIP).
27  *
28  * NOTE: pay no attention to the line discipline code (yet); its
29  * interface is still subject to change in this version...
30  * -- TYT, 1/31/92
31  *
32  * Added functionality to the OPOST tty handling.  No delays, but all
33  * other bits should be there.
34  *      -- Nick Holloway <alfie@dcs.warwick.ac.uk>, 27th May 1993.
35  *
36  * Rewrote canonical mode and added more termios flags.
37  *      -- julian@uhunix.uhcc.hawaii.edu (J. Cowley), 13Jan94
38  *
39  * Reorganized FASYNC support so mouse code can share it.
40  *      -- ctm@ardi.com, 9Sep95
41  *
42  * New TIOCLINUX variants added.
43  *      -- mj@k332.feld.cvut.cz, 19-Nov-95
44  * 
45  * Restrict vt switching via ioctl()
46  *      -- grif@cs.ucr.edu, 5-Dec-95
47  *
48  * Move console and virtual terminal code to more appropriate files,
49  * implement CONFIG_VT and generalize console device interface.
50  *      -- Marko Kohtala <Marko.Kohtala@hut.fi>, March 97
51  *
52  * Rewrote init_dev and release_dev to eliminate races.
53  *      -- Bill Hawes <whawes@star.net>, June 97
54  *
55  * Added devfs support.
56  *      -- C. Scott Ananian <cananian@alumni.princeton.edu>, 13-Jan-1998
57  *
58  * Added support for a Unix98-style ptmx device.
59  *      -- C. Scott Ananian <cananian@alumni.princeton.edu>, 14-Jan-1998
60  *
61  * Reduced memory usage for older ARM systems
62  *      -- Russell King <rmk@arm.linux.org.uk>
63  *
64  * Move do_SAK() into process context.  Less stack use in devfs functions.
65  * alloc_tty_struct() always uses kmalloc() -- Andrew Morton <andrewm@uow.edu.eu> 17Mar01
66  */
67
68 #include <linux/types.h>
69 #include <linux/major.h>
70 #include <linux/errno.h>
71 #include <linux/signal.h>
72 #include <linux/fcntl.h>
73 #include <linux/sched.h>
74 #include <linux/interrupt.h>
75 #include <linux/tty.h>
76 #include <linux/tty_driver.h>
77 #include <linux/tty_flip.h>
78 #include <linux/devpts_fs.h>
79 #include <linux/file.h>
80 #include <linux/console.h>
81 #include <linux/timer.h>
82 #include <linux/ctype.h>
83 #include <linux/kd.h>
84 #include <linux/mm.h>
85 #include <linux/string.h>
86 #include <linux/slab.h>
87 #include <linux/poll.h>
88 #include <linux/proc_fs.h>
89 #include <linux/init.h>
90 #include <linux/module.h>
91 #include <linux/smp_lock.h>
92 #include <linux/device.h>
93 #include <linux/idr.h>
94 #include <linux/wait.h>
95 #include <linux/bitops.h>
96 #include <linux/delay.h>
97
98 #include <asm/uaccess.h>
99 #include <asm/system.h>
100
101 #include <linux/kbd_kern.h>
102 #include <linux/vt_kern.h>
103 #include <linux/selection.h>
104
105 #include <linux/kmod.h>
106
107 #undef TTY_DEBUG_HANGUP
108
109 #define TTY_PARANOIA_CHECK 1
110 #define CHECK_TTY_COUNT 1
111
112 struct termios tty_std_termios = {      /* for the benefit of tty drivers  */
113         .c_iflag = ICRNL | IXON,
114         .c_oflag = OPOST | ONLCR,
115         .c_cflag = B38400 | CS8 | CREAD | HUPCL,
116         .c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK |
117                    ECHOCTL | ECHOKE | IEXTEN,
118         .c_cc = INIT_C_CC
119 };
120
121 EXPORT_SYMBOL(tty_std_termios);
122
123 /* This list gets poked at by procfs and various bits of boot up code. This
124    could do with some rationalisation such as pulling the tty proc function
125    into this file */
126    
127 LIST_HEAD(tty_drivers);                 /* linked list of tty drivers */
128
129 /* Semaphore to protect creating and releasing a tty. This is shared with
130    vt.c for deeply disgusting hack reasons */
131 DEFINE_MUTEX(tty_mutex);
132
133 #ifdef CONFIG_UNIX98_PTYS
134 extern struct tty_driver *ptm_driver;   /* Unix98 pty masters; for /dev/ptmx */
135 extern int pty_limit;           /* Config limit on Unix98 ptys */
136 static DEFINE_IDR(allocated_ptys);
137 static DECLARE_MUTEX(allocated_ptys_lock);
138 static int ptmx_open(struct inode *, struct file *);
139 #endif
140
141 extern void disable_early_printk(void);
142
143 static void initialize_tty_struct(struct tty_struct *tty);
144
145 static ssize_t tty_read(struct file *, char __user *, size_t, loff_t *);
146 static ssize_t tty_write(struct file *, const char __user *, size_t, loff_t *);
147 ssize_t redirected_tty_write(struct file *, const char __user *, size_t, loff_t *);
148 static unsigned int tty_poll(struct file *, poll_table *);
149 static int tty_open(struct inode *, struct file *);
150 static int tty_release(struct inode *, struct file *);
151 int tty_ioctl(struct inode * inode, struct file * file,
152               unsigned int cmd, unsigned long arg);
153 static int tty_fasync(int fd, struct file * filp, int on);
154 static void release_mem(struct tty_struct *tty, int idx);
155
156 /**
157  *      alloc_tty_struct        -       allocate a tty object
158  *
159  *      Return a new empty tty structure. The data fields have not
160  *      been initialized in any way but has been zeroed
161  *
162  *      Locking: none
163  *      FIXME: use kzalloc
164  */
165
166 static struct tty_struct *alloc_tty_struct(void)
167 {
168         struct tty_struct *tty;
169
170         tty = kmalloc(sizeof(struct tty_struct), GFP_KERNEL);
171         if (tty)
172                 memset(tty, 0, sizeof(struct tty_struct));
173         return tty;
174 }
175
176 static void tty_buffer_free_all(struct tty_struct *);
177
178 /**
179  *      free_tty_struct         -       free a disused tty
180  *      @tty: tty struct to free
181  *
182  *      Free the write buffers, tty queue and tty memory itself.
183  *
184  *      Locking: none. Must be called after tty is definitely unused
185  */
186
187 static inline void free_tty_struct(struct tty_struct *tty)
188 {
189         kfree(tty->write_buf);
190         tty_buffer_free_all(tty);
191         kfree(tty);
192 }
193
194 #define TTY_NUMBER(tty) ((tty)->index + (tty)->driver->name_base)
195
196 /**
197  *      tty_name        -       return tty naming
198  *      @tty: tty structure
199  *      @buf: buffer for output
200  *
201  *      Convert a tty structure into a name. The name reflects the kernel
202  *      naming policy and if udev is in use may not reflect user space
203  *
204  *      Locking: none
205  */
206
207 char *tty_name(struct tty_struct *tty, char *buf)
208 {
209         if (!tty) /* Hmm.  NULL pointer.  That's fun. */
210                 strcpy(buf, "NULL tty");
211         else
212                 strcpy(buf, tty->name);
213         return buf;
214 }
215
216 EXPORT_SYMBOL(tty_name);
217
218 int tty_paranoia_check(struct tty_struct *tty, struct inode *inode,
219                               const char *routine)
220 {
221 #ifdef TTY_PARANOIA_CHECK
222         if (!tty) {
223                 printk(KERN_WARNING
224                         "null TTY for (%d:%d) in %s\n",
225                         imajor(inode), iminor(inode), routine);
226                 return 1;
227         }
228         if (tty->magic != TTY_MAGIC) {
229                 printk(KERN_WARNING
230                         "bad magic number for tty struct (%d:%d) in %s\n",
231                         imajor(inode), iminor(inode), routine);
232                 return 1;
233         }
234 #endif
235         return 0;
236 }
237
238 static int check_tty_count(struct tty_struct *tty, const char *routine)
239 {
240 #ifdef CHECK_TTY_COUNT
241         struct list_head *p;
242         int count = 0;
243         
244         file_list_lock();
245         list_for_each(p, &tty->tty_files) {
246                 count++;
247         }
248         file_list_unlock();
249         if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
250             tty->driver->subtype == PTY_TYPE_SLAVE &&
251             tty->link && tty->link->count)
252                 count++;
253         if (tty->count != count) {
254                 printk(KERN_WARNING "Warning: dev (%s) tty->count(%d) "
255                                     "!= #fd's(%d) in %s\n",
256                        tty->name, tty->count, count, routine);
257                 return count;
258        }        
259 #endif
260         return 0;
261 }
262
263 /*
264  * Tty buffer allocation management
265  */
266
267
268 /**
269  *      tty_buffer_free_all             -       free buffers used by a tty
270  *      @tty: tty to free from
271  *
272  *      Remove all the buffers pending on a tty whether queued with data
273  *      or in the free ring. Must be called when the tty is no longer in use
274  *
275  *      Locking: none
276  */
277
278
279 /**
280  *      tty_buffer_free_all             -       free buffers used by a tty
281  *      @tty: tty to free from
282  *
283  *      Remove all the buffers pending on a tty whether queued with data
284  *      or in the free ring. Must be called when the tty is no longer in use
285  *
286  *      Locking: none
287  */
288
289 static void tty_buffer_free_all(struct tty_struct *tty)
290 {
291         struct tty_buffer *thead;
292         while((thead = tty->buf.head) != NULL) {
293                 tty->buf.head = thead->next;
294                 kfree(thead);
295         }
296         while((thead = tty->buf.free) != NULL) {
297                 tty->buf.free = thead->next;
298                 kfree(thead);
299         }
300         tty->buf.tail = NULL;
301         tty->buf.memory_used = 0;
302 }
303
304 /**
305  *      tty_buffer_init         -       prepare a tty buffer structure
306  *      @tty: tty to initialise
307  *
308  *      Set up the initial state of the buffer management for a tty device.
309  *      Must be called before the other tty buffer functions are used.
310  *
311  *      Locking: none
312  */
313
314 static void tty_buffer_init(struct tty_struct *tty)
315 {
316         spin_lock_init(&tty->buf.lock);
317         tty->buf.head = NULL;
318         tty->buf.tail = NULL;
319         tty->buf.free = NULL;
320         tty->buf.memory_used = 0;
321 }
322
323 /**
324  *      tty_buffer_alloc        -       allocate a tty buffer
325  *      @tty: tty device
326  *      @size: desired size (characters)
327  *
328  *      Allocate a new tty buffer to hold the desired number of characters.
329  *      Return NULL if out of memory or the allocation would exceed the
330  *      per device queue
331  *
332  *      Locking: Caller must hold tty->buf.lock
333  */
334
335 static struct tty_buffer *tty_buffer_alloc(struct tty_struct *tty, size_t size)
336 {
337         struct tty_buffer *p;
338
339         if (tty->buf.memory_used + size > 65536)
340                 return NULL;
341         p = kmalloc(sizeof(struct tty_buffer) + 2 * size, GFP_ATOMIC);
342         if(p == NULL)
343                 return NULL;
344         p->used = 0;
345         p->size = size;
346         p->next = NULL;
347         p->commit = 0;
348         p->read = 0;
349         p->char_buf_ptr = (char *)(p->data);
350         p->flag_buf_ptr = (unsigned char *)p->char_buf_ptr + size;
351         tty->buf.memory_used += size;
352         return p;
353 }
354
355 /**
356  *      tty_buffer_free         -       free a tty buffer
357  *      @tty: tty owning the buffer
358  *      @b: the buffer to free
359  *
360  *      Free a tty buffer, or add it to the free list according to our
361  *      internal strategy
362  *
363  *      Locking: Caller must hold tty->buf.lock
364  */
365
366 static void tty_buffer_free(struct tty_struct *tty, struct tty_buffer *b)
367 {
368         /* Dumb strategy for now - should keep some stats */
369         tty->buf.memory_used -= b->size;
370         WARN_ON(tty->buf.memory_used < 0);
371
372         if(b->size >= 512)
373                 kfree(b);
374         else {
375                 b->next = tty->buf.free;
376                 tty->buf.free = b;
377         }
378 }
379
380 /**
381  *      tty_buffer_find         -       find a free tty buffer
382  *      @tty: tty owning the buffer
383  *      @size: characters wanted
384  *
385  *      Locate an existing suitable tty buffer or if we are lacking one then
386  *      allocate a new one. We round our buffers off in 256 character chunks
387  *      to get better allocation behaviour.
388  *
389  *      Locking: Caller must hold tty->buf.lock
390  */
391
392 static struct tty_buffer *tty_buffer_find(struct tty_struct *tty, size_t size)
393 {
394         struct tty_buffer **tbh = &tty->buf.free;
395         while((*tbh) != NULL) {
396                 struct tty_buffer *t = *tbh;
397                 if(t->size >= size) {
398                         *tbh = t->next;
399                         t->next = NULL;
400                         t->used = 0;
401                         t->commit = 0;
402                         t->read = 0;
403                         tty->buf.memory_used += t->size;
404                         return t;
405                 }
406                 tbh = &((*tbh)->next);
407         }
408         /* Round the buffer size out */
409         size = (size + 0xFF) & ~ 0xFF;
410         return tty_buffer_alloc(tty, size);
411         /* Should possibly check if this fails for the largest buffer we
412            have queued and recycle that ? */
413 }
414
415 /**
416  *      tty_buffer_request_room         -       grow tty buffer if needed
417  *      @tty: tty structure
418  *      @size: size desired
419  *
420  *      Make at least size bytes of linear space available for the tty
421  *      buffer. If we fail return the size we managed to find.
422  *
423  *      Locking: Takes tty->buf.lock
424  */
425 int tty_buffer_request_room(struct tty_struct *tty, size_t size)
426 {
427         struct tty_buffer *b, *n;
428         int left;
429         unsigned long flags;
430
431         spin_lock_irqsave(&tty->buf.lock, flags);
432
433         /* OPTIMISATION: We could keep a per tty "zero" sized buffer to
434            remove this conditional if its worth it. This would be invisible
435            to the callers */
436         if ((b = tty->buf.tail) != NULL)
437                 left = b->size - b->used;
438         else
439                 left = 0;
440
441         if (left < size) {
442                 /* This is the slow path - looking for new buffers to use */
443                 if ((n = tty_buffer_find(tty, size)) != NULL) {
444                         if (b != NULL) {
445                                 b->next = n;
446                                 b->commit = b->used;
447                         } else
448                                 tty->buf.head = n;
449                         tty->buf.tail = n;
450                 } else
451                         size = left;
452         }
453
454         spin_unlock_irqrestore(&tty->buf.lock, flags);
455         return size;
456 }
457 EXPORT_SYMBOL_GPL(tty_buffer_request_room);
458
459 /**
460  *      tty_insert_flip_string  -       Add characters to the tty buffer
461  *      @tty: tty structure
462  *      @chars: characters
463  *      @size: size
464  *
465  *      Queue a series of bytes to the tty buffering. All the characters
466  *      passed are marked as without error. Returns the number added.
467  *
468  *      Locking: Called functions may take tty->buf.lock
469  */
470
471 int tty_insert_flip_string(struct tty_struct *tty, const unsigned char *chars,
472                                 size_t size)
473 {
474         int copied = 0;
475         do {
476                 int space = tty_buffer_request_room(tty, size - copied);
477                 struct tty_buffer *tb = tty->buf.tail;
478                 /* If there is no space then tb may be NULL */
479                 if(unlikely(space == 0))
480                         break;
481                 memcpy(tb->char_buf_ptr + tb->used, chars, space);
482                 memset(tb->flag_buf_ptr + tb->used, TTY_NORMAL, space);
483                 tb->used += space;
484                 copied += space;
485                 chars += space;
486                 /* There is a small chance that we need to split the data over
487                    several buffers. If this is the case we must loop */
488         } while (unlikely(size > copied));
489         return copied;
490 }
491 EXPORT_SYMBOL(tty_insert_flip_string);
492
493 /**
494  *      tty_insert_flip_string_flags    -       Add characters to the tty buffer
495  *      @tty: tty structure
496  *      @chars: characters
497  *      @flags: flag bytes
498  *      @size: size
499  *
500  *      Queue a series of bytes to the tty buffering. For each character
501  *      the flags array indicates the status of the character. Returns the
502  *      number added.
503  *
504  *      Locking: Called functions may take tty->buf.lock
505  */
506
507 int tty_insert_flip_string_flags(struct tty_struct *tty,
508                 const unsigned char *chars, const char *flags, size_t size)
509 {
510         int copied = 0;
511         do {
512                 int space = tty_buffer_request_room(tty, size - copied);
513                 struct tty_buffer *tb = tty->buf.tail;
514                 /* If there is no space then tb may be NULL */
515                 if(unlikely(space == 0))
516                         break;
517                 memcpy(tb->char_buf_ptr + tb->used, chars, space);
518                 memcpy(tb->flag_buf_ptr + tb->used, flags, space);
519                 tb->used += space;
520                 copied += space;
521                 chars += space;
522                 flags += space;
523                 /* There is a small chance that we need to split the data over
524                    several buffers. If this is the case we must loop */
525         } while (unlikely(size > copied));
526         return copied;
527 }
528 EXPORT_SYMBOL(tty_insert_flip_string_flags);
529
530 /**
531  *      tty_schedule_flip       -       push characters to ldisc
532  *      @tty: tty to push from
533  *
534  *      Takes any pending buffers and transfers their ownership to the
535  *      ldisc side of the queue. It then schedules those characters for
536  *      processing by the line discipline.
537  *
538  *      Locking: Takes tty->buf.lock
539  */
540
541 void tty_schedule_flip(struct tty_struct *tty)
542 {
543         unsigned long flags;
544         spin_lock_irqsave(&tty->buf.lock, flags);
545         if (tty->buf.tail != NULL)
546                 tty->buf.tail->commit = tty->buf.tail->used;
547         spin_unlock_irqrestore(&tty->buf.lock, flags);
548         schedule_delayed_work(&tty->buf.work, 1);
549 }
550 EXPORT_SYMBOL(tty_schedule_flip);
551
552 /**
553  *      tty_prepare_flip_string         -       make room for characters
554  *      @tty: tty
555  *      @chars: return pointer for character write area
556  *      @size: desired size
557  *
558  *      Prepare a block of space in the buffer for data. Returns the length
559  *      available and buffer pointer to the space which is now allocated and
560  *      accounted for as ready for normal characters. This is used for drivers
561  *      that need their own block copy routines into the buffer. There is no
562  *      guarantee the buffer is a DMA target!
563  *
564  *      Locking: May call functions taking tty->buf.lock
565  */
566
567 int tty_prepare_flip_string(struct tty_struct *tty, unsigned char **chars, size_t size)
568 {
569         int space = tty_buffer_request_room(tty, size);
570         if (likely(space)) {
571                 struct tty_buffer *tb = tty->buf.tail;
572                 *chars = tb->char_buf_ptr + tb->used;
573                 memset(tb->flag_buf_ptr + tb->used, TTY_NORMAL, space);
574                 tb->used += space;
575         }
576         return space;
577 }
578
579 EXPORT_SYMBOL_GPL(tty_prepare_flip_string);
580
581 /**
582  *      tty_prepare_flip_string_flags   -       make room for characters
583  *      @tty: tty
584  *      @chars: return pointer for character write area
585  *      @flags: return pointer for status flag write area
586  *      @size: desired size
587  *
588  *      Prepare a block of space in the buffer for data. Returns the length
589  *      available and buffer pointer to the space which is now allocated and
590  *      accounted for as ready for characters. This is used for drivers
591  *      that need their own block copy routines into the buffer. There is no
592  *      guarantee the buffer is a DMA target!
593  *
594  *      Locking: May call functions taking tty->buf.lock
595  */
596
597 int tty_prepare_flip_string_flags(struct tty_struct *tty, unsigned char **chars, char **flags, size_t size)
598 {
599         int space = tty_buffer_request_room(tty, size);
600         if (likely(space)) {
601                 struct tty_buffer *tb = tty->buf.tail;
602                 *chars = tb->char_buf_ptr + tb->used;
603                 *flags = tb->flag_buf_ptr + tb->used;
604                 tb->used += space;
605         }
606         return space;
607 }
608
609 EXPORT_SYMBOL_GPL(tty_prepare_flip_string_flags);
610
611
612
613 /**
614  *      tty_set_termios_ldisc           -       set ldisc field
615  *      @tty: tty structure
616  *      @num: line discipline number
617  *
618  *      This is probably overkill for real world processors but
619  *      they are not on hot paths so a little discipline won't do 
620  *      any harm.
621  *
622  *      Locking: takes termios_sem
623  */
624  
625 static void tty_set_termios_ldisc(struct tty_struct *tty, int num)
626 {
627         down(&tty->termios_sem);
628         tty->termios->c_line = num;
629         up(&tty->termios_sem);
630 }
631
632 /*
633  *      This guards the refcounted line discipline lists. The lock
634  *      must be taken with irqs off because there are hangup path
635  *      callers who will do ldisc lookups and cannot sleep.
636  */
637  
638 static DEFINE_SPINLOCK(tty_ldisc_lock);
639 static DECLARE_WAIT_QUEUE_HEAD(tty_ldisc_wait);
640 static struct tty_ldisc tty_ldiscs[NR_LDISCS];  /* line disc dispatch table */
641
642 /**
643  *      tty_register_ldisc      -       install a line discipline
644  *      @disc: ldisc number
645  *      @new_ldisc: pointer to the ldisc object
646  *
647  *      Installs a new line discipline into the kernel. The discipline
648  *      is set up as unreferenced and then made available to the kernel
649  *      from this point onwards.
650  *
651  *      Locking:
652  *              takes tty_ldisc_lock to guard against ldisc races
653  */
654
655 int tty_register_ldisc(int disc, struct tty_ldisc *new_ldisc)
656 {
657         unsigned long flags;
658         int ret = 0;
659         
660         if (disc < N_TTY || disc >= NR_LDISCS)
661                 return -EINVAL;
662         
663         spin_lock_irqsave(&tty_ldisc_lock, flags);
664         tty_ldiscs[disc] = *new_ldisc;
665         tty_ldiscs[disc].num = disc;
666         tty_ldiscs[disc].flags |= LDISC_FLAG_DEFINED;
667         tty_ldiscs[disc].refcount = 0;
668         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
669         
670         return ret;
671 }
672 EXPORT_SYMBOL(tty_register_ldisc);
673
674 /**
675  *      tty_unregister_ldisc    -       unload a line discipline
676  *      @disc: ldisc number
677  *      @new_ldisc: pointer to the ldisc object
678  *
679  *      Remove a line discipline from the kernel providing it is not
680  *      currently in use.
681  *
682  *      Locking:
683  *              takes tty_ldisc_lock to guard against ldisc races
684  */
685
686 int tty_unregister_ldisc(int disc)
687 {
688         unsigned long flags;
689         int ret = 0;
690
691         if (disc < N_TTY || disc >= NR_LDISCS)
692                 return -EINVAL;
693
694         spin_lock_irqsave(&tty_ldisc_lock, flags);
695         if (tty_ldiscs[disc].refcount)
696                 ret = -EBUSY;
697         else
698                 tty_ldiscs[disc].flags &= ~LDISC_FLAG_DEFINED;
699         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
700
701         return ret;
702 }
703 EXPORT_SYMBOL(tty_unregister_ldisc);
704
705 /**
706  *      tty_ldisc_get           -       take a reference to an ldisc
707  *      @disc: ldisc number
708  *
709  *      Takes a reference to a line discipline. Deals with refcounts and
710  *      module locking counts. Returns NULL if the discipline is not available.
711  *      Returns a pointer to the discipline and bumps the ref count if it is
712  *      available
713  *
714  *      Locking:
715  *              takes tty_ldisc_lock to guard against ldisc races
716  */
717
718 struct tty_ldisc *tty_ldisc_get(int disc)
719 {
720         unsigned long flags;
721         struct tty_ldisc *ld;
722
723         if (disc < N_TTY || disc >= NR_LDISCS)
724                 return NULL;
725         
726         spin_lock_irqsave(&tty_ldisc_lock, flags);
727
728         ld = &tty_ldiscs[disc];
729         /* Check the entry is defined */
730         if(ld->flags & LDISC_FLAG_DEFINED)
731         {
732                 /* If the module is being unloaded we can't use it */
733                 if (!try_module_get(ld->owner))
734                         ld = NULL;
735                 else /* lock it */
736                         ld->refcount++;
737         }
738         else
739                 ld = NULL;
740         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
741         return ld;
742 }
743
744 EXPORT_SYMBOL_GPL(tty_ldisc_get);
745
746 /**
747  *      tty_ldisc_put           -       drop ldisc reference
748  *      @disc: ldisc number
749  *
750  *      Drop a reference to a line discipline. Manage refcounts and
751  *      module usage counts
752  *
753  *      Locking:
754  *              takes tty_ldisc_lock to guard against ldisc races
755  */
756
757 void tty_ldisc_put(int disc)
758 {
759         struct tty_ldisc *ld;
760         unsigned long flags;
761         
762         BUG_ON(disc < N_TTY || disc >= NR_LDISCS);
763                 
764         spin_lock_irqsave(&tty_ldisc_lock, flags);
765         ld = &tty_ldiscs[disc];
766         BUG_ON(ld->refcount == 0);
767         ld->refcount--;
768         module_put(ld->owner);
769         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
770 }
771         
772 EXPORT_SYMBOL_GPL(tty_ldisc_put);
773
774 /**
775  *      tty_ldisc_assign        -       set ldisc on a tty
776  *      @tty: tty to assign
777  *      @ld: line discipline
778  *
779  *      Install an instance of a line discipline into a tty structure. The
780  *      ldisc must have a reference count above zero to ensure it remains/
781  *      The tty instance refcount starts at zero.
782  *
783  *      Locking:
784  *              Caller must hold references
785  */
786
787 static void tty_ldisc_assign(struct tty_struct *tty, struct tty_ldisc *ld)
788 {
789         tty->ldisc = *ld;
790         tty->ldisc.refcount = 0;
791 }
792
793 /**
794  *      tty_ldisc_try           -       internal helper
795  *      @tty: the tty
796  *
797  *      Make a single attempt to grab and bump the refcount on
798  *      the tty ldisc. Return 0 on failure or 1 on success. This is
799  *      used to implement both the waiting and non waiting versions
800  *      of tty_ldisc_ref
801  *
802  *      Locking: takes tty_ldisc_lock
803  */
804
805 static int tty_ldisc_try(struct tty_struct *tty)
806 {
807         unsigned long flags;
808         struct tty_ldisc *ld;
809         int ret = 0;
810         
811         spin_lock_irqsave(&tty_ldisc_lock, flags);
812         ld = &tty->ldisc;
813         if(test_bit(TTY_LDISC, &tty->flags))
814         {
815                 ld->refcount++;
816                 ret = 1;
817         }
818         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
819         return ret;
820 }
821
822 /**
823  *      tty_ldisc_ref_wait      -       wait for the tty ldisc
824  *      @tty: tty device
825  *
826  *      Dereference the line discipline for the terminal and take a 
827  *      reference to it. If the line discipline is in flux then 
828  *      wait patiently until it changes.
829  *
830  *      Note: Must not be called from an IRQ/timer context. The caller
831  *      must also be careful not to hold other locks that will deadlock
832  *      against a discipline change, such as an existing ldisc reference
833  *      (which we check for)
834  *
835  *      Locking: call functions take tty_ldisc_lock
836  */
837  
838 struct tty_ldisc *tty_ldisc_ref_wait(struct tty_struct *tty)
839 {
840         /* wait_event is a macro */
841         wait_event(tty_ldisc_wait, tty_ldisc_try(tty));
842         if(tty->ldisc.refcount == 0)
843                 printk(KERN_ERR "tty_ldisc_ref_wait\n");
844         return &tty->ldisc;
845 }
846
847 EXPORT_SYMBOL_GPL(tty_ldisc_ref_wait);
848
849 /**
850  *      tty_ldisc_ref           -       get the tty ldisc
851  *      @tty: tty device
852  *
853  *      Dereference the line discipline for the terminal and take a 
854  *      reference to it. If the line discipline is in flux then 
855  *      return NULL. Can be called from IRQ and timer functions.
856  *
857  *      Locking: called functions take tty_ldisc_lock
858  */
859  
860 struct tty_ldisc *tty_ldisc_ref(struct tty_struct *tty)
861 {
862         if(tty_ldisc_try(tty))
863                 return &tty->ldisc;
864         return NULL;
865 }
866
867 EXPORT_SYMBOL_GPL(tty_ldisc_ref);
868
869 /**
870  *      tty_ldisc_deref         -       free a tty ldisc reference
871  *      @ld: reference to free up
872  *
873  *      Undoes the effect of tty_ldisc_ref or tty_ldisc_ref_wait. May
874  *      be called in IRQ context.
875  *
876  *      Locking: takes tty_ldisc_lock
877  */
878  
879 void tty_ldisc_deref(struct tty_ldisc *ld)
880 {
881         unsigned long flags;
882
883         BUG_ON(ld == NULL);
884                 
885         spin_lock_irqsave(&tty_ldisc_lock, flags);
886         if(ld->refcount == 0)
887                 printk(KERN_ERR "tty_ldisc_deref: no references.\n");
888         else
889                 ld->refcount--;
890         if(ld->refcount == 0)
891                 wake_up(&tty_ldisc_wait);
892         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
893 }
894
895 EXPORT_SYMBOL_GPL(tty_ldisc_deref);
896
897 /**
898  *      tty_ldisc_enable        -       allow ldisc use
899  *      @tty: terminal to activate ldisc on
900  *
901  *      Set the TTY_LDISC flag when the line discipline can be called
902  *      again. Do neccessary wakeups for existing sleepers.
903  *
904  *      Note: nobody should set this bit except via this function. Clearing
905  *      directly is allowed.
906  */
907
908 static void tty_ldisc_enable(struct tty_struct *tty)
909 {
910         set_bit(TTY_LDISC, &tty->flags);
911         wake_up(&tty_ldisc_wait);
912 }
913         
914 /**
915  *      tty_set_ldisc           -       set line discipline
916  *      @tty: the terminal to set
917  *      @ldisc: the line discipline
918  *
919  *      Set the discipline of a tty line. Must be called from a process
920  *      context.
921  *
922  *      Locking: takes tty_ldisc_lock.
923  *              called functions take termios_sem
924  */
925  
926 static int tty_set_ldisc(struct tty_struct *tty, int ldisc)
927 {
928         int retval = 0;
929         struct tty_ldisc o_ldisc;
930         char buf[64];
931         int work;
932         unsigned long flags;
933         struct tty_ldisc *ld;
934         struct tty_struct *o_tty;
935
936         if ((ldisc < N_TTY) || (ldisc >= NR_LDISCS))
937                 return -EINVAL;
938
939 restart:
940
941         ld = tty_ldisc_get(ldisc);
942         /* Eduardo Blanco <ejbs@cs.cs.com.uy> */
943         /* Cyrus Durgin <cider@speakeasy.org> */
944         if (ld == NULL) {
945                 request_module("tty-ldisc-%d", ldisc);
946                 ld = tty_ldisc_get(ldisc);
947         }
948         if (ld == NULL)
949                 return -EINVAL;
950
951         /*
952          *      No more input please, we are switching. The new ldisc
953          *      will update this value in the ldisc open function
954          */
955
956         tty->receive_room = 0;
957
958         /*
959          *      Problem: What do we do if this blocks ?
960          */
961
962         tty_wait_until_sent(tty, 0);
963
964         if (tty->ldisc.num == ldisc) {
965                 tty_ldisc_put(ldisc);
966                 return 0;
967         }
968
969         o_ldisc = tty->ldisc;
970         o_tty = tty->link;
971
972         /*
973          *      Make sure we don't change while someone holds a
974          *      reference to the line discipline. The TTY_LDISC bit
975          *      prevents anyone taking a reference once it is clear.
976          *      We need the lock to avoid racing reference takers.
977          */
978
979         spin_lock_irqsave(&tty_ldisc_lock, flags);
980         if (tty->ldisc.refcount || (o_tty && o_tty->ldisc.refcount)) {
981                 if(tty->ldisc.refcount) {
982                         /* Free the new ldisc we grabbed. Must drop the lock
983                            first. */
984                         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
985                         tty_ldisc_put(ldisc);
986                         /*
987                          * There are several reasons we may be busy, including
988                          * random momentary I/O traffic. We must therefore
989                          * retry. We could distinguish between blocking ops
990                          * and retries if we made tty_ldisc_wait() smarter. That
991                          * is up for discussion.
992                          */
993                         if (wait_event_interruptible(tty_ldisc_wait, tty->ldisc.refcount == 0) < 0)
994                                 return -ERESTARTSYS;
995                         goto restart;
996                 }
997                 if(o_tty && o_tty->ldisc.refcount) {
998                         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
999                         tty_ldisc_put(ldisc);
1000                         if (wait_event_interruptible(tty_ldisc_wait, o_tty->ldisc.refcount == 0) < 0)
1001                                 return -ERESTARTSYS;
1002                         goto restart;
1003                 }
1004         }
1005
1006         /* if the TTY_LDISC bit is set, then we are racing against another ldisc change */
1007
1008         if (!test_bit(TTY_LDISC, &tty->flags)) {
1009                 spin_unlock_irqrestore(&tty_ldisc_lock, flags);
1010                 tty_ldisc_put(ldisc);
1011                 ld = tty_ldisc_ref_wait(tty);
1012                 tty_ldisc_deref(ld);
1013                 goto restart;
1014         }
1015
1016         clear_bit(TTY_LDISC, &tty->flags);
1017         if (o_tty)
1018                 clear_bit(TTY_LDISC, &o_tty->flags);
1019         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
1020
1021         /*
1022          *      From this point on we know nobody has an ldisc
1023          *      usage reference, nor can they obtain one until
1024          *      we say so later on.
1025          */
1026
1027         work = cancel_delayed_work(&tty->buf.work);
1028         /*
1029          * Wait for ->hangup_work and ->buf.work handlers to terminate
1030          */
1031          
1032         flush_scheduled_work();
1033         /* Shutdown the current discipline. */
1034         if (tty->ldisc.close)
1035                 (tty->ldisc.close)(tty);
1036
1037         /* Now set up the new line discipline. */
1038         tty_ldisc_assign(tty, ld);
1039         tty_set_termios_ldisc(tty, ldisc);
1040         if (tty->ldisc.open)
1041                 retval = (tty->ldisc.open)(tty);
1042         if (retval < 0) {
1043                 tty_ldisc_put(ldisc);
1044                 /* There is an outstanding reference here so this is safe */
1045                 tty_ldisc_assign(tty, tty_ldisc_get(o_ldisc.num));
1046                 tty_set_termios_ldisc(tty, tty->ldisc.num);
1047                 if (tty->ldisc.open && (tty->ldisc.open(tty) < 0)) {
1048                         tty_ldisc_put(o_ldisc.num);
1049                         /* This driver is always present */
1050                         tty_ldisc_assign(tty, tty_ldisc_get(N_TTY));
1051                         tty_set_termios_ldisc(tty, N_TTY);
1052                         if (tty->ldisc.open) {
1053                                 int r = tty->ldisc.open(tty);
1054
1055                                 if (r < 0)
1056                                         panic("Couldn't open N_TTY ldisc for "
1057                                               "%s --- error %d.",
1058                                               tty_name(tty, buf), r);
1059                         }
1060                 }
1061         }
1062         /* At this point we hold a reference to the new ldisc and a
1063            a reference to the old ldisc. If we ended up flipping back
1064            to the existing ldisc we have two references to it */
1065         
1066         if (tty->ldisc.num != o_ldisc.num && tty->driver->set_ldisc)
1067                 tty->driver->set_ldisc(tty);
1068                 
1069         tty_ldisc_put(o_ldisc.num);
1070         
1071         /*
1072          *      Allow ldisc referencing to occur as soon as the driver
1073          *      ldisc callback completes.
1074          */
1075          
1076         tty_ldisc_enable(tty);
1077         if (o_tty)
1078                 tty_ldisc_enable(o_tty);
1079         
1080         /* Restart it in case no characters kick it off. Safe if
1081            already running */
1082         if (work)
1083                 schedule_delayed_work(&tty->buf.work, 1);
1084         return retval;
1085 }
1086
1087 /**
1088  *      get_tty_driver          -       find device of a tty
1089  *      @dev_t: device identifier
1090  *      @index: returns the index of the tty
1091  *
1092  *      This routine returns a tty driver structure, given a device number
1093  *      and also passes back the index number.
1094  *
1095  *      Locking: caller must hold tty_mutex
1096  */
1097
1098 static struct tty_driver *get_tty_driver(dev_t device, int *index)
1099 {
1100         struct tty_driver *p;
1101
1102         list_for_each_entry(p, &tty_drivers, tty_drivers) {
1103                 dev_t base = MKDEV(p->major, p->minor_start);
1104                 if (device < base || device >= base + p->num)
1105                         continue;
1106                 *index = device - base;
1107                 return p;
1108         }
1109         return NULL;
1110 }
1111
1112 /**
1113  *      tty_check_change        -       check for POSIX terminal changes
1114  *      @tty: tty to check
1115  *
1116  *      If we try to write to, or set the state of, a terminal and we're
1117  *      not in the foreground, send a SIGTTOU.  If the signal is blocked or
1118  *      ignored, go ahead and perform the operation.  (POSIX 7.2)
1119  *
1120  *      Locking: none
1121  */
1122
1123 int tty_check_change(struct tty_struct * tty)
1124 {
1125         if (current->signal->tty != tty)
1126                 return 0;
1127         if (tty->pgrp <= 0) {
1128                 printk(KERN_WARNING "tty_check_change: tty->pgrp <= 0!\n");
1129                 return 0;
1130         }
1131         if (process_group(current) == tty->pgrp)
1132                 return 0;
1133         if (is_ignored(SIGTTOU))
1134                 return 0;
1135         if (is_orphaned_pgrp(process_group(current)))
1136                 return -EIO;
1137         (void) kill_pg(process_group(current), SIGTTOU, 1);
1138         return -ERESTARTSYS;
1139 }
1140
1141 EXPORT_SYMBOL(tty_check_change);
1142
1143 static ssize_t hung_up_tty_read(struct file * file, char __user * buf,
1144                                 size_t count, loff_t *ppos)
1145 {
1146         return 0;
1147 }
1148
1149 static ssize_t hung_up_tty_write(struct file * file, const char __user * buf,
1150                                  size_t count, loff_t *ppos)
1151 {
1152         return -EIO;
1153 }
1154
1155 /* No kernel lock held - none needed ;) */
1156 static unsigned int hung_up_tty_poll(struct file * filp, poll_table * wait)
1157 {
1158         return POLLIN | POLLOUT | POLLERR | POLLHUP | POLLRDNORM | POLLWRNORM;
1159 }
1160
1161 static int hung_up_tty_ioctl(struct inode * inode, struct file * file,
1162                              unsigned int cmd, unsigned long arg)
1163 {
1164         return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
1165 }
1166
1167 static const struct file_operations tty_fops = {
1168         .llseek         = no_llseek,
1169         .read           = tty_read,
1170         .write          = tty_write,
1171         .poll           = tty_poll,
1172         .ioctl          = tty_ioctl,
1173         .open           = tty_open,
1174         .release        = tty_release,
1175         .fasync         = tty_fasync,
1176 };
1177
1178 #ifdef CONFIG_UNIX98_PTYS
1179 static const struct file_operations ptmx_fops = {
1180         .llseek         = no_llseek,
1181         .read           = tty_read,
1182         .write          = tty_write,
1183         .poll           = tty_poll,
1184         .ioctl          = tty_ioctl,
1185         .open           = ptmx_open,
1186         .release        = tty_release,
1187         .fasync         = tty_fasync,
1188 };
1189 #endif
1190
1191 static const struct file_operations console_fops = {
1192         .llseek         = no_llseek,
1193         .read           = tty_read,
1194         .write          = redirected_tty_write,
1195         .poll           = tty_poll,
1196         .ioctl          = tty_ioctl,
1197         .open           = tty_open,
1198         .release        = tty_release,
1199         .fasync         = tty_fasync,
1200 };
1201
1202 static const struct file_operations hung_up_tty_fops = {
1203         .llseek         = no_llseek,
1204         .read           = hung_up_tty_read,
1205         .write          = hung_up_tty_write,
1206         .poll           = hung_up_tty_poll,
1207         .ioctl          = hung_up_tty_ioctl,
1208         .release        = tty_release,
1209 };
1210
1211 static DEFINE_SPINLOCK(redirect_lock);
1212 static struct file *redirect;
1213
1214 /**
1215  *      tty_wakeup      -       request more data
1216  *      @tty: terminal
1217  *
1218  *      Internal and external helper for wakeups of tty. This function
1219  *      informs the line discipline if present that the driver is ready
1220  *      to receive more output data.
1221  */
1222  
1223 void tty_wakeup(struct tty_struct *tty)
1224 {
1225         struct tty_ldisc *ld;
1226         
1227         if (test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) {
1228                 ld = tty_ldisc_ref(tty);
1229                 if(ld) {
1230                         if(ld->write_wakeup)
1231                                 ld->write_wakeup(tty);
1232                         tty_ldisc_deref(ld);
1233                 }
1234         }
1235         wake_up_interruptible(&tty->write_wait);
1236 }
1237
1238 EXPORT_SYMBOL_GPL(tty_wakeup);
1239
1240 /**
1241  *      tty_ldisc_flush -       flush line discipline queue
1242  *      @tty: tty
1243  *
1244  *      Flush the line discipline queue (if any) for this tty. If there
1245  *      is no line discipline active this is a no-op.
1246  */
1247  
1248 void tty_ldisc_flush(struct tty_struct *tty)
1249 {
1250         struct tty_ldisc *ld = tty_ldisc_ref(tty);
1251         if(ld) {
1252                 if(ld->flush_buffer)
1253                         ld->flush_buffer(tty);
1254                 tty_ldisc_deref(ld);
1255         }
1256 }
1257
1258 EXPORT_SYMBOL_GPL(tty_ldisc_flush);
1259         
1260 /**
1261  *      do_tty_hangup           -       actual handler for hangup events
1262  *      @data: tty device
1263  *
1264  *      This can be called by the "eventd" kernel thread.  That is process
1265  *      synchronous but doesn't hold any locks, so we need to make sure we
1266  *      have the appropriate locks for what we're doing.
1267  *
1268  *      The hangup event clears any pending redirections onto the hung up
1269  *      device. It ensures future writes will error and it does the needed
1270  *      line discipline hangup and signal delivery. The tty object itself
1271  *      remains intact.
1272  *
1273  *      Locking:
1274  *              BKL
1275  *              redirect lock for undoing redirection
1276  *              file list lock for manipulating list of ttys
1277  *              tty_ldisc_lock from called functions
1278  *              termios_sem resetting termios data
1279  *              tasklist_lock to walk task list for hangup event
1280  *
1281  */
1282 static void do_tty_hangup(void *data)
1283 {
1284         struct tty_struct *tty = (struct tty_struct *) data;
1285         struct file * cons_filp = NULL;
1286         struct file *filp, *f = NULL;
1287         struct task_struct *p;
1288         struct tty_ldisc *ld;
1289         int    closecount = 0, n;
1290
1291         if (!tty)
1292                 return;
1293
1294         /* inuse_filps is protected by the single kernel lock */
1295         lock_kernel();
1296
1297         spin_lock(&redirect_lock);
1298         if (redirect && redirect->private_data == tty) {
1299                 f = redirect;
1300                 redirect = NULL;
1301         }
1302         spin_unlock(&redirect_lock);
1303         
1304         check_tty_count(tty, "do_tty_hangup");
1305         file_list_lock();
1306         /* This breaks for file handles being sent over AF_UNIX sockets ? */
1307         list_for_each_entry(filp, &tty->tty_files, f_u.fu_list) {
1308                 if (filp->f_op->write == redirected_tty_write)
1309                         cons_filp = filp;
1310                 if (filp->f_op->write != tty_write)
1311                         continue;
1312                 closecount++;
1313                 tty_fasync(-1, filp, 0);        /* can't block */
1314                 filp->f_op = &hung_up_tty_fops;
1315         }
1316         file_list_unlock();
1317         
1318         /* FIXME! What are the locking issues here? This may me overdoing things..
1319          * this question is especially important now that we've removed the irqlock. */
1320
1321         ld = tty_ldisc_ref(tty);
1322         if(ld != NULL)  /* We may have no line discipline at this point */
1323         {
1324                 if (ld->flush_buffer)
1325                         ld->flush_buffer(tty);
1326                 if (tty->driver->flush_buffer)
1327                         tty->driver->flush_buffer(tty);
1328                 if ((test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) &&
1329                     ld->write_wakeup)
1330                         ld->write_wakeup(tty);
1331                 if (ld->hangup)
1332                         ld->hangup(tty);
1333         }
1334
1335         /* FIXME: Once we trust the LDISC code better we can wait here for
1336            ldisc completion and fix the driver call race */
1337            
1338         wake_up_interruptible(&tty->write_wait);
1339         wake_up_interruptible(&tty->read_wait);
1340
1341         /*
1342          * Shutdown the current line discipline, and reset it to
1343          * N_TTY.
1344          */
1345         if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
1346         {
1347                 down(&tty->termios_sem);
1348                 *tty->termios = tty->driver->init_termios;
1349                 up(&tty->termios_sem);
1350         }
1351         
1352         /* Defer ldisc switch */
1353         /* tty_deferred_ldisc_switch(N_TTY);
1354         
1355           This should get done automatically when the port closes and
1356           tty_release is called */
1357         
1358         read_lock(&tasklist_lock);
1359         if (tty->session > 0) {
1360                 do_each_task_pid(tty->session, PIDTYPE_SID, p) {
1361                         if (p->signal->tty == tty)
1362                                 p->signal->tty = NULL;
1363                         if (!p->signal->leader)
1364                                 continue;
1365                         group_send_sig_info(SIGHUP, SEND_SIG_PRIV, p);
1366                         group_send_sig_info(SIGCONT, SEND_SIG_PRIV, p);
1367                         if (tty->pgrp > 0)
1368                                 p->signal->tty_old_pgrp = tty->pgrp;
1369                 } while_each_task_pid(tty->session, PIDTYPE_SID, p);
1370         }
1371         read_unlock(&tasklist_lock);
1372
1373         tty->flags = 0;
1374         tty->session = 0;
1375         tty->pgrp = -1;
1376         tty->ctrl_status = 0;
1377         /*
1378          *      If one of the devices matches a console pointer, we
1379          *      cannot just call hangup() because that will cause
1380          *      tty->count and state->count to go out of sync.
1381          *      So we just call close() the right number of times.
1382          */
1383         if (cons_filp) {
1384                 if (tty->driver->close)
1385                         for (n = 0; n < closecount; n++)
1386                                 tty->driver->close(tty, cons_filp);
1387         } else if (tty->driver->hangup)
1388                 (tty->driver->hangup)(tty);
1389                 
1390         /* We don't want to have driver/ldisc interactions beyond
1391            the ones we did here. The driver layer expects no
1392            calls after ->hangup() from the ldisc side. However we
1393            can't yet guarantee all that */
1394
1395         set_bit(TTY_HUPPED, &tty->flags);
1396         if (ld) {
1397                 tty_ldisc_enable(tty);
1398                 tty_ldisc_deref(ld);
1399         }
1400         unlock_kernel();
1401         if (f)
1402                 fput(f);
1403 }
1404
1405 /**
1406  *      tty_hangup              -       trigger a hangup event
1407  *      @tty: tty to hangup
1408  *
1409  *      A carrier loss (virtual or otherwise) has occurred on this like
1410  *      schedule a hangup sequence to run after this event.
1411  */
1412
1413 void tty_hangup(struct tty_struct * tty)
1414 {
1415 #ifdef TTY_DEBUG_HANGUP
1416         char    buf[64];
1417         
1418         printk(KERN_DEBUG "%s hangup...\n", tty_name(tty, buf));
1419 #endif
1420         schedule_work(&tty->hangup_work);
1421 }
1422
1423 EXPORT_SYMBOL(tty_hangup);
1424
1425 /**
1426  *      tty_vhangup             -       process vhangup
1427  *      @tty: tty to hangup
1428  *
1429  *      The user has asked via system call for the terminal to be hung up.
1430  *      We do this synchronously so that when the syscall returns the process
1431  *      is complete. That guarantee is neccessary for security reasons.
1432  */
1433
1434 void tty_vhangup(struct tty_struct * tty)
1435 {
1436 #ifdef TTY_DEBUG_HANGUP
1437         char    buf[64];
1438
1439         printk(KERN_DEBUG "%s vhangup...\n", tty_name(tty, buf));
1440 #endif
1441         do_tty_hangup((void *) tty);
1442 }
1443 EXPORT_SYMBOL(tty_vhangup);
1444
1445 /**
1446  *      tty_hung_up_p           -       was tty hung up
1447  *      @filp: file pointer of tty
1448  *
1449  *      Return true if the tty has been subject to a vhangup or a carrier
1450  *      loss
1451  */
1452
1453 int tty_hung_up_p(struct file * filp)
1454 {
1455         return (filp->f_op == &hung_up_tty_fops);
1456 }
1457
1458 EXPORT_SYMBOL(tty_hung_up_p);
1459
1460 /**
1461  *      disassociate_ctty       -       disconnect controlling tty
1462  *      @on_exit: true if exiting so need to "hang up" the session
1463  *
1464  *      This function is typically called only by the session leader, when
1465  *      it wants to disassociate itself from its controlling tty.
1466  *
1467  *      It performs the following functions:
1468  *      (1)  Sends a SIGHUP and SIGCONT to the foreground process group
1469  *      (2)  Clears the tty from being controlling the session
1470  *      (3)  Clears the controlling tty for all processes in the
1471  *              session group.
1472  *
1473  *      The argument on_exit is set to 1 if called when a process is
1474  *      exiting; it is 0 if called by the ioctl TIOCNOTTY.
1475  *
1476  *      Locking: tty_mutex is taken to protect current->signal->tty
1477  *              BKL is taken for hysterical raisins
1478  *              Tasklist lock is taken (under tty_mutex) to walk process
1479  *              lists for the session.
1480  */
1481
1482 void disassociate_ctty(int on_exit)
1483 {
1484         struct tty_struct *tty;
1485         struct task_struct *p;
1486         int tty_pgrp = -1;
1487
1488         lock_kernel();
1489
1490         mutex_lock(&tty_mutex);
1491         tty = current->signal->tty;
1492         if (tty) {
1493                 tty_pgrp = tty->pgrp;
1494                 mutex_unlock(&tty_mutex);
1495                 if (on_exit && tty->driver->type != TTY_DRIVER_TYPE_PTY)
1496                         tty_vhangup(tty);
1497         } else {
1498                 if (current->signal->tty_old_pgrp) {
1499                         kill_pg(current->signal->tty_old_pgrp, SIGHUP, on_exit);
1500                         kill_pg(current->signal->tty_old_pgrp, SIGCONT, on_exit);
1501                 }
1502                 mutex_unlock(&tty_mutex);
1503                 unlock_kernel();        
1504                 return;
1505         }
1506         if (tty_pgrp > 0) {
1507                 kill_pg(tty_pgrp, SIGHUP, on_exit);
1508                 if (!on_exit)
1509                         kill_pg(tty_pgrp, SIGCONT, on_exit);
1510         }
1511
1512         /* Must lock changes to tty_old_pgrp */
1513         mutex_lock(&tty_mutex);
1514         current->signal->tty_old_pgrp = 0;
1515         tty->session = 0;
1516         tty->pgrp = -1;
1517
1518         /* Now clear signal->tty under the lock */
1519         read_lock(&tasklist_lock);
1520         do_each_task_pid(current->signal->session, PIDTYPE_SID, p) {
1521                 p->signal->tty = NULL;
1522         } while_each_task_pid(current->signal->session, PIDTYPE_SID, p);
1523         read_unlock(&tasklist_lock);
1524         mutex_unlock(&tty_mutex);
1525         unlock_kernel();
1526 }
1527
1528
1529 /**
1530  *      stop_tty        -       propogate flow control
1531  *      @tty: tty to stop
1532  *
1533  *      Perform flow control to the driver. For PTY/TTY pairs we
1534  *      must also propogate the TIOCKPKT status. May be called
1535  *      on an already stopped device and will not re-call the driver
1536  *      method.
1537  *
1538  *      This functionality is used by both the line disciplines for
1539  *      halting incoming flow and by the driver. It may therefore be
1540  *      called from any context, may be under the tty atomic_write_lock
1541  *      but not always.
1542  *
1543  *      Locking:
1544  *              Broken. Relies on BKL which is unsafe here.
1545  */
1546
1547 void stop_tty(struct tty_struct *tty)
1548 {
1549         if (tty->stopped)
1550                 return;
1551         tty->stopped = 1;
1552         if (tty->link && tty->link->packet) {
1553                 tty->ctrl_status &= ~TIOCPKT_START;
1554                 tty->ctrl_status |= TIOCPKT_STOP;
1555                 wake_up_interruptible(&tty->link->read_wait);
1556         }
1557         if (tty->driver->stop)
1558                 (tty->driver->stop)(tty);
1559 }
1560
1561 EXPORT_SYMBOL(stop_tty);
1562
1563 /**
1564  *      start_tty       -       propogate flow control
1565  *      @tty: tty to start
1566  *
1567  *      Start a tty that has been stopped if at all possible. Perform
1568  *      any neccessary wakeups and propogate the TIOCPKT status. If this
1569  *      is the tty was previous stopped and is being started then the
1570  *      driver start method is invoked and the line discipline woken.
1571  *
1572  *      Locking:
1573  *              Broken. Relies on BKL which is unsafe here.
1574  */
1575
1576 void start_tty(struct tty_struct *tty)
1577 {
1578         if (!tty->stopped || tty->flow_stopped)
1579                 return;
1580         tty->stopped = 0;
1581         if (tty->link && tty->link->packet) {
1582                 tty->ctrl_status &= ~TIOCPKT_STOP;
1583                 tty->ctrl_status |= TIOCPKT_START;
1584                 wake_up_interruptible(&tty->link->read_wait);
1585         }
1586         if (tty->driver->start)
1587                 (tty->driver->start)(tty);
1588
1589         /* If we have a running line discipline it may need kicking */
1590         tty_wakeup(tty);
1591         wake_up_interruptible(&tty->write_wait);
1592 }
1593
1594 EXPORT_SYMBOL(start_tty);
1595
1596 /**
1597  *      tty_read        -       read method for tty device files
1598  *      @file: pointer to tty file
1599  *      @buf: user buffer
1600  *      @count: size of user buffer
1601  *      @ppos: unused
1602  *
1603  *      Perform the read system call function on this terminal device. Checks
1604  *      for hung up devices before calling the line discipline method.
1605  *
1606  *      Locking:
1607  *              Locks the line discipline internally while needed
1608  *              For historical reasons the line discipline read method is
1609  *      invoked under the BKL. This will go away in time so do not rely on it
1610  *      in new code. Multiple read calls may be outstanding in parallel.
1611  */
1612
1613 static ssize_t tty_read(struct file * file, char __user * buf, size_t count, 
1614                         loff_t *ppos)
1615 {
1616         int i;
1617         struct tty_struct * tty;
1618         struct inode *inode;
1619         struct tty_ldisc *ld;
1620
1621         tty = (struct tty_struct *)file->private_data;
1622         inode = file->f_dentry->d_inode;
1623         if (tty_paranoia_check(tty, inode, "tty_read"))
1624                 return -EIO;
1625         if (!tty || (test_bit(TTY_IO_ERROR, &tty->flags)))
1626                 return -EIO;
1627
1628         /* We want to wait for the line discipline to sort out in this
1629            situation */
1630         ld = tty_ldisc_ref_wait(tty);
1631         lock_kernel();
1632         if (ld->read)
1633                 i = (ld->read)(tty,file,buf,count);
1634         else
1635                 i = -EIO;
1636         tty_ldisc_deref(ld);
1637         unlock_kernel();
1638         if (i > 0)
1639                 inode->i_atime = current_fs_time(inode->i_sb);
1640         return i;
1641 }
1642
1643 /*
1644  * Split writes up in sane blocksizes to avoid
1645  * denial-of-service type attacks
1646  */
1647 static inline ssize_t do_tty_write(
1648         ssize_t (*write)(struct tty_struct *, struct file *, const unsigned char *, size_t),
1649         struct tty_struct *tty,
1650         struct file *file,
1651         const char __user *buf,
1652         size_t count)
1653 {
1654         ssize_t ret = 0, written = 0;
1655         unsigned int chunk;
1656         
1657         /* FIXME: O_NDELAY ... */
1658         if (mutex_lock_interruptible(&tty->atomic_write_lock)) {
1659                 return -ERESTARTSYS;
1660         }
1661
1662         /*
1663          * We chunk up writes into a temporary buffer. This
1664          * simplifies low-level drivers immensely, since they
1665          * don't have locking issues and user mode accesses.
1666          *
1667          * But if TTY_NO_WRITE_SPLIT is set, we should use a
1668          * big chunk-size..
1669          *
1670          * The default chunk-size is 2kB, because the NTTY
1671          * layer has problems with bigger chunks. It will
1672          * claim to be able to handle more characters than
1673          * it actually does.
1674          *
1675          * FIXME: This can probably go away now except that 64K chunks
1676          * are too likely to fail unless switched to vmalloc...
1677          */
1678         chunk = 2048;
1679         if (test_bit(TTY_NO_WRITE_SPLIT, &tty->flags))
1680                 chunk = 65536;
1681         if (count < chunk)
1682                 chunk = count;
1683
1684         /* write_buf/write_cnt is protected by the atomic_write_lock mutex */
1685         if (tty->write_cnt < chunk) {
1686                 unsigned char *buf;
1687
1688                 if (chunk < 1024)
1689                         chunk = 1024;
1690
1691                 buf = kmalloc(chunk, GFP_KERNEL);
1692                 if (!buf) {
1693                         mutex_unlock(&tty->atomic_write_lock);
1694                         return -ENOMEM;
1695                 }
1696                 kfree(tty->write_buf);
1697                 tty->write_cnt = chunk;
1698                 tty->write_buf = buf;
1699         }
1700
1701         /* Do the write .. */
1702         for (;;) {
1703                 size_t size = count;
1704                 if (size > chunk)
1705                         size = chunk;
1706                 ret = -EFAULT;
1707                 if (copy_from_user(tty->write_buf, buf, size))
1708                         break;
1709                 lock_kernel();
1710                 ret = write(tty, file, tty->write_buf, size);
1711                 unlock_kernel();
1712                 if (ret <= 0)
1713                         break;
1714                 written += ret;
1715                 buf += ret;
1716                 count -= ret;
1717                 if (!count)
1718                         break;
1719                 ret = -ERESTARTSYS;
1720                 if (signal_pending(current))
1721                         break;
1722                 cond_resched();
1723         }
1724         if (written) {
1725                 struct inode *inode = file->f_dentry->d_inode;
1726                 inode->i_mtime = current_fs_time(inode->i_sb);
1727                 ret = written;
1728         }
1729         mutex_unlock(&tty->atomic_write_lock);
1730         return ret;
1731 }
1732
1733
1734 /**
1735  *      tty_write               -       write method for tty device file
1736  *      @file: tty file pointer
1737  *      @buf: user data to write
1738  *      @count: bytes to write
1739  *      @ppos: unused
1740  *
1741  *      Write data to a tty device via the line discipline.
1742  *
1743  *      Locking:
1744  *              Locks the line discipline as required
1745  *              Writes to the tty driver are serialized by the atomic_write_lock
1746  *      and are then processed in chunks to the device. The line discipline
1747  *      write method will not be involked in parallel for each device
1748  *              The line discipline write method is called under the big
1749  *      kernel lock for historical reasons. New code should not rely on this.
1750  */
1751
1752 static ssize_t tty_write(struct file * file, const char __user * buf, size_t count,
1753                          loff_t *ppos)
1754 {
1755         struct tty_struct * tty;
1756         struct inode *inode = file->f_dentry->d_inode;
1757         ssize_t ret;
1758         struct tty_ldisc *ld;
1759         
1760         tty = (struct tty_struct *)file->private_data;
1761         if (tty_paranoia_check(tty, inode, "tty_write"))
1762                 return -EIO;
1763         if (!tty || !tty->driver->write || (test_bit(TTY_IO_ERROR, &tty->flags)))
1764                 return -EIO;
1765
1766         ld = tty_ldisc_ref_wait(tty);           
1767         if (!ld->write)
1768                 ret = -EIO;
1769         else
1770                 ret = do_tty_write(ld->write, tty, file, buf, count);
1771         tty_ldisc_deref(ld);
1772         return ret;
1773 }
1774
1775 ssize_t redirected_tty_write(struct file * file, const char __user * buf, size_t count,
1776                          loff_t *ppos)
1777 {
1778         struct file *p = NULL;
1779
1780         spin_lock(&redirect_lock);
1781         if (redirect) {
1782                 get_file(redirect);
1783                 p = redirect;
1784         }
1785         spin_unlock(&redirect_lock);
1786
1787         if (p) {
1788                 ssize_t res;
1789                 res = vfs_write(p, buf, count, &p->f_pos);
1790                 fput(p);
1791                 return res;
1792         }
1793
1794         return tty_write(file, buf, count, ppos);
1795 }
1796
1797 static char ptychar[] = "pqrstuvwxyzabcde";
1798
1799 /**
1800  *      pty_line_name   -       generate name for a pty
1801  *      @driver: the tty driver in use
1802  *      @index: the minor number
1803  *      @p: output buffer of at least 6 bytes
1804  *
1805  *      Generate a name from a driver reference and write it to the output
1806  *      buffer.
1807  *
1808  *      Locking: None
1809  */
1810 static void pty_line_name(struct tty_driver *driver, int index, char *p)
1811 {
1812         int i = index + driver->name_base;
1813         /* ->name is initialized to "ttyp", but "tty" is expected */
1814         sprintf(p, "%s%c%x",
1815                         driver->subtype == PTY_TYPE_SLAVE ? "tty" : driver->name,
1816                         ptychar[i >> 4 & 0xf], i & 0xf);
1817 }
1818
1819 /**
1820  *      pty_line_name   -       generate name for a tty
1821  *      @driver: the tty driver in use
1822  *      @index: the minor number
1823  *      @p: output buffer of at least 7 bytes
1824  *
1825  *      Generate a name from a driver reference and write it to the output
1826  *      buffer.
1827  *
1828  *      Locking: None
1829  */
1830 static void tty_line_name(struct tty_driver *driver, int index, char *p)
1831 {
1832         sprintf(p, "%s%d", driver->name, index + driver->name_base);
1833 }
1834
1835 /**
1836  *      init_dev                -       initialise a tty device
1837  *      @driver: tty driver we are opening a device on
1838  *      @idx: device index
1839  *      @tty: returned tty structure
1840  *
1841  *      Prepare a tty device. This may not be a "new" clean device but
1842  *      could also be an active device. The pty drivers require special
1843  *      handling because of this.
1844  *
1845  *      Locking:
1846  *              The function is called under the tty_mutex, which
1847  *      protects us from the tty struct or driver itself going away.
1848  *
1849  *      On exit the tty device has the line discipline attached and
1850  *      a reference count of 1. If a pair was created for pty/tty use
1851  *      and the other was a pty master then it too has a reference count of 1.
1852  *
1853  * WSH 06/09/97: Rewritten to remove races and properly clean up after a
1854  * failed open.  The new code protects the open with a mutex, so it's
1855  * really quite straightforward.  The mutex locking can probably be
1856  * relaxed for the (most common) case of reopening a tty.
1857  */
1858
1859 static int init_dev(struct tty_driver *driver, int idx,
1860         struct tty_struct **ret_tty)
1861 {
1862         struct tty_struct *tty, *o_tty;
1863         struct termios *tp, **tp_loc, *o_tp, **o_tp_loc;
1864         struct termios *ltp, **ltp_loc, *o_ltp, **o_ltp_loc;
1865         int retval = 0;
1866
1867         /* check whether we're reopening an existing tty */
1868         if (driver->flags & TTY_DRIVER_DEVPTS_MEM) {
1869                 tty = devpts_get_tty(idx);
1870                 if (tty && driver->subtype == PTY_TYPE_MASTER)
1871                         tty = tty->link;
1872         } else {
1873                 tty = driver->ttys[idx];
1874         }
1875         if (tty) goto fast_track;
1876
1877         /*
1878          * First time open is complex, especially for PTY devices.
1879          * This code guarantees that either everything succeeds and the
1880          * TTY is ready for operation, or else the table slots are vacated
1881          * and the allocated memory released.  (Except that the termios 
1882          * and locked termios may be retained.)
1883          */
1884
1885         if (!try_module_get(driver->owner)) {
1886                 retval = -ENODEV;
1887                 goto end_init;
1888         }
1889
1890         o_tty = NULL;
1891         tp = o_tp = NULL;
1892         ltp = o_ltp = NULL;
1893
1894         tty = alloc_tty_struct();
1895         if(!tty)
1896                 goto fail_no_mem;
1897         initialize_tty_struct(tty);
1898         tty->driver = driver;
1899         tty->index = idx;
1900         tty_line_name(driver, idx, tty->name);
1901
1902         if (driver->flags & TTY_DRIVER_DEVPTS_MEM) {
1903                 tp_loc = &tty->termios;
1904                 ltp_loc = &tty->termios_locked;
1905         } else {
1906                 tp_loc = &driver->termios[idx];
1907                 ltp_loc = &driver->termios_locked[idx];
1908         }
1909
1910         if (!*tp_loc) {
1911                 tp = (struct termios *) kmalloc(sizeof(struct termios),
1912                                                 GFP_KERNEL);
1913                 if (!tp)
1914                         goto free_mem_out;
1915                 *tp = driver->init_termios;
1916         }
1917
1918         if (!*ltp_loc) {
1919                 ltp = (struct termios *) kmalloc(sizeof(struct termios),
1920                                                  GFP_KERNEL);
1921                 if (!ltp)
1922                         goto free_mem_out;
1923                 memset(ltp, 0, sizeof(struct termios));
1924         }
1925
1926         if (driver->type == TTY_DRIVER_TYPE_PTY) {
1927                 o_tty = alloc_tty_struct();
1928                 if (!o_tty)
1929                         goto free_mem_out;
1930                 initialize_tty_struct(o_tty);
1931                 o_tty->driver = driver->other;
1932                 o_tty->index = idx;
1933                 tty_line_name(driver->other, idx, o_tty->name);
1934
1935                 if (driver->flags & TTY_DRIVER_DEVPTS_MEM) {
1936                         o_tp_loc = &o_tty->termios;
1937                         o_ltp_loc = &o_tty->termios_locked;
1938                 } else {
1939                         o_tp_loc = &driver->other->termios[idx];
1940                         o_ltp_loc = &driver->other->termios_locked[idx];
1941                 }
1942
1943                 if (!*o_tp_loc) {
1944                         o_tp = (struct termios *)
1945                                 kmalloc(sizeof(struct termios), GFP_KERNEL);
1946                         if (!o_tp)
1947                                 goto free_mem_out;
1948                         *o_tp = driver->other->init_termios;
1949                 }
1950
1951                 if (!*o_ltp_loc) {
1952                         o_ltp = (struct termios *)
1953                                 kmalloc(sizeof(struct termios), GFP_KERNEL);
1954                         if (!o_ltp)
1955                                 goto free_mem_out;
1956                         memset(o_ltp, 0, sizeof(struct termios));
1957                 }
1958
1959                 /*
1960                  * Everything allocated ... set up the o_tty structure.
1961                  */
1962                 if (!(driver->other->flags & TTY_DRIVER_DEVPTS_MEM)) {
1963                         driver->other->ttys[idx] = o_tty;
1964                 }
1965                 if (!*o_tp_loc)
1966                         *o_tp_loc = o_tp;
1967                 if (!*o_ltp_loc)
1968                         *o_ltp_loc = o_ltp;
1969                 o_tty->termios = *o_tp_loc;
1970                 o_tty->termios_locked = *o_ltp_loc;
1971                 driver->other->refcount++;
1972                 if (driver->subtype == PTY_TYPE_MASTER)
1973                         o_tty->count++;
1974
1975                 /* Establish the links in both directions */
1976                 tty->link   = o_tty;
1977                 o_tty->link = tty;
1978         }
1979
1980         /* 
1981          * All structures have been allocated, so now we install them.
1982          * Failures after this point use release_mem to clean up, so 
1983          * there's no need to null out the local pointers.
1984          */
1985         if (!(driver->flags & TTY_DRIVER_DEVPTS_MEM)) {
1986                 driver->ttys[idx] = tty;
1987         }
1988         
1989         if (!*tp_loc)
1990                 *tp_loc = tp;
1991         if (!*ltp_loc)
1992                 *ltp_loc = ltp;
1993         tty->termios = *tp_loc;
1994         tty->termios_locked = *ltp_loc;
1995         driver->refcount++;
1996         tty->count++;
1997
1998         /* 
1999          * Structures all installed ... call the ldisc open routines.
2000          * If we fail here just call release_mem to clean up.  No need
2001          * to decrement the use counts, as release_mem doesn't care.
2002          */
2003
2004         if (tty->ldisc.open) {
2005                 retval = (tty->ldisc.open)(tty);
2006                 if (retval)
2007                         goto release_mem_out;
2008         }
2009         if (o_tty && o_tty->ldisc.open) {
2010                 retval = (o_tty->ldisc.open)(o_tty);
2011                 if (retval) {
2012                         if (tty->ldisc.close)
2013                                 (tty->ldisc.close)(tty);
2014                         goto release_mem_out;
2015                 }
2016                 tty_ldisc_enable(o_tty);
2017         }
2018         tty_ldisc_enable(tty);
2019         goto success;
2020
2021         /*
2022          * This fast open can be used if the tty is already open.
2023          * No memory is allocated, and the only failures are from
2024          * attempting to open a closing tty or attempting multiple
2025          * opens on a pty master.
2026          */
2027 fast_track:
2028         if (test_bit(TTY_CLOSING, &tty->flags)) {
2029                 retval = -EIO;
2030                 goto end_init;
2031         }
2032         if (driver->type == TTY_DRIVER_TYPE_PTY &&
2033             driver->subtype == PTY_TYPE_MASTER) {
2034                 /*
2035                  * special case for PTY masters: only one open permitted, 
2036                  * and the slave side open count is incremented as well.
2037                  */
2038                 if (tty->count) {
2039                         retval = -EIO;
2040                         goto end_init;
2041                 }
2042                 tty->link->count++;
2043         }
2044         tty->count++;
2045         tty->driver = driver; /* N.B. why do this every time?? */
2046
2047         /* FIXME */
2048         if(!test_bit(TTY_LDISC, &tty->flags))
2049                 printk(KERN_ERR "init_dev but no ldisc\n");
2050 success:
2051         *ret_tty = tty;
2052         
2053         /* All paths come through here to release the mutex */
2054 end_init:
2055         return retval;
2056
2057         /* Release locally allocated memory ... nothing placed in slots */
2058 free_mem_out:
2059         kfree(o_tp);
2060         if (o_tty)
2061                 free_tty_struct(o_tty);
2062         kfree(ltp);
2063         kfree(tp);
2064         free_tty_struct(tty);
2065
2066 fail_no_mem:
2067         module_put(driver->owner);
2068         retval = -ENOMEM;
2069         goto end_init;
2070
2071         /* call the tty release_mem routine to clean out this slot */
2072 release_mem_out:
2073         printk(KERN_INFO "init_dev: ldisc open failed, "
2074                          "clearing slot %d\n", idx);
2075         release_mem(tty, idx);
2076         goto end_init;
2077 }
2078
2079 /**
2080  *      release_mem             -       release tty structure memory
2081  *
2082  *      Releases memory associated with a tty structure, and clears out the
2083  *      driver table slots. This function is called when a device is no longer
2084  *      in use. It also gets called when setup of a device fails.
2085  *
2086  *      Locking:
2087  *              tty_mutex - sometimes only
2088  *              takes the file list lock internally when working on the list
2089  *      of ttys that the driver keeps.
2090  *              FIXME: should we require tty_mutex is held here ??
2091  */
2092
2093 static void release_mem(struct tty_struct *tty, int idx)
2094 {
2095         struct tty_struct *o_tty;
2096         struct termios *tp;
2097         int devpts = tty->driver->flags & TTY_DRIVER_DEVPTS_MEM;
2098
2099         if ((o_tty = tty->link) != NULL) {
2100                 if (!devpts)
2101                         o_tty->driver->ttys[idx] = NULL;
2102                 if (o_tty->driver->flags & TTY_DRIVER_RESET_TERMIOS) {
2103                         tp = o_tty->termios;
2104                         if (!devpts)
2105                                 o_tty->driver->termios[idx] = NULL;
2106                         kfree(tp);
2107
2108                         tp = o_tty->termios_locked;
2109                         if (!devpts)
2110                                 o_tty->driver->termios_locked[idx] = NULL;
2111                         kfree(tp);
2112                 }
2113                 o_tty->magic = 0;
2114                 o_tty->driver->refcount--;
2115                 file_list_lock();
2116                 list_del_init(&o_tty->tty_files);
2117                 file_list_unlock();
2118                 free_tty_struct(o_tty);
2119         }
2120
2121         if (!devpts)
2122                 tty->driver->ttys[idx] = NULL;
2123         if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS) {
2124                 tp = tty->termios;
2125                 if (!devpts)
2126                         tty->driver->termios[idx] = NULL;
2127                 kfree(tp);
2128
2129                 tp = tty->termios_locked;
2130                 if (!devpts)
2131                         tty->driver->termios_locked[idx] = NULL;
2132                 kfree(tp);
2133         }
2134
2135         tty->magic = 0;
2136         tty->driver->refcount--;
2137         file_list_lock();
2138         list_del_init(&tty->tty_files);
2139         file_list_unlock();
2140         module_put(tty->driver->owner);
2141         free_tty_struct(tty);
2142 }
2143
2144 /*
2145  * Even releasing the tty structures is a tricky business.. We have
2146  * to be very careful that the structures are all released at the
2147  * same time, as interrupts might otherwise get the wrong pointers.
2148  *
2149  * WSH 09/09/97: rewritten to avoid some nasty race conditions that could
2150  * lead to double frees or releasing memory still in use.
2151  */
2152 static void release_dev(struct file * filp)
2153 {
2154         struct tty_struct *tty, *o_tty;
2155         int     pty_master, tty_closing, o_tty_closing, do_sleep;
2156         int     devpts;
2157         int     idx;
2158         char    buf[64];
2159         unsigned long flags;
2160         
2161         tty = (struct tty_struct *)filp->private_data;
2162         if (tty_paranoia_check(tty, filp->f_dentry->d_inode, "release_dev"))
2163                 return;
2164
2165         check_tty_count(tty, "release_dev");
2166
2167         tty_fasync(-1, filp, 0);
2168
2169         idx = tty->index;
2170         pty_master = (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
2171                       tty->driver->subtype == PTY_TYPE_MASTER);
2172         devpts = (tty->driver->flags & TTY_DRIVER_DEVPTS_MEM) != 0;
2173         o_tty = tty->link;
2174
2175 #ifdef TTY_PARANOIA_CHECK
2176         if (idx < 0 || idx >= tty->driver->num) {
2177                 printk(KERN_DEBUG "release_dev: bad idx when trying to "
2178                                   "free (%s)\n", tty->name);
2179                 return;
2180         }
2181         if (!(tty->driver->flags & TTY_DRIVER_DEVPTS_MEM)) {
2182                 if (tty != tty->driver->ttys[idx]) {
2183                         printk(KERN_DEBUG "release_dev: driver.table[%d] not tty "
2184                                "for (%s)\n", idx, tty->name);
2185                         return;
2186                 }
2187                 if (tty->termios != tty->driver->termios[idx]) {
2188                         printk(KERN_DEBUG "release_dev: driver.termios[%d] not termios "
2189                                "for (%s)\n",
2190                                idx, tty->name);
2191                         return;
2192                 }
2193                 if (tty->termios_locked != tty->driver->termios_locked[idx]) {
2194                         printk(KERN_DEBUG "release_dev: driver.termios_locked[%d] not "
2195                                "termios_locked for (%s)\n",
2196                                idx, tty->name);
2197                         return;
2198                 }
2199         }
2200 #endif
2201
2202 #ifdef TTY_DEBUG_HANGUP
2203         printk(KERN_DEBUG "release_dev of %s (tty count=%d)...",
2204                tty_name(tty, buf), tty->count);
2205 #endif
2206
2207 #ifdef TTY_PARANOIA_CHECK
2208         if (tty->driver->other &&
2209              !(tty->driver->flags & TTY_DRIVER_DEVPTS_MEM)) {
2210                 if (o_tty != tty->driver->other->ttys[idx]) {
2211                         printk(KERN_DEBUG "release_dev: other->table[%d] "
2212                                           "not o_tty for (%s)\n",
2213                                idx, tty->name);
2214                         return;
2215                 }
2216                 if (o_tty->termios != tty->driver->other->termios[idx]) {
2217                         printk(KERN_DEBUG "release_dev: other->termios[%d] "
2218                                           "not o_termios for (%s)\n",
2219                                idx, tty->name);
2220                         return;
2221                 }
2222                 if (o_tty->termios_locked != 
2223                       tty->driver->other->termios_locked[idx]) {
2224                         printk(KERN_DEBUG "release_dev: other->termios_locked["
2225                                           "%d] not o_termios_locked for (%s)\n",
2226                                idx, tty->name);
2227                         return;
2228                 }
2229                 if (o_tty->link != tty) {
2230                         printk(KERN_DEBUG "release_dev: bad pty pointers\n");
2231                         return;
2232                 }
2233         }
2234 #endif
2235         if (tty->driver->close)
2236                 tty->driver->close(tty, filp);
2237
2238         /*
2239          * Sanity check: if tty->count is going to zero, there shouldn't be
2240          * any waiters on tty->read_wait or tty->write_wait.  We test the
2241          * wait queues and kick everyone out _before_ actually starting to
2242          * close.  This ensures that we won't block while releasing the tty
2243          * structure.
2244          *
2245          * The test for the o_tty closing is necessary, since the master and
2246          * slave sides may close in any order.  If the slave side closes out
2247          * first, its count will be one, since the master side holds an open.
2248          * Thus this test wouldn't be triggered at the time the slave closes,
2249          * so we do it now.
2250          *
2251          * Note that it's possible for the tty to be opened again while we're
2252          * flushing out waiters.  By recalculating the closing flags before
2253          * each iteration we avoid any problems.
2254          */
2255         while (1) {
2256                 /* Guard against races with tty->count changes elsewhere and
2257                    opens on /dev/tty */
2258                    
2259                 mutex_lock(&tty_mutex);
2260                 tty_closing = tty->count <= 1;
2261                 o_tty_closing = o_tty &&
2262                         (o_tty->count <= (pty_master ? 1 : 0));
2263                 do_sleep = 0;
2264
2265                 if (tty_closing) {
2266                         if (waitqueue_active(&tty->read_wait)) {
2267                                 wake_up(&tty->read_wait);
2268                                 do_sleep++;
2269                         }
2270                         if (waitqueue_active(&tty->write_wait)) {
2271                                 wake_up(&tty->write_wait);
2272                                 do_sleep++;
2273                         }
2274                 }
2275                 if (o_tty_closing) {
2276                         if (waitqueue_active(&o_tty->read_wait)) {
2277                                 wake_up(&o_tty->read_wait);
2278                                 do_sleep++;
2279                         }
2280                         if (waitqueue_active(&o_tty->write_wait)) {
2281                                 wake_up(&o_tty->write_wait);
2282                                 do_sleep++;
2283                         }
2284                 }
2285                 if (!do_sleep)
2286                         break;
2287
2288                 printk(KERN_WARNING "release_dev: %s: read/write wait queue "
2289                                     "active!\n", tty_name(tty, buf));
2290                 mutex_unlock(&tty_mutex);
2291                 schedule();
2292         }       
2293
2294         /*
2295          * The closing flags are now consistent with the open counts on 
2296          * both sides, and we've completed the last operation that could 
2297          * block, so it's safe to proceed with closing.
2298          */
2299         if (pty_master) {
2300                 if (--o_tty->count < 0) {
2301                         printk(KERN_WARNING "release_dev: bad pty slave count "
2302                                             "(%d) for %s\n",
2303                                o_tty->count, tty_name(o_tty, buf));
2304                         o_tty->count = 0;
2305                 }
2306         }
2307         if (--tty->count < 0) {
2308                 printk(KERN_WARNING "release_dev: bad tty->count (%d) for %s\n",
2309                        tty->count, tty_name(tty, buf));
2310                 tty->count = 0;
2311         }
2312         
2313         /*
2314          * We've decremented tty->count, so we need to remove this file
2315          * descriptor off the tty->tty_files list; this serves two
2316          * purposes:
2317          *  - check_tty_count sees the correct number of file descriptors
2318          *    associated with this tty.
2319          *  - do_tty_hangup no longer sees this file descriptor as
2320          *    something that needs to be handled for hangups.
2321          */
2322         file_kill(filp);
2323         filp->private_data = NULL;
2324
2325         /*
2326          * Perform some housekeeping before deciding whether to return.
2327          *
2328          * Set the TTY_CLOSING flag if this was the last open.  In the
2329          * case of a pty we may have to wait around for the other side
2330          * to close, and TTY_CLOSING makes sure we can't be reopened.
2331          */
2332         if(tty_closing)
2333                 set_bit(TTY_CLOSING, &tty->flags);
2334         if(o_tty_closing)
2335                 set_bit(TTY_CLOSING, &o_tty->flags);
2336
2337         /*
2338          * If _either_ side is closing, make sure there aren't any
2339          * processes that still think tty or o_tty is their controlling
2340          * tty.
2341          */
2342         if (tty_closing || o_tty_closing) {
2343                 struct task_struct *p;
2344
2345                 read_lock(&tasklist_lock);
2346                 do_each_task_pid(tty->session, PIDTYPE_SID, p) {
2347                         p->signal->tty = NULL;
2348                 } while_each_task_pid(tty->session, PIDTYPE_SID, p);
2349                 if (o_tty)
2350                         do_each_task_pid(o_tty->session, PIDTYPE_SID, p) {
2351                                 p->signal->tty = NULL;
2352                         } while_each_task_pid(o_tty->session, PIDTYPE_SID, p);
2353                 read_unlock(&tasklist_lock);
2354         }
2355
2356         mutex_unlock(&tty_mutex);
2357
2358         /* check whether both sides are closing ... */
2359         if (!tty_closing || (o_tty && !o_tty_closing))
2360                 return;
2361         
2362 #ifdef TTY_DEBUG_HANGUP
2363         printk(KERN_DEBUG "freeing tty structure...");
2364 #endif
2365         /*
2366          * Prevent flush_to_ldisc() from rescheduling the work for later.  Then
2367          * kill any delayed work. As this is the final close it does not
2368          * race with the set_ldisc code path.
2369          */
2370         clear_bit(TTY_LDISC, &tty->flags);
2371         cancel_delayed_work(&tty->buf.work);
2372
2373         /*
2374          * Wait for ->hangup_work and ->buf.work handlers to terminate
2375          */
2376          
2377         flush_scheduled_work();
2378         
2379         /*
2380          * Wait for any short term users (we know they are just driver
2381          * side waiters as the file is closing so user count on the file
2382          * side is zero.
2383          */
2384         spin_lock_irqsave(&tty_ldisc_lock, flags);
2385         while(tty->ldisc.refcount)
2386         {
2387                 spin_unlock_irqrestore(&tty_ldisc_lock, flags);
2388                 wait_event(tty_ldisc_wait, tty->ldisc.refcount == 0);
2389                 spin_lock_irqsave(&tty_ldisc_lock, flags);
2390         }
2391         spin_unlock_irqrestore(&tty_ldisc_lock, flags);
2392         /*
2393          * Shutdown the current line discipline, and reset it to N_TTY.
2394          * N.B. why reset ldisc when we're releasing the memory??
2395          *
2396          * FIXME: this MUST get fixed for the new reflocking
2397          */
2398         if (tty->ldisc.close)
2399                 (tty->ldisc.close)(tty);
2400         tty_ldisc_put(tty->ldisc.num);
2401         
2402         /*
2403          *      Switch the line discipline back
2404          */
2405         tty_ldisc_assign(tty, tty_ldisc_get(N_TTY));
2406         tty_set_termios_ldisc(tty,N_TTY); 
2407         if (o_tty) {
2408                 /* FIXME: could o_tty be in setldisc here ? */
2409                 clear_bit(TTY_LDISC, &o_tty->flags);
2410                 if (o_tty->ldisc.close)
2411                         (o_tty->ldisc.close)(o_tty);
2412                 tty_ldisc_put(o_tty->ldisc.num);
2413                 tty_ldisc_assign(o_tty, tty_ldisc_get(N_TTY));
2414                 tty_set_termios_ldisc(o_tty,N_TTY); 
2415         }
2416         /*
2417          * The release_mem function takes care of the details of clearing
2418          * the slots and preserving the termios structure.
2419          */
2420         release_mem(tty, idx);
2421
2422 #ifdef CONFIG_UNIX98_PTYS
2423         /* Make this pty number available for reallocation */
2424         if (devpts) {
2425                 down(&allocated_ptys_lock);
2426                 idr_remove(&allocated_ptys, idx);
2427                 up(&allocated_ptys_lock);
2428         }
2429 #endif
2430
2431 }
2432
2433 /**
2434  *      tty_open                -       open a tty device
2435  *      @inode: inode of device file
2436  *      @filp: file pointer to tty
2437  *
2438  *      tty_open and tty_release keep up the tty count that contains the
2439  *      number of opens done on a tty. We cannot use the inode-count, as
2440  *      different inodes might point to the same tty.
2441  *
2442  *      Open-counting is needed for pty masters, as well as for keeping
2443  *      track of serial lines: DTR is dropped when the last close happens.
2444  *      (This is not done solely through tty->count, now.  - Ted 1/27/92)
2445  *
2446  *      The termios state of a pty is reset on first open so that
2447  *      settings don't persist across reuse.
2448  *
2449  *      Locking: tty_mutex protects current->signal->tty, get_tty_driver and
2450  *              init_dev work. tty->count should protect the rest.
2451  *              task_lock is held to update task details for sessions
2452  */
2453
2454 static int tty_open(struct inode * inode, struct file * filp)
2455 {
2456         struct tty_struct *tty;
2457         int noctty, retval;
2458         struct tty_driver *driver;
2459         int index;
2460         dev_t device = inode->i_rdev;
2461         unsigned short saved_flags = filp->f_flags;
2462
2463         nonseekable_open(inode, filp);
2464         
2465 retry_open:
2466         noctty = filp->f_flags & O_NOCTTY;
2467         index  = -1;
2468         retval = 0;
2469         
2470         mutex_lock(&tty_mutex);
2471
2472         if (device == MKDEV(TTYAUX_MAJOR,0)) {
2473                 if (!current->signal->tty) {
2474                         mutex_unlock(&tty_mutex);
2475                         return -ENXIO;
2476                 }
2477                 driver = current->signal->tty->driver;
2478                 index = current->signal->tty->index;
2479                 filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
2480                 /* noctty = 1; */
2481                 goto got_driver;
2482         }
2483 #ifdef CONFIG_VT
2484         if (device == MKDEV(TTY_MAJOR,0)) {
2485                 extern struct tty_driver *console_driver;
2486                 driver = console_driver;
2487                 index = fg_console;
2488                 noctty = 1;
2489                 goto got_driver;
2490         }
2491 #endif
2492         if (device == MKDEV(TTYAUX_MAJOR,1)) {
2493                 driver = console_device(&index);
2494                 if (driver) {
2495                         /* Don't let /dev/console block */
2496                         filp->f_flags |= O_NONBLOCK;
2497                         noctty = 1;
2498                         goto got_driver;
2499                 }
2500                 mutex_unlock(&tty_mutex);
2501                 return -ENODEV;
2502         }
2503
2504         driver = get_tty_driver(device, &index);
2505         if (!driver) {
2506                 mutex_unlock(&tty_mutex);
2507                 return -ENODEV;
2508         }
2509 got_driver:
2510         retval = init_dev(driver, index, &tty);
2511         mutex_unlock(&tty_mutex);
2512         if (retval)
2513                 return retval;
2514
2515         filp->private_data = tty;
2516         file_move(filp, &tty->tty_files);
2517         check_tty_count(tty, "tty_open");
2518         if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
2519             tty->driver->subtype == PTY_TYPE_MASTER)
2520                 noctty = 1;
2521 #ifdef TTY_DEBUG_HANGUP
2522         printk(KERN_DEBUG "opening %s...", tty->name);
2523 #endif
2524         if (!retval) {
2525                 if (tty->driver->open)
2526                         retval = tty->driver->open(tty, filp);
2527                 else
2528                         retval = -ENODEV;
2529         }
2530         filp->f_flags = saved_flags;
2531
2532         if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) && !capable(CAP_SYS_ADMIN))
2533                 retval = -EBUSY;
2534
2535         if (retval) {
2536 #ifdef TTY_DEBUG_HANGUP
2537                 printk(KERN_DEBUG "error %d in opening %s...", retval,
2538                        tty->name);
2539 #endif
2540                 release_dev(filp);
2541                 if (retval != -ERESTARTSYS)
2542                         return retval;
2543                 if (signal_pending(current))
2544                         return retval;
2545                 schedule();
2546                 /*
2547                  * Need to reset f_op in case a hangup happened.
2548                  */
2549                 if (filp->f_op == &hung_up_tty_fops)
2550                         filp->f_op = &tty_fops;
2551                 goto retry_open;
2552         }
2553         if (!noctty &&
2554             current->signal->leader &&
2555             !current->signal->tty &&
2556             tty->session == 0) {
2557                 task_lock(current);
2558                 current->signal->tty = tty;
2559                 task_unlock(current);
2560                 current->signal->tty_old_pgrp = 0;
2561                 tty->session = current->signal->session;
2562                 tty->pgrp = process_group(current);
2563         }
2564         return 0;
2565 }
2566
2567 #ifdef CONFIG_UNIX98_PTYS
2568 /**
2569  *      ptmx_open               -       open a unix 98 pty master
2570  *      @inode: inode of device file
2571  *      @filp: file pointer to tty
2572  *
2573  *      Allocate a unix98 pty master device from the ptmx driver.
2574  *
2575  *      Locking: tty_mutex protects theinit_dev work. tty->count should
2576                 protect the rest.
2577  *              allocated_ptys_lock handles the list of free pty numbers
2578  */
2579
2580 static int ptmx_open(struct inode * inode, struct file * filp)
2581 {
2582         struct tty_struct *tty;
2583         int retval;
2584         int index;
2585         int idr_ret;
2586
2587         nonseekable_open(inode, filp);
2588
2589         /* find a device that is not in use. */
2590         down(&allocated_ptys_lock);
2591         if (!idr_pre_get(&allocated_ptys, GFP_KERNEL)) {
2592                 up(&allocated_ptys_lock);
2593                 return -ENOMEM;
2594         }
2595         idr_ret = idr_get_new(&allocated_ptys, NULL, &index);
2596         if (idr_ret < 0) {
2597                 up(&allocated_ptys_lock);
2598                 if (idr_ret == -EAGAIN)
2599                         return -ENOMEM;
2600                 return -EIO;
2601         }
2602         if (index >= pty_limit) {
2603                 idr_remove(&allocated_ptys, index);
2604                 up(&allocated_ptys_lock);
2605                 return -EIO;
2606         }
2607         up(&allocated_ptys_lock);
2608
2609         mutex_lock(&tty_mutex);
2610         retval = init_dev(ptm_driver, index, &tty);
2611         mutex_unlock(&tty_mutex);
2612         
2613         if (retval)
2614                 goto out;
2615
2616         set_bit(TTY_PTY_LOCK, &tty->flags); /* LOCK THE SLAVE */
2617         filp->private_data = tty;
2618         file_move(filp, &tty->tty_files);
2619
2620         retval = -ENOMEM;
2621         if (devpts_pty_new(tty->link))
2622                 goto out1;
2623
2624         check_tty_count(tty, "tty_open");
2625         retval = ptm_driver->open(tty, filp);
2626         if (!retval)
2627                 return 0;
2628 out1:
2629         release_dev(filp);
2630         return retval;
2631 out:
2632         down(&allocated_ptys_lock);
2633         idr_remove(&allocated_ptys, index);
2634         up(&allocated_ptys_lock);
2635         return retval;
2636 }
2637 #endif
2638
2639 /**
2640  *      tty_release             -       vfs callback for close
2641  *      @inode: inode of tty
2642  *      @filp: file pointer for handle to tty
2643  *
2644  *      Called the last time each file handle is closed that references
2645  *      this tty. There may however be several such references.
2646  *
2647  *      Locking:
2648  *              Takes bkl. See release_dev
2649  */
2650
2651 static int tty_release(struct inode * inode, struct file * filp)
2652 {
2653         lock_kernel();
2654         release_dev(filp);
2655         unlock_kernel();
2656         return 0;
2657 }
2658
2659 /**
2660  *      tty_poll        -       check tty status
2661  *      @filp: file being polled
2662  *      @wait: poll wait structures to update
2663  *
2664  *      Call the line discipline polling method to obtain the poll
2665  *      status of the device.
2666  *
2667  *      Locking: locks called line discipline but ldisc poll method
2668  *      may be re-entered freely by other callers.
2669  */
2670
2671 static unsigned int tty_poll(struct file * filp, poll_table * wait)
2672 {
2673         struct tty_struct * tty;
2674         struct tty_ldisc *ld;
2675         int ret = 0;
2676
2677         tty = (struct tty_struct *)filp->private_data;
2678         if (tty_paranoia_check(tty, filp->f_dentry->d_inode, "tty_poll"))
2679                 return 0;
2680                 
2681         ld = tty_ldisc_ref_wait(tty);
2682         if (ld->poll)
2683                 ret = (ld->poll)(tty, filp, wait);
2684         tty_ldisc_deref(ld);
2685         return ret;
2686 }
2687
2688 static int tty_fasync(int fd, struct file * filp, int on)
2689 {
2690         struct tty_struct * tty;
2691         int retval;
2692
2693         tty = (struct tty_struct *)filp->private_data;
2694         if (tty_paranoia_check(tty, filp->f_dentry->d_inode, "tty_fasync"))
2695                 return 0;
2696         
2697         retval = fasync_helper(fd, filp, on, &tty->fasync);
2698         if (retval <= 0)
2699                 return retval;
2700
2701         if (on) {
2702                 if (!waitqueue_active(&tty->read_wait))
2703                         tty->minimum_to_wake = 1;
2704                 retval = f_setown(filp, (-tty->pgrp) ? : current->pid, 0);
2705                 if (retval)
2706                         return retval;
2707         } else {
2708                 if (!tty->fasync && !waitqueue_active(&tty->read_wait))
2709                         tty->minimum_to_wake = N_TTY_BUF_SIZE;
2710         }
2711         return 0;
2712 }
2713
2714 /**
2715  *      tiocsti                 -       fake input character
2716  *      @tty: tty to fake input into
2717  *      @p: pointer to character
2718  *
2719  *      Fake input to a tty device. Does the neccessary locking and
2720  *      input management.
2721  *
2722  *      FIXME: does not honour flow control ??
2723  *
2724  *      Locking:
2725  *              Called functions take tty_ldisc_lock
2726  *              current->signal->tty check is safe without locks
2727  */
2728
2729 static int tiocsti(struct tty_struct *tty, char __user *p)
2730 {
2731         char ch, mbz = 0;
2732         struct tty_ldisc *ld;
2733         
2734         if ((current->signal->tty != tty) && !capable(CAP_SYS_ADMIN))
2735                 return -EPERM;
2736         if (get_user(ch, p))
2737                 return -EFAULT;
2738         ld = tty_ldisc_ref_wait(tty);
2739         ld->receive_buf(tty, &ch, &mbz, 1);
2740         tty_ldisc_deref(ld);
2741         return 0;
2742 }
2743
2744 /**
2745  *      tiocgwinsz              -       implement window query ioctl
2746  *      @tty; tty
2747  *      @arg: user buffer for result
2748  *
2749  *      Copies the kernel idea of the window size into the user buffer. No
2750  *      locking is done.
2751  *
2752  *      FIXME: Returning random values racing a window size set is wrong
2753  *      should lock here against that
2754  */
2755
2756 static int tiocgwinsz(struct tty_struct *tty, struct winsize __user * arg)
2757 {
2758         if (copy_to_user(arg, &tty->winsize, sizeof(*arg)))
2759                 return -EFAULT;
2760         return 0;
2761 }
2762
2763 /**
2764  *      tiocswinsz              -       implement window size set ioctl
2765  *      @tty; tty
2766  *      @arg: user buffer for result
2767  *
2768  *      Copies the user idea of the window size to the kernel. Traditionally
2769  *      this is just advisory information but for the Linux console it
2770  *      actually has driver level meaning and triggers a VC resize.
2771  *
2772  *      Locking:
2773  *              Called function use the console_sem is used to ensure we do
2774  *      not try and resize the console twice at once.
2775  *              The tty->termios_sem is used to ensure we don't double
2776  *      resize and get confused. Lock order - tty->termios.sem before
2777  *      console sem
2778  */
2779
2780 static int tiocswinsz(struct tty_struct *tty, struct tty_struct *real_tty,
2781         struct winsize __user * arg)
2782 {
2783         struct winsize tmp_ws;
2784
2785         if (copy_from_user(&tmp_ws, arg, sizeof(*arg)))
2786                 return -EFAULT;
2787
2788         down(&tty->termios_sem);
2789         if (!memcmp(&tmp_ws, &tty->winsize, sizeof(*arg)))
2790                 goto done;
2791
2792 #ifdef CONFIG_VT
2793         if (tty->driver->type == TTY_DRIVER_TYPE_CONSOLE) {
2794                 if (vc_lock_resize(tty->driver_data, tmp_ws.ws_col, tmp_ws.ws_row)) {
2795                         up(&tty->termios_sem);
2796                         return -ENXIO;
2797                 }
2798         }
2799 #endif
2800         if (tty->pgrp > 0)
2801                 kill_pg(tty->pgrp, SIGWINCH, 1);
2802         if ((real_tty->pgrp != tty->pgrp) && (real_tty->pgrp > 0))
2803                 kill_pg(real_tty->pgrp, SIGWINCH, 1);
2804         tty->winsize = tmp_ws;
2805         real_tty->winsize = tmp_ws;
2806 done:
2807         up(&tty->termios_sem);
2808         return 0;
2809 }
2810
2811 /**
2812  *      tioccons        -       allow admin to move logical console
2813  *      @file: the file to become console
2814  *
2815  *      Allow the adminstrator to move the redirected console device
2816  *
2817  *      Locking: uses redirect_lock to guard the redirect information
2818  */
2819
2820 static int tioccons(struct file *file)
2821 {
2822         if (!capable(CAP_SYS_ADMIN))
2823                 return -EPERM;
2824         if (file->f_op->write == redirected_tty_write) {
2825                 struct file *f;
2826                 spin_lock(&redirect_lock);
2827                 f = redirect;
2828                 redirect = NULL;
2829                 spin_unlock(&redirect_lock);
2830                 if (f)
2831                         fput(f);
2832                 return 0;
2833         }
2834         spin_lock(&redirect_lock);
2835         if (redirect) {
2836                 spin_unlock(&redirect_lock);
2837                 return -EBUSY;
2838         }
2839         get_file(file);
2840         redirect = file;
2841         spin_unlock(&redirect_lock);
2842         return 0;
2843 }
2844
2845 /**
2846  *      fionbio         -       non blocking ioctl
2847  *      @file: file to set blocking value
2848  *      @p: user parameter
2849  *
2850  *      Historical tty interfaces had a blocking control ioctl before
2851  *      the generic functionality existed. This piece of history is preserved
2852  *      in the expected tty API of posix OS's.
2853  *
2854  *      Locking: none, the open fle handle ensures it won't go away.
2855  */
2856
2857 static int fionbio(struct file *file, int __user *p)
2858 {
2859         int nonblock;
2860
2861         if (get_user(nonblock, p))
2862                 return -EFAULT;
2863
2864         if (nonblock)
2865                 file->f_flags |= O_NONBLOCK;
2866         else
2867                 file->f_flags &= ~O_NONBLOCK;
2868         return 0;
2869 }
2870
2871 /**
2872  *      tiocsctty       -       set controlling tty
2873  *      @tty: tty structure
2874  *      @arg: user argument
2875  *
2876  *      This ioctl is used to manage job control. It permits a session
2877  *      leader to set this tty as the controlling tty for the session.
2878  *
2879  *      Locking:
2880  *              Takes tasklist lock internally to walk sessions
2881  *              Takes task_lock() when updating signal->tty
2882  *
2883  *      FIXME: tty_mutex is needed to protect signal->tty references.
2884  *      FIXME: why task_lock on the signal->tty reference ??
2885  *
2886  */
2887
2888 static int tiocsctty(struct tty_struct *tty, int arg)
2889 {
2890         struct task_struct *p;
2891
2892         if (current->signal->leader &&
2893             (current->signal->session == tty->session))
2894                 return 0;
2895         /*
2896          * The process must be a session leader and
2897          * not have a controlling tty already.
2898          */
2899         if (!current->signal->leader || current->signal->tty)
2900                 return -EPERM;
2901         if (tty->session > 0) {
2902                 /*
2903                  * This tty is already the controlling
2904                  * tty for another session group!
2905                  */
2906                 if ((arg == 1) && capable(CAP_SYS_ADMIN)) {
2907                         /*
2908                          * Steal it away
2909                          */
2910
2911                         read_lock(&tasklist_lock);
2912                         do_each_task_pid(tty->session, PIDTYPE_SID, p) {
2913                                 p->signal->tty = NULL;
2914                         } while_each_task_pid(tty->session, PIDTYPE_SID, p);
2915                         read_unlock(&tasklist_lock);
2916                 } else
2917                         return -EPERM;
2918         }
2919         task_lock(current);
2920         current->signal->tty = tty;
2921         task_unlock(current);
2922         current->signal->tty_old_pgrp = 0;
2923         tty->session = current->signal->session;
2924         tty->pgrp = process_group(current);
2925         return 0;
2926 }
2927
2928 /**
2929  *      tiocgpgrp               -       get process group
2930  *      @tty: tty passed by user
2931  *      @real_tty: tty side of the tty pased by the user if a pty else the tty
2932  *      @p: returned pid
2933  *
2934  *      Obtain the process group of the tty. If there is no process group
2935  *      return an error.
2936  *
2937  *      Locking: none. Reference to ->signal->tty is safe.
2938  */
2939
2940 static int tiocgpgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
2941 {
2942         /*
2943          * (tty == real_tty) is a cheap way of
2944          * testing if the tty is NOT a master pty.
2945          */
2946         if (tty == real_tty && current->signal->tty != real_tty)
2947                 return -ENOTTY;
2948         return put_user(real_tty->pgrp, p);
2949 }
2950
2951 /**
2952  *      tiocspgrp               -       attempt to set process group
2953  *      @tty: tty passed by user
2954  *      @real_tty: tty side device matching tty passed by user
2955  *      @p: pid pointer
2956  *
2957  *      Set the process group of the tty to the session passed. Only
2958  *      permitted where the tty session is our session.
2959  *
2960  *      Locking: None
2961  *
2962  *      FIXME: current->signal->tty referencing is unsafe.
2963  */
2964
2965 static int tiocspgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
2966 {
2967         pid_t pgrp;
2968         int retval = tty_check_change(real_tty);
2969
2970         if (retval == -EIO)
2971                 return -ENOTTY;
2972         if (retval)
2973                 return retval;
2974         if (!current->signal->tty ||
2975             (current->signal->tty != real_tty) ||
2976             (real_tty->session != current->signal->session))
2977                 return -ENOTTY;
2978         if (get_user(pgrp, p))
2979                 return -EFAULT;
2980         if (pgrp < 0)
2981                 return -EINVAL;
2982         if (session_of_pgrp(pgrp) != current->signal->session)
2983                 return -EPERM;
2984         real_tty->pgrp = pgrp;
2985         return 0;
2986 }
2987
2988 /**
2989  *      tiocgsid                -       get session id
2990  *      @tty: tty passed by user
2991  *      @real_tty: tty side of the tty pased by the user if a pty else the tty
2992  *      @p: pointer to returned session id
2993  *
2994  *      Obtain the session id of the tty. If there is no session
2995  *      return an error.
2996  *
2997  *      Locking: none. Reference to ->signal->tty is safe.
2998  */
2999
3000 static int tiocgsid(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
3001 {
3002         /*
3003          * (tty == real_tty) is a cheap way of
3004          * testing if the tty is NOT a master pty.
3005         */
3006         if (tty == real_tty && current->signal->tty != real_tty)
3007                 return -ENOTTY;
3008         if (real_tty->session <= 0)
3009                 return -ENOTTY;
3010         return put_user(real_tty->session, p);
3011 }
3012
3013 /**
3014  *      tiocsetd        -       set line discipline
3015  *      @tty: tty device
3016  *      @p: pointer to user data
3017  *
3018  *      Set the line discipline according to user request.
3019  *
3020  *      Locking: see tty_set_ldisc, this function is just a helper
3021  */
3022
3023 static int tiocsetd(struct tty_struct *tty, int __user *p)
3024 {
3025         int ldisc;
3026
3027         if (get_user(ldisc, p))
3028                 return -EFAULT;
3029         return tty_set_ldisc(tty, ldisc);
3030 }
3031
3032 /**
3033  *      send_break      -       performed time break
3034  *      @tty: device to break on
3035  *      @duration: timeout in mS
3036  *
3037  *      Perform a timed break on hardware that lacks its own driver level
3038  *      timed break functionality.
3039  *
3040  *      Locking:
3041  *              None
3042  *
3043  *      FIXME:
3044  *              What if two overlap
3045  */
3046
3047 static int send_break(struct tty_struct *tty, unsigned int duration)
3048 {
3049         tty->driver->break_ctl(tty, -1);
3050         if (!signal_pending(current)) {
3051                 msleep_interruptible(duration);
3052         }
3053         tty->driver->break_ctl(tty, 0);
3054         if (signal_pending(current))
3055                 return -EINTR;
3056         return 0;
3057 }
3058
3059 /**
3060  *      tiocmget                -       get modem status
3061  *      @tty: tty device
3062  *      @file: user file pointer
3063  *      @p: pointer to result
3064  *
3065  *      Obtain the modem status bits from the tty driver if the feature
3066  *      is supported. Return -EINVAL if it is not available.
3067  *
3068  *      Locking: none (up to the driver)
3069  */
3070
3071 static int tty_tiocmget(struct tty_struct *tty, struct file *file, int __user *p)
3072 {
3073         int retval = -EINVAL;
3074
3075         if (tty->driver->tiocmget) {
3076                 retval = tty->driver->tiocmget(tty, file);
3077
3078                 if (retval >= 0)
3079                         retval = put_user(retval, p);
3080         }
3081         return retval;
3082 }
3083
3084 /**
3085  *      tiocmset                -       set modem status
3086  *      @tty: tty device
3087  *      @file: user file pointer
3088  *      @cmd: command - clear bits, set bits or set all
3089  *      @p: pointer to desired bits
3090  *
3091  *      Set the modem status bits from the tty driver if the feature
3092  *      is supported. Return -EINVAL if it is not available.
3093  *
3094  *      Locking: none (up to the driver)
3095  */
3096
3097 static int tty_tiocmset(struct tty_struct *tty, struct file *file, unsigned int cmd,
3098              unsigned __user *p)
3099 {
3100         int retval = -EINVAL;
3101
3102         if (tty->driver->tiocmset) {
3103                 unsigned int set, clear, val;
3104
3105                 retval = get_user(val, p);
3106                 if (retval)
3107                         return retval;
3108
3109                 set = clear = 0;
3110                 switch (cmd) {
3111                 case TIOCMBIS:
3112                         set = val;
3113                         break;
3114                 case TIOCMBIC:
3115                         clear = val;
3116                         break;
3117                 case TIOCMSET:
3118                         set = val;
3119                         clear = ~val;
3120                         break;
3121                 }
3122
3123                 set &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
3124                 clear &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
3125
3126                 retval = tty->driver->tiocmset(tty, file, set, clear);
3127         }
3128         return retval;
3129 }
3130
3131 /*
3132  * Split this up, as gcc can choke on it otherwise..
3133  */
3134 int tty_ioctl(struct inode * inode, struct file * file,
3135               unsigned int cmd, unsigned long arg)
3136 {
3137         struct tty_struct *tty, *real_tty;
3138         void __user *p = (void __user *)arg;
3139         int retval;
3140         struct tty_ldisc *ld;
3141         
3142         tty = (struct tty_struct *)file->private_data;
3143         if (tty_paranoia_check(tty, inode, "tty_ioctl"))
3144                 return -EINVAL;
3145
3146         real_tty = tty;
3147         if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
3148             tty->driver->subtype == PTY_TYPE_MASTER)
3149                 real_tty = tty->link;
3150
3151         /*
3152          * Break handling by driver
3153          */
3154         if (!tty->driver->break_ctl) {
3155                 switch(cmd) {
3156                 case TIOCSBRK:
3157                 case TIOCCBRK:
3158                         if (tty->driver->ioctl)
3159                                 return tty->driver->ioctl(tty, file, cmd, arg);
3160                         return -EINVAL;
3161                         
3162                 /* These two ioctl's always return success; even if */
3163                 /* the driver doesn't support them. */
3164                 case TCSBRK:
3165                 case TCSBRKP:
3166                         if (!tty->driver->ioctl)
3167                                 return 0;
3168                         retval = tty->driver->ioctl(tty, file, cmd, arg);
3169                         if (retval == -ENOIOCTLCMD)
3170                                 retval = 0;
3171                         return retval;
3172                 }
3173         }
3174
3175         /*
3176          * Factor out some common prep work
3177          */
3178         switch (cmd) {
3179         case TIOCSETD:
3180         case TIOCSBRK:
3181         case TIOCCBRK:
3182         case TCSBRK:
3183         case TCSBRKP:                   
3184                 retval = tty_check_change(tty);
3185                 if (retval)
3186                         return retval;
3187                 if (cmd != TIOCCBRK) {
3188                         tty_wait_until_sent(tty, 0);
3189                         if (signal_pending(current))
3190                                 return -EINTR;
3191                 }
3192                 break;
3193         }
3194
3195         switch (cmd) {
3196                 case TIOCSTI:
3197                         return tiocsti(tty, p);
3198                 case TIOCGWINSZ:
3199                         return tiocgwinsz(tty, p);
3200                 case TIOCSWINSZ:
3201                         return tiocswinsz(tty, real_tty, p);
3202                 case TIOCCONS:
3203                         return real_tty!=tty ? -EINVAL : tioccons(file);
3204                 case FIONBIO:
3205                         return fionbio(file, p);
3206                 case TIOCEXCL:
3207                         set_bit(TTY_EXCLUSIVE, &tty->flags);
3208                         return 0;
3209                 case TIOCNXCL:
3210                         clear_bit(TTY_EXCLUSIVE, &tty->flags);
3211                         return 0;
3212                 case TIOCNOTTY:
3213                         /* FIXME: taks lock or tty_mutex ? */
3214                         if (current->signal->tty != tty)
3215                                 return -ENOTTY;
3216                         if (current->signal->leader)
3217                                 disassociate_ctty(0);
3218                         task_lock(current);
3219                         current->signal->tty = NULL;
3220                         task_unlock(current);
3221                         return 0;
3222                 case TIOCSCTTY:
3223                         return tiocsctty(tty, arg);
3224                 case TIOCGPGRP:
3225                         return tiocgpgrp(tty, real_tty, p);
3226                 case TIOCSPGRP:
3227                         return tiocspgrp(tty, real_tty, p);
3228                 case TIOCGSID:
3229                         return tiocgsid(tty, real_tty, p);
3230                 case TIOCGETD:
3231                         /* FIXME: check this is ok */
3232                         return put_user(tty->ldisc.num, (int __user *)p);
3233                 case TIOCSETD:
3234                         return tiocsetd(tty, p);
3235 #ifdef CONFIG_VT
3236                 case TIOCLINUX:
3237                         return tioclinux(tty, arg);
3238 #endif
3239                 /*
3240                  * Break handling
3241                  */
3242                 case TIOCSBRK:  /* Turn break on, unconditionally */
3243                         tty->driver->break_ctl(tty, -1);
3244                         return 0;
3245                         
3246                 case TIOCCBRK:  /* Turn break off, unconditionally */
3247                         tty->driver->break_ctl(tty, 0);
3248                         return 0;
3249                 case TCSBRK:   /* SVID version: non-zero arg --> no break */
3250                         /* non-zero arg means wait for all output data
3251                          * to be sent (performed above) but don't send break.
3252                          * This is used by the tcdrain() termios function.
3253                          */
3254                         if (!arg)
3255                                 return send_break(tty, 250);
3256                         return 0;
3257                 case TCSBRKP:   /* support for POSIX tcsendbreak() */   
3258                         return send_break(tty, arg ? arg*100 : 250);
3259
3260                 case TIOCMGET:
3261                         return tty_tiocmget(tty, file, p);
3262
3263                 case TIOCMSET:
3264                 case TIOCMBIC:
3265                 case TIOCMBIS:
3266                         return tty_tiocmset(tty, file, cmd, p);
3267         }
3268         if (tty->driver->ioctl) {
3269                 retval = (tty->driver->ioctl)(tty, file, cmd, arg);
3270                 if (retval != -ENOIOCTLCMD)
3271                         return retval;
3272         }
3273         ld = tty_ldisc_ref_wait(tty);
3274         retval = -EINVAL;
3275         if (ld->ioctl) {
3276                 retval = ld->ioctl(tty, file, cmd, arg);
3277                 if (retval == -ENOIOCTLCMD)
3278                         retval = -EINVAL;
3279         }
3280         tty_ldisc_deref(ld);
3281         return retval;
3282 }
3283
3284
3285 /*
3286  * This implements the "Secure Attention Key" ---  the idea is to
3287  * prevent trojan horses by killing all processes associated with this
3288  * tty when the user hits the "Secure Attention Key".  Required for
3289  * super-paranoid applications --- see the Orange Book for more details.
3290  * 
3291  * This code could be nicer; ideally it should send a HUP, wait a few
3292  * seconds, then send a INT, and then a KILL signal.  But you then
3293  * have to coordinate with the init process, since all processes associated
3294  * with the current tty must be dead before the new getty is allowed
3295  * to spawn.
3296  *
3297  * Now, if it would be correct ;-/ The current code has a nasty hole -
3298  * it doesn't catch files in flight. We may send the descriptor to ourselves
3299  * via AF_UNIX socket, close it and later fetch from socket. FIXME.
3300  *
3301  * Nasty bug: do_SAK is being called in interrupt context.  This can
3302  * deadlock.  We punt it up to process context.  AKPM - 16Mar2001
3303  */
3304 static void __do_SAK(void *arg)
3305 {
3306 #ifdef TTY_SOFT_SAK
3307         tty_hangup(tty);
3308 #else
3309         struct tty_struct *tty = arg;
3310         struct task_struct *g, *p;
3311         int session;
3312         int             i;
3313         struct file     *filp;
3314         struct tty_ldisc *disc;
3315         struct fdtable *fdt;
3316         
3317         if (!tty)
3318                 return;
3319         session  = tty->session;
3320         
3321         /* We don't want an ldisc switch during this */
3322         disc = tty_ldisc_ref(tty);
3323         if (disc && disc->flush_buffer)
3324                 disc->flush_buffer(tty);
3325         tty_ldisc_deref(disc);
3326
3327         if (tty->driver->flush_buffer)
3328                 tty->driver->flush_buffer(tty);
3329         
3330         read_lock(&tasklist_lock);
3331         /* Kill the entire session */
3332         do_each_task_pid(session, PIDTYPE_SID, p) {
3333                 printk(KERN_NOTICE "SAK: killed process %d"
3334                         " (%s): p->signal->session==tty->session\n",
3335                         p->pid, p->comm);
3336                 send_sig(SIGKILL, p, 1);
3337         } while_each_task_pid(session, PIDTYPE_SID, p);
3338         /* Now kill any processes that happen to have the
3339          * tty open.
3340          */
3341         do_each_thread(g, p) {
3342                 if (p->signal->tty == tty) {
3343                         printk(KERN_NOTICE "SAK: killed process %d"
3344                             " (%s): p->signal->session==tty->session\n",
3345                             p->pid, p->comm);
3346                         send_sig(SIGKILL, p, 1);
3347                         continue;
3348                 }
3349                 task_lock(p);
3350                 if (p->files) {
3351                         /*
3352                          * We don't take a ref to the file, so we must
3353                          * hold ->file_lock instead.
3354                          */
3355                         spin_lock(&p->files->file_lock);
3356                         fdt = files_fdtable(p->files);
3357                         for (i=0; i < fdt->max_fds; i++) {
3358                                 filp = fcheck_files(p->files, i);
3359                                 if (!filp)
3360                                         continue;
3361                                 if (filp->f_op->read == tty_read &&
3362                                     filp->private_data == tty) {
3363                                         printk(KERN_NOTICE "SAK: killed process %d"
3364                                             " (%s): fd#%d opened to the tty\n",
3365                                             p->pid, p->comm, i);
3366                                         force_sig(SIGKILL, p);
3367                                         break;
3368                                 }
3369                         }
3370                         spin_unlock(&p->files->file_lock);
3371                 }
3372                 task_unlock(p);
3373         } while_each_thread(g, p);
3374         read_unlock(&tasklist_lock);
3375 #endif
3376 }
3377
3378 /*
3379  * The tq handling here is a little racy - tty->SAK_work may already be queued.
3380  * Fortunately we don't need to worry, because if ->SAK_work is already queued,
3381  * the values which we write to it will be identical to the values which it
3382  * already has. --akpm
3383  */
3384 void do_SAK(struct tty_struct *tty)
3385 {
3386         if (!tty)
3387                 return;
3388         PREPARE_WORK(&tty->SAK_work, __do_SAK, tty);
3389         schedule_work(&tty->SAK_work);
3390 }
3391
3392 EXPORT_SYMBOL(do_SAK);
3393
3394 /**
3395  *      flush_to_ldisc
3396  *      @private_: tty structure passed from work queue.
3397  *
3398  *      This routine is called out of the software interrupt to flush data
3399  *      from the buffer chain to the line discipline.
3400  *
3401  *      Locking: holds tty->buf.lock to guard buffer list. Drops the lock
3402  *      while invoking the line discipline receive_buf method. The
3403  *      receive_buf method is single threaded for each tty instance.
3404  */
3405  
3406 static void flush_to_ldisc(void *private_)
3407 {
3408         struct tty_struct *tty = (struct tty_struct *) private_;
3409         unsigned long   flags;
3410         struct tty_ldisc *disc;
3411         struct tty_buffer *tbuf, *head;
3412         char *char_buf;
3413         unsigned char *flag_buf;
3414
3415         disc = tty_ldisc_ref(tty);
3416         if (disc == NULL)       /*  !TTY_LDISC */
3417                 return;
3418
3419         spin_lock_irqsave(&tty->buf.lock, flags);
3420         head = tty->buf.head;
3421         if (head != NULL) {
3422                 tty->buf.head = NULL;
3423                 for (;;) {
3424                         int count = head->commit - head->read;
3425                         if (!count) {
3426                                 if (head->next == NULL)
3427                                         break;
3428                                 tbuf = head;
3429                                 head = head->next;
3430                                 tty_buffer_free(tty, tbuf);
3431                                 continue;
3432                         }
3433                         if (!tty->receive_room) {
3434                                 schedule_delayed_work(&tty->buf.work, 1);
3435                                 break;
3436                         }
3437                         if (count > tty->receive_room)
3438                                 count = tty->receive_room;
3439                         char_buf = head->char_buf_ptr + head->read;
3440                         flag_buf = head->flag_buf_ptr + head->read;
3441                         head->read += count;
3442                         spin_unlock_irqrestore(&tty->buf.lock, flags);
3443                         disc->receive_buf(tty, char_buf, flag_buf, count);
3444                         spin_lock_irqsave(&tty->buf.lock, flags);
3445                 }
3446                 tty->buf.head = head;
3447         }
3448         spin_unlock_irqrestore(&tty->buf.lock, flags);
3449
3450         tty_ldisc_deref(disc);
3451 }
3452
3453 /*
3454  * Routine which returns the baud rate of the tty
3455  *
3456  * Note that the baud_table needs to be kept in sync with the
3457  * include/asm/termbits.h file.
3458  */
3459 static int baud_table[] = {
3460         0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
3461         9600, 19200, 38400, 57600, 115200, 230400, 460800,
3462 #ifdef __sparc__
3463         76800, 153600, 307200, 614400, 921600
3464 #else
3465         500000, 576000, 921600, 1000000, 1152000, 1500000, 2000000,
3466         2500000, 3000000, 3500000, 4000000
3467 #endif
3468 };
3469
3470 static int n_baud_table = ARRAY_SIZE(baud_table);
3471
3472 /**
3473  *      tty_termios_baud_rate
3474  *      @termios: termios structure
3475  *
3476  *      Convert termios baud rate data into a speed. This should be called
3477  *      with the termios lock held if this termios is a terminal termios
3478  *      structure. May change the termios data.
3479  *
3480  *      Locking: none
3481  */
3482  
3483 int tty_termios_baud_rate(struct termios *termios)
3484 {
3485         unsigned int cbaud;
3486         
3487         cbaud = termios->c_cflag & CBAUD;
3488
3489         if (cbaud & CBAUDEX) {
3490                 cbaud &= ~CBAUDEX;
3491
3492                 if (cbaud < 1 || cbaud + 15 > n_baud_table)
3493                         termios->c_cflag &= ~CBAUDEX;
3494                 else
3495                         cbaud += 15;
3496         }
3497         return baud_table[cbaud];
3498 }
3499
3500 EXPORT_SYMBOL(tty_termios_baud_rate);
3501
3502 /**
3503  *      tty_get_baud_rate       -       get tty bit rates
3504  *      @tty: tty to query
3505  *
3506  *      Returns the baud rate as an integer for this terminal. The
3507  *      termios lock must be held by the caller and the terminal bit
3508  *      flags may be updated.
3509  *
3510  *      Locking: none
3511  */
3512  
3513 int tty_get_baud_rate(struct tty_struct *tty)
3514 {
3515         int baud = tty_termios_baud_rate(tty->termios);
3516
3517         if (baud == 38400 && tty->alt_speed) {
3518                 if (!tty->warned) {
3519                         printk(KERN_WARNING "Use of setserial/setrocket to "
3520                                             "set SPD_* flags is deprecated\n");
3521                         tty->warned = 1;
3522                 }
3523                 baud = tty->alt_speed;
3524         }
3525         
3526         return baud;
3527 }
3528
3529 EXPORT_SYMBOL(tty_get_baud_rate);
3530
3531 /**
3532  *      tty_flip_buffer_push    -       terminal
3533  *      @tty: tty to push
3534  *
3535  *      Queue a push of the terminal flip buffers to the line discipline. This
3536  *      function must not be called from IRQ context if tty->low_latency is set.
3537  *
3538  *      In the event of the queue being busy for flipping the work will be
3539  *      held off and retried later.
3540  *
3541  *      Locking: tty buffer lock. Driver locks in low latency mode.
3542  */
3543
3544 void tty_flip_buffer_push(struct tty_struct *tty)
3545 {
3546         unsigned long flags;
3547         spin_lock_irqsave(&tty->buf.lock, flags);
3548         if (tty->buf.tail != NULL)
3549                 tty->buf.tail->commit = tty->buf.tail->used;
3550         spin_unlock_irqrestore(&tty->buf.lock, flags);
3551
3552         if (tty->low_latency)
3553                 flush_to_ldisc((void *) tty);
3554         else
3555                 schedule_delayed_work(&tty->buf.work, 1);
3556 }
3557
3558 EXPORT_SYMBOL(tty_flip_buffer_push);
3559
3560
3561 /**
3562  *      initialize_tty_struct
3563  *      @tty: tty to initialize
3564  *
3565  *      This subroutine initializes a tty structure that has been newly
3566  *      allocated.
3567  *
3568  *      Locking: none - tty in question must not be exposed at this point
3569  */
3570
3571 static void initialize_tty_struct(struct tty_struct *tty)
3572 {
3573         memset(tty, 0, sizeof(struct tty_struct));
3574         tty->magic = TTY_MAGIC;
3575         tty_ldisc_assign(tty, tty_ldisc_get(N_TTY));
3576         tty->pgrp = -1;
3577         tty->overrun_time = jiffies;
3578         tty->buf.head = tty->buf.tail = NULL;
3579         tty_buffer_init(tty);
3580         INIT_WORK(&tty->buf.work, flush_to_ldisc, tty);
3581         init_MUTEX(&tty->buf.pty_sem);
3582         init_MUTEX(&tty->termios_sem);
3583         init_waitqueue_head(&tty->write_wait);
3584         init_waitqueue_head(&tty->read_wait);
3585         INIT_WORK(&tty->hangup_work, do_tty_hangup, tty);
3586         mutex_init(&tty->atomic_read_lock);
3587         mutex_init(&tty->atomic_write_lock);
3588         spin_lock_init(&tty->read_lock);
3589         INIT_LIST_HEAD(&tty->tty_files);
3590         INIT_WORK(&tty->SAK_work, NULL, NULL);
3591 }
3592
3593 /*
3594  * The default put_char routine if the driver did not define one.
3595  */
3596
3597 static void tty_default_put_char(struct tty_struct *tty, unsigned char ch)
3598 {
3599         tty->driver->write(tty, &ch, 1);
3600 }
3601
3602 static struct class *tty_class;
3603
3604 /**
3605  *      tty_register_device - register a tty device
3606  *      @driver: the tty driver that describes the tty device
3607  *      @index: the index in the tty driver for this tty device
3608  *      @device: a struct device that is associated with this tty device.
3609  *              This field is optional, if there is no known struct device
3610  *              for this tty device it can be set to NULL safely.
3611  *
3612  *      Returns a pointer to the class device (or ERR_PTR(-EFOO) on error).
3613  *
3614  *      This call is required to be made to register an individual tty device
3615  *      if the tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set.  If
3616  *      that bit is not set, this function should not be called by a tty
3617  *      driver.
3618  *
3619  *      Locking: ??
3620  */
3621
3622 struct class_device *tty_register_device(struct tty_driver *driver,
3623                                          unsigned index, struct device *device)
3624 {
3625         char name[64];
3626         dev_t dev = MKDEV(driver->major, driver->minor_start) + index;
3627
3628         if (index >= driver->num) {
3629                 printk(KERN_ERR "Attempt to register invalid tty line number "
3630                        " (%d).\n", index);
3631                 return ERR_PTR(-EINVAL);
3632         }
3633
3634         if (driver->type == TTY_DRIVER_TYPE_PTY)
3635                 pty_line_name(driver, index, name);
3636         else
3637                 tty_line_name(driver, index, name);
3638
3639         return class_device_create(tty_class, NULL, dev, device, "%s", name);
3640 }
3641
3642 /**
3643  *      tty_unregister_device - unregister a tty device
3644  *      @driver: the tty driver that describes the tty device
3645  *      @index: the index in the tty driver for this tty device
3646  *
3647  *      If a tty device is registered with a call to tty_register_device() then
3648  *      this function must be called when the tty device is gone.
3649  *
3650  *      Locking: ??
3651  */
3652
3653 void tty_unregister_device(struct tty_driver *driver, unsigned index)
3654 {
3655         class_device_destroy(tty_class, MKDEV(driver->major, driver->minor_start) + index);
3656 }
3657
3658 EXPORT_SYMBOL(tty_register_device);
3659 EXPORT_SYMBOL(tty_unregister_device);
3660
3661 struct tty_driver *alloc_tty_driver(int lines)
3662 {
3663         struct tty_driver *driver;
3664
3665         driver = kmalloc(sizeof(struct tty_driver), GFP_KERNEL);
3666         if (driver) {
3667                 memset(driver, 0, sizeof(struct tty_driver));
3668                 driver->magic = TTY_DRIVER_MAGIC;
3669                 driver->num = lines;
3670                 /* later we'll move allocation of tables here */
3671         }
3672         return driver;
3673 }
3674
3675 void put_tty_driver(struct tty_driver *driver)
3676 {
3677         kfree(driver);
3678 }
3679
3680 void tty_set_operations(struct tty_driver *driver, struct tty_operations *op)
3681 {
3682         driver->open = op->open;
3683         driver->close = op->close;
3684         driver->write = op->write;
3685         driver->put_char = op->put_char;
3686         driver->flush_chars = op->flush_chars;
3687         driver->write_room = op->write_room;
3688         driver->chars_in_buffer = op->chars_in_buffer;
3689         driver->ioctl = op->ioctl;
3690         driver->set_termios = op->set_termios;
3691         driver->throttle = op->throttle;
3692         driver->unthrottle = op->unthrottle;
3693         driver->stop = op->stop;
3694         driver->start = op->start;
3695         driver->hangup = op->hangup;
3696         driver->break_ctl = op->break_ctl;
3697         driver->flush_buffer = op->flush_buffer;
3698         driver->set_ldisc = op->set_ldisc;
3699         driver->wait_until_sent = op->wait_until_sent;
3700         driver->send_xchar = op->send_xchar;
3701         driver->read_proc = op->read_proc;
3702         driver->write_proc = op->write_proc;
3703         driver->tiocmget = op->tiocmget;
3704         driver->tiocmset = op->tiocmset;
3705 }
3706
3707
3708 EXPORT_SYMBOL(alloc_tty_driver);
3709 EXPORT_SYMBOL(put_tty_driver);
3710 EXPORT_SYMBOL(tty_set_operations);
3711
3712 /*
3713  * Called by a tty driver to register itself.
3714  */
3715 int tty_register_driver(struct tty_driver *driver)
3716 {
3717         int error;
3718         int i;
3719         dev_t dev;
3720         void **p = NULL;
3721
3722         if (driver->flags & TTY_DRIVER_INSTALLED)
3723                 return 0;
3724
3725         if (!(driver->flags & TTY_DRIVER_DEVPTS_MEM)) {
3726                 p = kmalloc(driver->num * 3 * sizeof(void *), GFP_KERNEL);
3727                 if (!p)
3728                         return -ENOMEM;
3729                 memset(p, 0, driver->num * 3 * sizeof(void *));
3730         }
3731
3732         if (!driver->major) {
3733                 error = alloc_chrdev_region(&dev, driver->minor_start, driver->num,
3734                                                 (char*)driver->name);
3735                 if (!error) {
3736                         driver->major = MAJOR(dev);
3737                         driver->minor_start = MINOR(dev);
3738                 }
3739         } else {
3740                 dev = MKDEV(driver->major, driver->minor_start);
3741                 error = register_chrdev_region(dev, driver->num,
3742                                                 (char*)driver->name);
3743         }
3744         if (error < 0) {
3745                 kfree(p);
3746                 return error;
3747         }
3748
3749         if (p) {
3750                 driver->ttys = (struct tty_struct **)p;
3751                 driver->termios = (struct termios **)(p + driver->num);
3752                 driver->termios_locked = (struct termios **)(p + driver->num * 2);
3753         } else {
3754                 driver->ttys = NULL;
3755                 driver->termios = NULL;
3756                 driver->termios_locked = NULL;
3757         }
3758
3759         cdev_init(&driver->cdev, &tty_fops);
3760         driver->cdev.owner = driver->owner;
3761         error = cdev_add(&driver->cdev, dev, driver->num);
3762         if (error) {
3763                 unregister_chrdev_region(dev, driver->num);
3764                 driver->ttys = NULL;
3765                 driver->termios = driver->termios_locked = NULL;
3766                 kfree(p);
3767                 return error;
3768         }
3769
3770         if (!driver->put_char)
3771                 driver->put_char = tty_default_put_char;
3772         
3773         list_add(&driver->tty_drivers, &tty_drivers);
3774         
3775         if ( !(driver->flags & TTY_DRIVER_DYNAMIC_DEV) ) {
3776                 for(i = 0; i < driver->num; i++)
3777                     tty_register_device(driver, i, NULL);
3778         }
3779         proc_tty_register_driver(driver);
3780         return 0;
3781 }
3782
3783 EXPORT_SYMBOL(tty_register_driver);
3784
3785 /*
3786  * Called by a tty driver to unregister itself.
3787  */
3788 int tty_unregister_driver(struct tty_driver *driver)
3789 {
3790         int i;
3791         struct termios *tp;
3792         void *p;
3793
3794         if (driver->refcount)
3795                 return -EBUSY;
3796
3797         unregister_chrdev_region(MKDEV(driver->major, driver->minor_start),
3798                                 driver->num);
3799
3800         list_del(&driver->tty_drivers);
3801
3802         /*
3803          * Free the termios and termios_locked structures because
3804          * we don't want to get memory leaks when modular tty
3805          * drivers are removed from the kernel.
3806          */
3807         for (i = 0; i < driver->num; i++) {
3808                 tp = driver->termios[i];
3809                 if (tp) {
3810                         driver->termios[i] = NULL;
3811                         kfree(tp);
3812                 }
3813                 tp = driver->termios_locked[i];
3814                 if (tp) {
3815                         driver->termios_locked[i] = NULL;
3816                         kfree(tp);
3817                 }
3818                 if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV))
3819                         tty_unregister_device(driver, i);
3820         }
3821         p = driver->ttys;
3822         proc_tty_unregister_driver(driver);
3823         driver->ttys = NULL;
3824         driver->termios = driver->termios_locked = NULL;
3825         kfree(p);
3826         cdev_del(&driver->cdev);
3827         return 0;
3828 }
3829
3830 EXPORT_SYMBOL(tty_unregister_driver);
3831
3832
3833 /*
3834  * Initialize the console device. This is called *early*, so
3835  * we can't necessarily depend on lots of kernel help here.
3836  * Just do some early initializations, and do the complex setup
3837  * later.
3838  */
3839 void __init console_init(void)
3840 {
3841         initcall_t *call;
3842
3843         /* Setup the default TTY line discipline. */
3844         (void) tty_register_ldisc(N_TTY, &tty_ldisc_N_TTY);
3845
3846         /*
3847          * set up the console device so that later boot sequences can 
3848          * inform about problems etc..
3849          */
3850 #ifdef CONFIG_EARLY_PRINTK
3851         disable_early_printk();
3852 #endif
3853         call = __con_initcall_start;
3854         while (call < __con_initcall_end) {
3855                 (*call)();
3856                 call++;
3857         }
3858 }
3859
3860 #ifdef CONFIG_VT
3861 extern int vty_init(void);
3862 #endif
3863
3864 static int __init tty_class_init(void)
3865 {
3866         tty_class = class_create(THIS_MODULE, "tty");
3867         if (IS_ERR(tty_class))
3868                 return PTR_ERR(tty_class);
3869         return 0;
3870 }
3871
3872 postcore_initcall(tty_class_init);
3873
3874 /* 3/2004 jmc: why do these devices exist? */
3875
3876 static struct cdev tty_cdev, console_cdev;
3877 #ifdef CONFIG_UNIX98_PTYS
3878 static struct cdev ptmx_cdev;
3879 #endif
3880 #ifdef CONFIG_VT
3881 static struct cdev vc0_cdev;
3882 #endif
3883
3884 /*
3885  * Ok, now we can initialize the rest of the tty devices and can count
3886  * on memory allocations, interrupts etc..
3887  */
3888 static int __init tty_init(void)
3889 {
3890         cdev_init(&tty_cdev, &tty_fops);
3891         if (cdev_add(&tty_cdev, MKDEV(TTYAUX_MAJOR, 0), 1) ||
3892             register_chrdev_region(MKDEV(TTYAUX_MAJOR, 0), 1, "/dev/tty") < 0)
3893                 panic("Couldn't register /dev/tty driver\n");
3894         class_device_create(tty_class, NULL, MKDEV(TTYAUX_MAJOR, 0), NULL, "tty");
3895
3896         cdev_init(&console_cdev, &console_fops);
3897         if (cdev_add(&console_cdev, MKDEV(TTYAUX_MAJOR, 1), 1) ||
3898             register_chrdev_region(MKDEV(TTYAUX_MAJOR, 1), 1, "/dev/console") < 0)
3899                 panic("Couldn't register /dev/console driver\n");
3900         class_device_create(tty_class, NULL, MKDEV(TTYAUX_MAJOR, 1), NULL, "console");
3901
3902 #ifdef CONFIG_UNIX98_PTYS
3903         cdev_init(&ptmx_cdev, &ptmx_fops);
3904         if (cdev_add(&ptmx_cdev, MKDEV(TTYAUX_MAJOR, 2), 1) ||
3905             register_chrdev_region(MKDEV(TTYAUX_MAJOR, 2), 1, "/dev/ptmx") < 0)
3906                 panic("Couldn't register /dev/ptmx driver\n");
3907         class_device_create(tty_class, NULL, MKDEV(TTYAUX_MAJOR, 2), NULL, "ptmx");
3908 #endif
3909
3910 #ifdef CONFIG_VT
3911         cdev_init(&vc0_cdev, &console_fops);
3912         if (cdev_add(&vc0_cdev, MKDEV(TTY_MAJOR, 0), 1) ||
3913             register_chrdev_region(MKDEV(TTY_MAJOR, 0), 1, "/dev/vc/0") < 0)
3914                 panic("Couldn't register /dev/tty0 driver\n");
3915         class_device_create(tty_class, NULL, MKDEV(TTY_MAJOR, 0), NULL, "tty0");
3916
3917         vty_init();
3918 #endif
3919         return 0;
3920 }
3921 module_init(tty_init);