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