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