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