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