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