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