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