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