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