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