OSDN Git Service

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