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