2 * Copyright (C) 1991, 1992 Linus Torvalds
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.
9 * Kill-line thanks to John T Kohl, who also corrected VMIN = VTIME = 0.
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.
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
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).
26 * NOTE: pay no attention to the line discipline code (yet); its
27 * interface is still subject to change in this version...
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.
34 * Rewrote canonical mode and added more termios flags.
35 * -- julian@uhunix.uhcc.hawaii.edu (J. Cowley), 13Jan94
37 * Reorganized FASYNC support so mouse code can share it.
38 * -- ctm@ardi.com, 9Sep95
40 * New TIOCLINUX variants added.
41 * -- mj@k332.feld.cvut.cz, 19-Nov-95
43 * Restrict vt switching via ioctl()
44 * -- grif@cs.ucr.edu, 5-Dec-95
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
50 * Rewrote tty_init_dev and tty_release_dev to eliminate races.
51 * -- Bill Hawes <whawes@star.net>, June 97
53 * Added devfs support.
54 * -- C. Scott Ananian <cananian@alumni.princeton.edu>, 13-Jan-1998
56 * Added support for a Unix98-style ptmx device.
57 * -- C. Scott Ananian <cananian@alumni.princeton.edu>, 14-Jan-1998
59 * Reduced memory usage for older ARM systems
60 * -- Russell King <rmk@arm.linux.org.uk>
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
67 #include <linux/types.h>
68 #include <linux/major.h>
69 #include <linux/errno.h>
70 #include <linux/signal.h>
71 #include <linux/fcntl.h>
72 #include <linux/sched.h>
73 #include <linux/interrupt.h>
74 #include <linux/tty.h>
75 #include <linux/tty_driver.h>
76 #include <linux/tty_flip.h>
77 #include <linux/devpts_fs.h>
78 #include <linux/file.h>
79 #include <linux/fdtable.h>
80 #include <linux/console.h>
81 #include <linux/timer.h>
82 #include <linux/ctype.h>
85 #include <linux/string.h>
86 #include <linux/slab.h>
87 #include <linux/poll.h>
88 #include <linux/proc_fs.h>
89 #include <linux/init.h>
90 #include <linux/module.h>
91 #include <linux/device.h>
92 #include <linux/wait.h>
93 #include <linux/bitops.h>
94 #include <linux/delay.h>
95 #include <linux/seq_file.h>
96 #include <linux/serial.h>
97 #include <linux/ratelimit.h>
99 #include <linux/uaccess.h>
101 #include <linux/kbd_kern.h>
102 #include <linux/vt_kern.h>
103 #include <linux/selection.h>
105 #include <linux/kmod.h>
106 #include <linux/nsproxy.h>
108 #undef TTY_DEBUG_HANGUP
109 #ifdef TTY_DEBUG_HANGUP
110 # define tty_debug_hangup(tty, f, args...) tty_debug(tty, f, ##args)
112 # define tty_debug_hangup(tty, f, args...) do { } while (0)
115 #define TTY_PARANOIA_CHECK 1
116 #define CHECK_TTY_COUNT 1
118 struct ktermios tty_std_termios = { /* for the benefit of tty drivers */
119 .c_iflag = ICRNL | IXON,
120 .c_oflag = OPOST | ONLCR,
121 .c_cflag = B38400 | CS8 | CREAD | HUPCL,
122 .c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK |
123 ECHOCTL | ECHOKE | IEXTEN,
127 /* .c_line = N_TTY, */
130 EXPORT_SYMBOL(tty_std_termios);
132 /* This list gets poked at by procfs and various bits of boot up code. This
133 could do with some rationalisation such as pulling the tty proc function
136 LIST_HEAD(tty_drivers); /* linked list of tty drivers */
138 /* Mutex to protect creating and releasing a tty */
139 DEFINE_MUTEX(tty_mutex);
141 static ssize_t tty_read(struct file *, char __user *, size_t, loff_t *);
142 static ssize_t tty_write(struct file *, const char __user *, size_t, loff_t *);
143 ssize_t redirected_tty_write(struct file *, const char __user *,
145 static unsigned int tty_poll(struct file *, poll_table *);
146 static int tty_open(struct inode *, struct file *);
147 long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
149 static long tty_compat_ioctl(struct file *file, unsigned int cmd,
152 #define tty_compat_ioctl NULL
154 static int __tty_fasync(int fd, struct file *filp, int on);
155 static int tty_fasync(int fd, struct file *filp, int on);
156 static void release_tty(struct tty_struct *tty, int idx);
159 * free_tty_struct - free a disused tty
160 * @tty: tty struct to free
162 * Free the write buffers, tty queue and tty memory itself.
164 * Locking: none. Must be called after tty is definitely unused
167 static void free_tty_struct(struct tty_struct *tty)
169 tty_ldisc_deinit(tty);
170 put_device(tty->dev);
171 kfree(tty->write_buf);
172 tty->magic = 0xDEADDEAD;
176 static inline struct tty_struct *file_tty(struct file *file)
178 return ((struct tty_file_private *)file->private_data)->tty;
181 int tty_alloc_file(struct file *file)
183 struct tty_file_private *priv;
185 priv = kmalloc(sizeof(*priv), GFP_KERNEL);
189 file->private_data = priv;
194 /* Associate a new file with the tty structure */
195 void tty_add_file(struct tty_struct *tty, struct file *file)
197 struct tty_file_private *priv = file->private_data;
202 spin_lock(&tty->files_lock);
203 list_add(&priv->list, &tty->tty_files);
204 spin_unlock(&tty->files_lock);
208 * tty_free_file - free file->private_data
210 * This shall be used only for fail path handling when tty_add_file was not
213 void tty_free_file(struct file *file)
215 struct tty_file_private *priv = file->private_data;
217 file->private_data = NULL;
221 /* Delete file from its tty */
222 static void tty_del_file(struct file *file)
224 struct tty_file_private *priv = file->private_data;
225 struct tty_struct *tty = priv->tty;
227 spin_lock(&tty->files_lock);
228 list_del(&priv->list);
229 spin_unlock(&tty->files_lock);
234 * tty_name - return tty naming
235 * @tty: tty structure
237 * Convert a tty structure into a name. The name reflects the kernel
238 * naming policy and if udev is in use may not reflect user space
243 const char *tty_name(const struct tty_struct *tty)
245 if (!tty) /* Hmm. NULL pointer. That's fun. */
250 EXPORT_SYMBOL(tty_name);
252 const char *tty_driver_name(const struct tty_struct *tty)
254 if (!tty || !tty->driver)
256 return tty->driver->name;
259 static int tty_paranoia_check(struct tty_struct *tty, struct inode *inode,
262 #ifdef TTY_PARANOIA_CHECK
264 pr_warn("(%d:%d): %s: NULL tty\n",
265 imajor(inode), iminor(inode), routine);
268 if (tty->magic != TTY_MAGIC) {
269 pr_warn("(%d:%d): %s: bad magic number\n",
270 imajor(inode), iminor(inode), routine);
277 /* Caller must hold tty_lock */
278 static int check_tty_count(struct tty_struct *tty, const char *routine)
280 #ifdef CHECK_TTY_COUNT
284 spin_lock(&tty->files_lock);
285 list_for_each(p, &tty->tty_files) {
288 spin_unlock(&tty->files_lock);
289 if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
290 tty->driver->subtype == PTY_TYPE_SLAVE &&
291 tty->link && tty->link->count)
293 if (tty->count != count) {
294 tty_warn(tty, "%s: tty->count(%d) != #fd's(%d)\n",
295 routine, tty->count, count);
303 * get_tty_driver - find device of a tty
304 * @dev_t: device identifier
305 * @index: returns the index of the tty
307 * This routine returns a tty driver structure, given a device number
308 * and also passes back the index number.
310 * Locking: caller must hold tty_mutex
313 static struct tty_driver *get_tty_driver(dev_t device, int *index)
315 struct tty_driver *p;
317 list_for_each_entry(p, &tty_drivers, tty_drivers) {
318 dev_t base = MKDEV(p->major, p->minor_start);
319 if (device < base || device >= base + p->num)
321 *index = device - base;
322 return tty_driver_kref_get(p);
327 #ifdef CONFIG_CONSOLE_POLL
330 * tty_find_polling_driver - find device of a polled tty
331 * @name: name string to match
332 * @line: pointer to resulting tty line nr
334 * This routine returns a tty driver structure, given a name
335 * and the condition that the tty driver is capable of polled
338 struct tty_driver *tty_find_polling_driver(char *name, int *line)
340 struct tty_driver *p, *res = NULL;
345 for (str = name; *str; str++)
346 if ((*str >= '0' && *str <= '9') || *str == ',')
352 tty_line = simple_strtoul(str, &str, 10);
354 mutex_lock(&tty_mutex);
355 /* Search through the tty devices to look for a match */
356 list_for_each_entry(p, &tty_drivers, tty_drivers) {
357 if (!len || strncmp(name, p->name, len) != 0)
365 if (tty_line >= 0 && tty_line < p->num && p->ops &&
366 p->ops->poll_init && !p->ops->poll_init(p, tty_line, stp)) {
367 res = tty_driver_kref_get(p);
372 mutex_unlock(&tty_mutex);
376 EXPORT_SYMBOL_GPL(tty_find_polling_driver);
379 static int is_ignored(int sig)
381 return (sigismember(¤t->blocked, sig) ||
382 current->sighand->action[sig-1].sa.sa_handler == SIG_IGN);
386 * tty_check_change - check for POSIX terminal changes
389 * If we try to write to, or set the state of, a terminal and we're
390 * not in the foreground, send a SIGTTOU. If the signal is blocked or
391 * ignored, go ahead and perform the operation. (POSIX 7.2)
396 int __tty_check_change(struct tty_struct *tty, int sig)
399 struct pid *pgrp, *tty_pgrp;
402 if (current->signal->tty != tty)
406 pgrp = task_pgrp(current);
408 spin_lock_irqsave(&tty->ctrl_lock, flags);
409 tty_pgrp = tty->pgrp;
410 spin_unlock_irqrestore(&tty->ctrl_lock, flags);
412 if (tty_pgrp && pgrp != tty->pgrp) {
413 if (is_ignored(sig)) {
416 } else if (is_current_pgrp_orphaned())
419 kill_pgrp(pgrp, sig, 1);
420 set_thread_flag(TIF_SIGPENDING);
427 tty_warn(tty, "sig=%d, tty->pgrp == NULL!\n", sig);
432 int tty_check_change(struct tty_struct *tty)
434 return __tty_check_change(tty, SIGTTOU);
436 EXPORT_SYMBOL(tty_check_change);
438 static ssize_t hung_up_tty_read(struct file *file, char __user *buf,
439 size_t count, loff_t *ppos)
444 static ssize_t hung_up_tty_write(struct file *file, const char __user *buf,
445 size_t count, loff_t *ppos)
450 /* No kernel lock held - none needed ;) */
451 static unsigned int hung_up_tty_poll(struct file *filp, poll_table *wait)
453 return POLLIN | POLLOUT | POLLERR | POLLHUP | POLLRDNORM | POLLWRNORM;
456 static long hung_up_tty_ioctl(struct file *file, unsigned int cmd,
459 return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
462 static long hung_up_tty_compat_ioctl(struct file *file,
463 unsigned int cmd, unsigned long arg)
465 return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
468 static int hung_up_tty_fasync(int fd, struct file *file, int on)
473 static const struct file_operations tty_fops = {
478 .unlocked_ioctl = tty_ioctl,
479 .compat_ioctl = tty_compat_ioctl,
481 .release = tty_release,
482 .fasync = tty_fasync,
485 static const struct file_operations console_fops = {
488 .write = redirected_tty_write,
490 .unlocked_ioctl = tty_ioctl,
491 .compat_ioctl = tty_compat_ioctl,
493 .release = tty_release,
494 .fasync = tty_fasync,
497 static const struct file_operations hung_up_tty_fops = {
499 .read = hung_up_tty_read,
500 .write = hung_up_tty_write,
501 .poll = hung_up_tty_poll,
502 .unlocked_ioctl = hung_up_tty_ioctl,
503 .compat_ioctl = hung_up_tty_compat_ioctl,
504 .release = tty_release,
505 .fasync = hung_up_tty_fasync,
508 static DEFINE_SPINLOCK(redirect_lock);
509 static struct file *redirect;
512 void proc_clear_tty(struct task_struct *p)
515 struct tty_struct *tty;
516 spin_lock_irqsave(&p->sighand->siglock, flags);
517 tty = p->signal->tty;
518 p->signal->tty = NULL;
519 spin_unlock_irqrestore(&p->sighand->siglock, flags);
523 extern void tty_sysctl_init(void);
526 * proc_set_tty - set the controlling terminal
528 * Only callable by the session leader and only if it does not already have
529 * a controlling terminal.
531 * Caller must hold: tty_lock()
532 * a readlock on tasklist_lock
535 static void __proc_set_tty(struct tty_struct *tty)
539 spin_lock_irqsave(&tty->ctrl_lock, flags);
541 * The session and fg pgrp references will be non-NULL if
542 * tiocsctty() is stealing the controlling tty
544 put_pid(tty->session);
546 tty->pgrp = get_pid(task_pgrp(current));
547 tty->session = get_pid(task_session(current));
548 spin_unlock_irqrestore(&tty->ctrl_lock, flags);
549 if (current->signal->tty) {
550 tty_debug(tty, "current tty %s not NULL!!\n",
551 current->signal->tty->name);
552 tty_kref_put(current->signal->tty);
554 put_pid(current->signal->tty_old_pgrp);
555 current->signal->tty = tty_kref_get(tty);
556 current->signal->tty_old_pgrp = NULL;
559 static void proc_set_tty(struct tty_struct *tty)
561 spin_lock_irq(¤t->sighand->siglock);
563 spin_unlock_irq(¤t->sighand->siglock);
566 struct tty_struct *get_current_tty(void)
568 struct tty_struct *tty;
571 spin_lock_irqsave(¤t->sighand->siglock, flags);
572 tty = tty_kref_get(current->signal->tty);
573 spin_unlock_irqrestore(¤t->sighand->siglock, flags);
576 EXPORT_SYMBOL_GPL(get_current_tty);
578 static void session_clear_tty(struct pid *session)
580 struct task_struct *p;
581 do_each_pid_task(session, PIDTYPE_SID, p) {
583 } while_each_pid_task(session, PIDTYPE_SID, p);
587 * tty_wakeup - request more data
590 * Internal and external helper for wakeups of tty. This function
591 * informs the line discipline if present that the driver is ready
592 * to receive more output data.
595 void tty_wakeup(struct tty_struct *tty)
597 struct tty_ldisc *ld;
599 if (test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) {
600 ld = tty_ldisc_ref(tty);
602 if (ld->ops->write_wakeup)
603 ld->ops->write_wakeup(tty);
607 wake_up_interruptible_poll(&tty->write_wait, POLLOUT);
610 EXPORT_SYMBOL_GPL(tty_wakeup);
613 * tty_signal_session_leader - sends SIGHUP to session leader
614 * @tty controlling tty
615 * @exit_session if non-zero, signal all foreground group processes
617 * Send SIGHUP and SIGCONT to the session leader and its process group.
618 * Optionally, signal all processes in the foreground process group.
620 * Returns the number of processes in the session with this tty
621 * as their controlling terminal. This value is used to drop
622 * tty references for those processes.
624 static int tty_signal_session_leader(struct tty_struct *tty, int exit_session)
626 struct task_struct *p;
628 struct pid *tty_pgrp = NULL;
630 read_lock(&tasklist_lock);
632 do_each_pid_task(tty->session, PIDTYPE_SID, p) {
633 spin_lock_irq(&p->sighand->siglock);
634 if (p->signal->tty == tty) {
635 p->signal->tty = NULL;
636 /* We defer the dereferences outside fo
640 if (!p->signal->leader) {
641 spin_unlock_irq(&p->sighand->siglock);
644 __group_send_sig_info(SIGHUP, SEND_SIG_PRIV, p);
645 __group_send_sig_info(SIGCONT, SEND_SIG_PRIV, p);
646 put_pid(p->signal->tty_old_pgrp); /* A noop */
647 spin_lock(&tty->ctrl_lock);
648 tty_pgrp = get_pid(tty->pgrp);
650 p->signal->tty_old_pgrp = get_pid(tty->pgrp);
651 spin_unlock(&tty->ctrl_lock);
652 spin_unlock_irq(&p->sighand->siglock);
653 } while_each_pid_task(tty->session, PIDTYPE_SID, p);
655 read_unlock(&tasklist_lock);
659 kill_pgrp(tty_pgrp, SIGHUP, exit_session);
667 * __tty_hangup - actual handler for hangup events
670 * This can be called by a "kworker" kernel thread. That is process
671 * synchronous but doesn't hold any locks, so we need to make sure we
672 * have the appropriate locks for what we're doing.
674 * The hangup event clears any pending redirections onto the hung up
675 * device. It ensures future writes will error and it does the needed
676 * line discipline hangup and signal delivery. The tty object itself
681 * redirect lock for undoing redirection
682 * file list lock for manipulating list of ttys
683 * tty_ldiscs_lock from called functions
684 * termios_rwsem resetting termios data
685 * tasklist_lock to walk task list for hangup event
686 * ->siglock to protect ->signal/->sighand
688 static void __tty_hangup(struct tty_struct *tty, int exit_session)
690 struct file *cons_filp = NULL;
691 struct file *filp, *f = NULL;
692 struct tty_file_private *priv;
693 int closecount = 0, n;
700 spin_lock(&redirect_lock);
701 if (redirect && file_tty(redirect) == tty) {
705 spin_unlock(&redirect_lock);
709 if (test_bit(TTY_HUPPED, &tty->flags)) {
715 * Some console devices aren't actually hung up for technical and
716 * historical reasons, which can lead to indefinite interruptible
717 * sleep in n_tty_read(). The following explicitly tells
718 * n_tty_read() to abort readers.
720 set_bit(TTY_HUPPING, &tty->flags);
722 /* inuse_filps is protected by the single tty lock,
723 this really needs to change if we want to flush the
724 workqueue with the lock held */
725 check_tty_count(tty, "tty_hangup");
727 spin_lock(&tty->files_lock);
728 /* This breaks for file handles being sent over AF_UNIX sockets ? */
729 list_for_each_entry(priv, &tty->tty_files, list) {
731 if (filp->f_op->write == redirected_tty_write)
733 if (filp->f_op->write != tty_write)
736 __tty_fasync(-1, filp, 0); /* can't block */
737 filp->f_op = &hung_up_tty_fops;
739 spin_unlock(&tty->files_lock);
741 refs = tty_signal_session_leader(tty, exit_session);
742 /* Account for the p->signal references we killed */
746 tty_ldisc_hangup(tty, cons_filp != NULL);
748 spin_lock_irq(&tty->ctrl_lock);
749 clear_bit(TTY_THROTTLED, &tty->flags);
750 clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
751 put_pid(tty->session);
755 tty->ctrl_status = 0;
756 spin_unlock_irq(&tty->ctrl_lock);
759 * If one of the devices matches a console pointer, we
760 * cannot just call hangup() because that will cause
761 * tty->count and state->count to go out of sync.
762 * So we just call close() the right number of times.
766 for (n = 0; n < closecount; n++)
767 tty->ops->close(tty, cons_filp);
768 } else if (tty->ops->hangup)
769 tty->ops->hangup(tty);
771 * We don't want to have driver/ldisc interactions beyond the ones
772 * we did here. The driver layer expects no calls after ->hangup()
773 * from the ldisc side, which is now guaranteed.
775 set_bit(TTY_HUPPED, &tty->flags);
776 clear_bit(TTY_HUPPING, &tty->flags);
783 static void do_tty_hangup(struct work_struct *work)
785 struct tty_struct *tty =
786 container_of(work, struct tty_struct, hangup_work);
788 __tty_hangup(tty, 0);
792 * tty_hangup - trigger a hangup event
793 * @tty: tty to hangup
795 * A carrier loss (virtual or otherwise) has occurred on this like
796 * schedule a hangup sequence to run after this event.
799 void tty_hangup(struct tty_struct *tty)
801 tty_debug_hangup(tty, "hangup\n");
802 schedule_work(&tty->hangup_work);
805 EXPORT_SYMBOL(tty_hangup);
808 * tty_vhangup - process vhangup
809 * @tty: tty to hangup
811 * The user has asked via system call for the terminal to be hung up.
812 * We do this synchronously so that when the syscall returns the process
813 * is complete. That guarantee is necessary for security reasons.
816 void tty_vhangup(struct tty_struct *tty)
818 tty_debug_hangup(tty, "vhangup\n");
819 __tty_hangup(tty, 0);
822 EXPORT_SYMBOL(tty_vhangup);
826 * tty_vhangup_self - process vhangup for own ctty
828 * Perform a vhangup on the current controlling tty
831 void tty_vhangup_self(void)
833 struct tty_struct *tty;
835 tty = get_current_tty();
843 * tty_vhangup_session - hangup session leader exit
844 * @tty: tty to hangup
846 * The session leader is exiting and hanging up its controlling terminal.
847 * Every process in the foreground process group is signalled SIGHUP.
849 * We do this synchronously so that when the syscall returns the process
850 * is complete. That guarantee is necessary for security reasons.
853 static void tty_vhangup_session(struct tty_struct *tty)
855 tty_debug_hangup(tty, "session hangup\n");
856 __tty_hangup(tty, 1);
860 * tty_hung_up_p - was tty hung up
861 * @filp: file pointer of tty
863 * Return true if the tty has been subject to a vhangup or a carrier
867 int tty_hung_up_p(struct file *filp)
869 return (filp->f_op == &hung_up_tty_fops);
872 EXPORT_SYMBOL(tty_hung_up_p);
875 * disassociate_ctty - disconnect controlling tty
876 * @on_exit: true if exiting so need to "hang up" the session
878 * This function is typically called only by the session leader, when
879 * it wants to disassociate itself from its controlling tty.
881 * It performs the following functions:
882 * (1) Sends a SIGHUP and SIGCONT to the foreground process group
883 * (2) Clears the tty from being controlling the session
884 * (3) Clears the controlling tty for all processes in the
887 * The argument on_exit is set to 1 if called when a process is
888 * exiting; it is 0 if called by the ioctl TIOCNOTTY.
891 * BTM is taken for hysterical raisins, and held when
892 * called from no_tty().
893 * tty_mutex is taken to protect tty
894 * ->siglock is taken to protect ->signal/->sighand
895 * tasklist_lock is taken to walk process list for sessions
896 * ->siglock is taken to protect ->signal/->sighand
899 void disassociate_ctty(int on_exit)
901 struct tty_struct *tty;
903 if (!current->signal->leader)
906 tty = get_current_tty();
908 if (on_exit && tty->driver->type != TTY_DRIVER_TYPE_PTY) {
909 tty_vhangup_session(tty);
911 struct pid *tty_pgrp = tty_get_pgrp(tty);
913 kill_pgrp(tty_pgrp, SIGHUP, on_exit);
915 kill_pgrp(tty_pgrp, SIGCONT, on_exit);
921 } else if (on_exit) {
922 struct pid *old_pgrp;
923 spin_lock_irq(¤t->sighand->siglock);
924 old_pgrp = current->signal->tty_old_pgrp;
925 current->signal->tty_old_pgrp = NULL;
926 spin_unlock_irq(¤t->sighand->siglock);
928 kill_pgrp(old_pgrp, SIGHUP, on_exit);
929 kill_pgrp(old_pgrp, SIGCONT, on_exit);
935 spin_lock_irq(¤t->sighand->siglock);
936 put_pid(current->signal->tty_old_pgrp);
937 current->signal->tty_old_pgrp = NULL;
938 tty = tty_kref_get(current->signal->tty);
939 spin_unlock_irq(¤t->sighand->siglock);
945 spin_lock_irqsave(&tty->ctrl_lock, flags);
946 put_pid(tty->session);
950 spin_unlock_irqrestore(&tty->ctrl_lock, flags);
954 tty_debug_hangup(tty, "no current tty\n");
956 /* Now clear signal->tty under the lock */
957 read_lock(&tasklist_lock);
958 session_clear_tty(task_session(current));
959 read_unlock(&tasklist_lock);
964 * no_tty - Ensure the current process does not have a controlling tty
968 /* FIXME: Review locking here. The tty_lock never covered any race
969 between a new association and proc_clear_tty but possible we need
970 to protect against this anyway */
971 struct task_struct *tsk = current;
972 disassociate_ctty(0);
978 * stop_tty - propagate flow control
981 * Perform flow control to the driver. May be called
982 * on an already stopped device and will not re-call the driver
985 * This functionality is used by both the line disciplines for
986 * halting incoming flow and by the driver. It may therefore be
987 * called from any context, may be under the tty atomic_write_lock
994 void __stop_tty(struct tty_struct *tty)
1000 tty->ops->stop(tty);
1003 void stop_tty(struct tty_struct *tty)
1005 unsigned long flags;
1007 spin_lock_irqsave(&tty->flow_lock, flags);
1009 spin_unlock_irqrestore(&tty->flow_lock, flags);
1011 EXPORT_SYMBOL(stop_tty);
1014 * start_tty - propagate flow control
1015 * @tty: tty to start
1017 * Start a tty that has been stopped if at all possible. If this
1018 * tty was previous stopped and is now being started, the driver
1019 * start method is invoked and the line discipline woken.
1025 void __start_tty(struct tty_struct *tty)
1027 if (!tty->stopped || tty->flow_stopped)
1030 if (tty->ops->start)
1031 tty->ops->start(tty);
1035 void start_tty(struct tty_struct *tty)
1037 unsigned long flags;
1039 spin_lock_irqsave(&tty->flow_lock, flags);
1041 spin_unlock_irqrestore(&tty->flow_lock, flags);
1043 EXPORT_SYMBOL(start_tty);
1045 static void tty_update_time(struct timespec *time)
1047 unsigned long sec = get_seconds();
1050 * We only care if the two values differ in anything other than the
1051 * lower three bits (i.e every 8 seconds). If so, then we can update
1052 * the time of the tty device, otherwise it could be construded as a
1053 * security leak to let userspace know the exact timing of the tty.
1055 if ((sec ^ time->tv_sec) & ~7)
1060 * tty_read - read method for tty device files
1061 * @file: pointer to tty file
1063 * @count: size of user buffer
1066 * Perform the read system call function on this terminal device. Checks
1067 * for hung up devices before calling the line discipline method.
1070 * Locks the line discipline internally while needed. Multiple
1071 * read calls may be outstanding in parallel.
1074 static ssize_t tty_read(struct file *file, char __user *buf, size_t count,
1078 struct inode *inode = file_inode(file);
1079 struct tty_struct *tty = file_tty(file);
1080 struct tty_ldisc *ld;
1082 if (tty_paranoia_check(tty, inode, "tty_read"))
1084 if (!tty || tty_io_error(tty))
1087 /* We want to wait for the line discipline to sort out in this
1089 ld = tty_ldisc_ref_wait(tty);
1091 return hung_up_tty_read(file, buf, count, ppos);
1093 i = ld->ops->read(tty, file, buf, count);
1096 tty_ldisc_deref(ld);
1099 tty_update_time(&inode->i_atime);
1104 static void tty_write_unlock(struct tty_struct *tty)
1106 mutex_unlock(&tty->atomic_write_lock);
1107 wake_up_interruptible_poll(&tty->write_wait, POLLOUT);
1110 static int tty_write_lock(struct tty_struct *tty, int ndelay)
1112 if (!mutex_trylock(&tty->atomic_write_lock)) {
1115 if (mutex_lock_interruptible(&tty->atomic_write_lock))
1116 return -ERESTARTSYS;
1122 * Split writes up in sane blocksizes to avoid
1123 * denial-of-service type attacks
1125 static inline ssize_t do_tty_write(
1126 ssize_t (*write)(struct tty_struct *, struct file *, const unsigned char *, size_t),
1127 struct tty_struct *tty,
1129 const char __user *buf,
1132 ssize_t ret, written = 0;
1135 ret = tty_write_lock(tty, file->f_flags & O_NDELAY);
1140 * We chunk up writes into a temporary buffer. This
1141 * simplifies low-level drivers immensely, since they
1142 * don't have locking issues and user mode accesses.
1144 * But if TTY_NO_WRITE_SPLIT is set, we should use a
1147 * The default chunk-size is 2kB, because the NTTY
1148 * layer has problems with bigger chunks. It will
1149 * claim to be able to handle more characters than
1152 * FIXME: This can probably go away now except that 64K chunks
1153 * are too likely to fail unless switched to vmalloc...
1156 if (test_bit(TTY_NO_WRITE_SPLIT, &tty->flags))
1161 /* write_buf/write_cnt is protected by the atomic_write_lock mutex */
1162 if (tty->write_cnt < chunk) {
1163 unsigned char *buf_chunk;
1168 buf_chunk = kmalloc(chunk, GFP_KERNEL);
1173 kfree(tty->write_buf);
1174 tty->write_cnt = chunk;
1175 tty->write_buf = buf_chunk;
1178 /* Do the write .. */
1180 size_t size = count;
1184 if (copy_from_user(tty->write_buf, buf, size))
1186 ret = write(tty, file, tty->write_buf, size);
1195 if (signal_pending(current))
1200 tty_update_time(&file_inode(file)->i_mtime);
1204 tty_write_unlock(tty);
1209 * tty_write_message - write a message to a certain tty, not just the console.
1210 * @tty: the destination tty_struct
1211 * @msg: the message to write
1213 * This is used for messages that need to be redirected to a specific tty.
1214 * We don't put it into the syslog queue right now maybe in the future if
1217 * We must still hold the BTM and test the CLOSING flag for the moment.
1220 void tty_write_message(struct tty_struct *tty, char *msg)
1223 mutex_lock(&tty->atomic_write_lock);
1225 if (tty->ops->write && tty->count > 0)
1226 tty->ops->write(tty, msg, strlen(msg));
1228 tty_write_unlock(tty);
1235 * tty_write - write method for tty device file
1236 * @file: tty file pointer
1237 * @buf: user data to write
1238 * @count: bytes to write
1241 * Write data to a tty device via the line discipline.
1244 * Locks the line discipline as required
1245 * Writes to the tty driver are serialized by the atomic_write_lock
1246 * and are then processed in chunks to the device. The line discipline
1247 * write method will not be invoked in parallel for each device.
1250 static ssize_t tty_write(struct file *file, const char __user *buf,
1251 size_t count, loff_t *ppos)
1253 struct tty_struct *tty = file_tty(file);
1254 struct tty_ldisc *ld;
1257 if (tty_paranoia_check(tty, file_inode(file), "tty_write"))
1259 if (!tty || !tty->ops->write || tty_io_error(tty))
1261 /* Short term debug to catch buggy drivers */
1262 if (tty->ops->write_room == NULL)
1263 tty_err(tty, "missing write_room method\n");
1264 ld = tty_ldisc_ref_wait(tty);
1266 return hung_up_tty_write(file, buf, count, ppos);
1267 if (!ld->ops->write)
1270 ret = do_tty_write(ld->ops->write, tty, file, buf, count);
1271 tty_ldisc_deref(ld);
1275 ssize_t redirected_tty_write(struct file *file, const char __user *buf,
1276 size_t count, loff_t *ppos)
1278 struct file *p = NULL;
1280 spin_lock(&redirect_lock);
1282 p = get_file(redirect);
1283 spin_unlock(&redirect_lock);
1287 res = vfs_write(p, buf, count, &p->f_pos);
1291 return tty_write(file, buf, count, ppos);
1295 * tty_send_xchar - send priority character
1297 * Send a high priority character to the tty even if stopped
1299 * Locking: none for xchar method, write ordering for write method.
1302 int tty_send_xchar(struct tty_struct *tty, char ch)
1304 int was_stopped = tty->stopped;
1306 if (tty->ops->send_xchar) {
1307 down_read(&tty->termios_rwsem);
1308 tty->ops->send_xchar(tty, ch);
1309 up_read(&tty->termios_rwsem);
1313 if (tty_write_lock(tty, 0) < 0)
1314 return -ERESTARTSYS;
1316 down_read(&tty->termios_rwsem);
1319 tty->ops->write(tty, &ch, 1);
1322 up_read(&tty->termios_rwsem);
1323 tty_write_unlock(tty);
1327 static char ptychar[] = "pqrstuvwxyzabcde";
1330 * pty_line_name - generate name for a pty
1331 * @driver: the tty driver in use
1332 * @index: the minor number
1333 * @p: output buffer of at least 6 bytes
1335 * Generate a name from a driver reference and write it to the output
1340 static void pty_line_name(struct tty_driver *driver, int index, char *p)
1342 int i = index + driver->name_base;
1343 /* ->name is initialized to "ttyp", but "tty" is expected */
1344 sprintf(p, "%s%c%x",
1345 driver->subtype == PTY_TYPE_SLAVE ? "tty" : driver->name,
1346 ptychar[i >> 4 & 0xf], i & 0xf);
1350 * tty_line_name - generate name for a tty
1351 * @driver: the tty driver in use
1352 * @index: the minor number
1353 * @p: output buffer of at least 7 bytes
1355 * Generate a name from a driver reference and write it to the output
1360 static ssize_t tty_line_name(struct tty_driver *driver, int index, char *p)
1362 if (driver->flags & TTY_DRIVER_UNNUMBERED_NODE)
1363 return sprintf(p, "%s", driver->name);
1365 return sprintf(p, "%s%d", driver->name,
1366 index + driver->name_base);
1370 * tty_driver_lookup_tty() - find an existing tty, if any
1371 * @driver: the driver for the tty
1372 * @idx: the minor number
1374 * Return the tty, if found. If not found, return NULL or ERR_PTR() if the
1375 * driver lookup() method returns an error.
1377 * Locking: tty_mutex must be held. If the tty is found, bump the tty kref.
1379 static struct tty_struct *tty_driver_lookup_tty(struct tty_driver *driver,
1380 struct file *file, int idx)
1382 struct tty_struct *tty;
1384 if (driver->ops->lookup)
1385 tty = driver->ops->lookup(driver, file, idx);
1387 tty = driver->ttys[idx];
1395 * tty_init_termios - helper for termios setup
1396 * @tty: the tty to set up
1398 * Initialise the termios structures for this tty. Thus runs under
1399 * the tty_mutex currently so we can be relaxed about ordering.
1402 void tty_init_termios(struct tty_struct *tty)
1404 struct ktermios *tp;
1405 int idx = tty->index;
1407 if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
1408 tty->termios = tty->driver->init_termios;
1410 /* Check for lazy saved data */
1411 tp = tty->driver->termios[idx];
1414 tty->termios.c_line = tty->driver->init_termios.c_line;
1416 tty->termios = tty->driver->init_termios;
1418 /* Compatibility until drivers always set this */
1419 tty->termios.c_ispeed = tty_termios_input_baud_rate(&tty->termios);
1420 tty->termios.c_ospeed = tty_termios_baud_rate(&tty->termios);
1422 EXPORT_SYMBOL_GPL(tty_init_termios);
1424 int tty_standard_install(struct tty_driver *driver, struct tty_struct *tty)
1426 tty_init_termios(tty);
1427 tty_driver_kref_get(driver);
1429 driver->ttys[tty->index] = tty;
1432 EXPORT_SYMBOL_GPL(tty_standard_install);
1435 * tty_driver_install_tty() - install a tty entry in the driver
1436 * @driver: the driver for the tty
1439 * Install a tty object into the driver tables. The tty->index field
1440 * will be set by the time this is called. This method is responsible
1441 * for ensuring any need additional structures are allocated and
1444 * Locking: tty_mutex for now
1446 static int tty_driver_install_tty(struct tty_driver *driver,
1447 struct tty_struct *tty)
1449 return driver->ops->install ? driver->ops->install(driver, tty) :
1450 tty_standard_install(driver, tty);
1454 * tty_driver_remove_tty() - remove a tty from the driver tables
1455 * @driver: the driver for the tty
1456 * @idx: the minor number
1458 * Remvoe a tty object from the driver tables. The tty->index field
1459 * will be set by the time this is called.
1461 * Locking: tty_mutex for now
1463 static void tty_driver_remove_tty(struct tty_driver *driver, struct tty_struct *tty)
1465 if (driver->ops->remove)
1466 driver->ops->remove(driver, tty);
1468 driver->ttys[tty->index] = NULL;
1472 * tty_reopen() - fast re-open of an open tty
1473 * @tty - the tty to open
1475 * Return 0 on success, -errno on error.
1476 * Re-opens on master ptys are not allowed and return -EIO.
1478 * Locking: Caller must hold tty_lock
1480 static int tty_reopen(struct tty_struct *tty)
1482 struct tty_driver *driver = tty->driver;
1483 struct tty_ldisc *ld;
1486 if (driver->type == TTY_DRIVER_TYPE_PTY &&
1487 driver->subtype == PTY_TYPE_MASTER)
1493 if (test_bit(TTY_EXCLUSIVE, &tty->flags) && !capable(CAP_SYS_ADMIN))
1496 ld = tty_ldisc_ref_wait(tty);
1498 tty_ldisc_deref(ld);
1500 retval = tty_ldisc_lock(tty, 5 * HZ);
1505 retval = tty_ldisc_reinit(tty, tty->termios.c_line);
1506 tty_ldisc_unlock(tty);
1516 * tty_init_dev - initialise a tty device
1517 * @driver: tty driver we are opening a device on
1518 * @idx: device index
1519 * @ret_tty: returned tty structure
1521 * Prepare a tty device. This may not be a "new" clean device but
1522 * could also be an active device. The pty drivers require special
1523 * handling because of this.
1526 * The function is called under the tty_mutex, which
1527 * protects us from the tty struct or driver itself going away.
1529 * On exit the tty device has the line discipline attached and
1530 * a reference count of 1. If a pair was created for pty/tty use
1531 * and the other was a pty master then it too has a reference count of 1.
1533 * WSH 06/09/97: Rewritten to remove races and properly clean up after a
1534 * failed open. The new code protects the open with a mutex, so it's
1535 * really quite straightforward. The mutex locking can probably be
1536 * relaxed for the (most common) case of reopening a tty.
1539 struct tty_struct *tty_init_dev(struct tty_driver *driver, int idx)
1541 struct tty_struct *tty;
1545 * First time open is complex, especially for PTY devices.
1546 * This code guarantees that either everything succeeds and the
1547 * TTY is ready for operation, or else the table slots are vacated
1548 * and the allocated memory released. (Except that the termios
1549 * and locked termios may be retained.)
1552 if (!try_module_get(driver->owner))
1553 return ERR_PTR(-ENODEV);
1555 tty = alloc_tty_struct(driver, idx);
1558 goto err_module_put;
1562 retval = tty_driver_install_tty(driver, tty);
1567 tty->port = driver->ports[idx];
1569 WARN_RATELIMIT(!tty->port,
1570 "%s: %s driver does not set tty->port. This will crash the kernel later. Fix the driver!\n",
1571 __func__, tty->driver->name);
1573 retval = tty_ldisc_lock(tty, 5 * HZ);
1575 goto err_release_lock;
1576 tty->port->itty = tty;
1579 * Structures all installed ... call the ldisc open routines.
1580 * If we fail here just call release_tty to clean up. No need
1581 * to decrement the use counts, as release_tty doesn't care.
1583 retval = tty_ldisc_setup(tty, tty->link);
1585 goto err_release_tty;
1586 tty_ldisc_unlock(tty);
1587 /* Return the tty locked so that it cannot vanish under the caller */
1592 free_tty_struct(tty);
1594 module_put(driver->owner);
1595 return ERR_PTR(retval);
1597 /* call the tty release_tty routine to clean out this slot */
1599 tty_ldisc_unlock(tty);
1600 tty_info_ratelimited(tty, "ldisc open failed (%d), clearing slot %d\n",
1604 release_tty(tty, idx);
1605 return ERR_PTR(retval);
1608 static void tty_free_termios(struct tty_struct *tty)
1610 struct ktermios *tp;
1611 int idx = tty->index;
1613 /* If the port is going to reset then it has no termios to save */
1614 if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
1617 /* Stash the termios data */
1618 tp = tty->driver->termios[idx];
1620 tp = kmalloc(sizeof(struct ktermios), GFP_KERNEL);
1623 tty->driver->termios[idx] = tp;
1629 * tty_flush_works - flush all works of a tty/pty pair
1630 * @tty: tty device to flush works for (or either end of a pty pair)
1632 * Sync flush all works belonging to @tty (and the 'other' tty).
1634 static void tty_flush_works(struct tty_struct *tty)
1636 flush_work(&tty->SAK_work);
1637 flush_work(&tty->hangup_work);
1639 flush_work(&tty->link->SAK_work);
1640 flush_work(&tty->link->hangup_work);
1645 * release_one_tty - release tty structure memory
1646 * @kref: kref of tty we are obliterating
1648 * Releases memory associated with a tty structure, and clears out the
1649 * driver table slots. This function is called when a device is no longer
1650 * in use. It also gets called when setup of a device fails.
1653 * takes the file list lock internally when working on the list
1654 * of ttys that the driver keeps.
1656 * This method gets called from a work queue so that the driver private
1657 * cleanup ops can sleep (needed for USB at least)
1659 static void release_one_tty(struct work_struct *work)
1661 struct tty_struct *tty =
1662 container_of(work, struct tty_struct, hangup_work);
1663 struct tty_driver *driver = tty->driver;
1664 struct module *owner = driver->owner;
1666 if (tty->ops->cleanup)
1667 tty->ops->cleanup(tty);
1670 tty_driver_kref_put(driver);
1673 spin_lock(&tty->files_lock);
1674 list_del_init(&tty->tty_files);
1675 spin_unlock(&tty->files_lock);
1678 put_pid(tty->session);
1679 free_tty_struct(tty);
1682 static void queue_release_one_tty(struct kref *kref)
1684 struct tty_struct *tty = container_of(kref, struct tty_struct, kref);
1686 /* The hangup queue is now free so we can reuse it rather than
1687 waste a chunk of memory for each port */
1688 INIT_WORK(&tty->hangup_work, release_one_tty);
1689 schedule_work(&tty->hangup_work);
1693 * tty_kref_put - release a tty kref
1696 * Release a reference to a tty device and if need be let the kref
1697 * layer destruct the object for us
1700 void tty_kref_put(struct tty_struct *tty)
1703 kref_put(&tty->kref, queue_release_one_tty);
1705 EXPORT_SYMBOL(tty_kref_put);
1708 * release_tty - release tty structure memory
1710 * Release both @tty and a possible linked partner (think pty pair),
1711 * and decrement the refcount of the backing module.
1715 * takes the file list lock internally when working on the list
1716 * of ttys that the driver keeps.
1719 static void release_tty(struct tty_struct *tty, int idx)
1721 /* This should always be true but check for the moment */
1722 WARN_ON(tty->index != idx);
1723 WARN_ON(!mutex_is_locked(&tty_mutex));
1724 if (tty->ops->shutdown)
1725 tty->ops->shutdown(tty);
1726 tty_free_termios(tty);
1727 tty_driver_remove_tty(tty->driver, tty);
1728 tty->port->itty = NULL;
1730 tty->link->port->itty = NULL;
1731 tty_buffer_cancel_work(tty->port);
1733 tty_buffer_cancel_work(tty->link->port);
1735 tty_kref_put(tty->link);
1740 * tty_release_checks - check a tty before real release
1741 * @tty: tty to check
1742 * @o_tty: link of @tty (if any)
1743 * @idx: index of the tty
1745 * Performs some paranoid checking before true release of the @tty.
1746 * This is a no-op unless TTY_PARANOIA_CHECK is defined.
1748 static int tty_release_checks(struct tty_struct *tty, int idx)
1750 #ifdef TTY_PARANOIA_CHECK
1751 if (idx < 0 || idx >= tty->driver->num) {
1752 tty_debug(tty, "bad idx %d\n", idx);
1756 /* not much to check for devpts */
1757 if (tty->driver->flags & TTY_DRIVER_DEVPTS_MEM)
1760 if (tty != tty->driver->ttys[idx]) {
1761 tty_debug(tty, "bad driver table[%d] = %p\n",
1762 idx, tty->driver->ttys[idx]);
1765 if (tty->driver->other) {
1766 struct tty_struct *o_tty = tty->link;
1768 if (o_tty != tty->driver->other->ttys[idx]) {
1769 tty_debug(tty, "bad other table[%d] = %p\n",
1770 idx, tty->driver->other->ttys[idx]);
1773 if (o_tty->link != tty) {
1774 tty_debug(tty, "bad link = %p\n", o_tty->link);
1783 * tty_release - vfs callback for close
1784 * @inode: inode of tty
1785 * @filp: file pointer for handle to tty
1787 * Called the last time each file handle is closed that references
1788 * this tty. There may however be several such references.
1791 * Takes bkl. See tty_release_dev
1793 * Even releasing the tty structures is a tricky business.. We have
1794 * to be very careful that the structures are all released at the
1795 * same time, as interrupts might otherwise get the wrong pointers.
1797 * WSH 09/09/97: rewritten to avoid some nasty race conditions that could
1798 * lead to double frees or releasing memory still in use.
1801 int tty_release(struct inode *inode, struct file *filp)
1803 struct tty_struct *tty = file_tty(filp);
1804 struct tty_struct *o_tty = NULL;
1805 int do_sleep, final;
1810 if (tty_paranoia_check(tty, inode, __func__))
1814 check_tty_count(tty, __func__);
1816 __tty_fasync(-1, filp, 0);
1819 if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
1820 tty->driver->subtype == PTY_TYPE_MASTER)
1823 if (tty_release_checks(tty, idx)) {
1828 tty_debug_hangup(tty, "releasing (count=%d)\n", tty->count);
1830 if (tty->ops->close)
1831 tty->ops->close(tty, filp);
1833 /* If tty is pty master, lock the slave pty (stable lock order) */
1834 tty_lock_slave(o_tty);
1837 * Sanity check: if tty->count is going to zero, there shouldn't be
1838 * any waiters on tty->read_wait or tty->write_wait. We test the
1839 * wait queues and kick everyone out _before_ actually starting to
1840 * close. This ensures that we won't block while releasing the tty
1843 * The test for the o_tty closing is necessary, since the master and
1844 * slave sides may close in any order. If the slave side closes out
1845 * first, its count will be one, since the master side holds an open.
1846 * Thus this test wouldn't be triggered at the time the slave closed,
1852 if (tty->count <= 1) {
1853 if (waitqueue_active(&tty->read_wait)) {
1854 wake_up_poll(&tty->read_wait, POLLIN);
1857 if (waitqueue_active(&tty->write_wait)) {
1858 wake_up_poll(&tty->write_wait, POLLOUT);
1862 if (o_tty && o_tty->count <= 1) {
1863 if (waitqueue_active(&o_tty->read_wait)) {
1864 wake_up_poll(&o_tty->read_wait, POLLIN);
1867 if (waitqueue_active(&o_tty->write_wait)) {
1868 wake_up_poll(&o_tty->write_wait, POLLOUT);
1877 tty_warn(tty, "read/write wait queue active!\n");
1879 schedule_timeout_killable(timeout);
1880 if (timeout < 120 * HZ)
1881 timeout = 2 * timeout + 1;
1883 timeout = MAX_SCHEDULE_TIMEOUT;
1887 if (--o_tty->count < 0) {
1888 tty_warn(tty, "bad slave count (%d)\n", o_tty->count);
1892 if (--tty->count < 0) {
1893 tty_warn(tty, "bad tty->count (%d)\n", tty->count);
1898 * We've decremented tty->count, so we need to remove this file
1899 * descriptor off the tty->tty_files list; this serves two
1901 * - check_tty_count sees the correct number of file descriptors
1902 * associated with this tty.
1903 * - do_tty_hangup no longer sees this file descriptor as
1904 * something that needs to be handled for hangups.
1909 * Perform some housekeeping before deciding whether to return.
1911 * If _either_ side is closing, make sure there aren't any
1912 * processes that still think tty or o_tty is their controlling
1916 read_lock(&tasklist_lock);
1917 session_clear_tty(tty->session);
1919 session_clear_tty(o_tty->session);
1920 read_unlock(&tasklist_lock);
1923 /* check whether both sides are closing ... */
1924 final = !tty->count && !(o_tty && o_tty->count);
1926 tty_unlock_slave(o_tty);
1929 /* At this point, the tty->count == 0 should ensure a dead tty
1930 cannot be re-opened by a racing opener */
1935 tty_debug_hangup(tty, "final close\n");
1937 * Ask the line discipline code to release its structures
1939 tty_ldisc_release(tty);
1941 /* Wait for pending work before tty destruction commmences */
1942 tty_flush_works(tty);
1944 tty_debug_hangup(tty, "freeing structure\n");
1946 * The release_tty function takes care of the details of clearing
1947 * the slots and preserving the termios structure. The tty_unlock_pair
1948 * should be safe as we keep a kref while the tty is locked (so the
1949 * unlock never unlocks a freed tty).
1951 mutex_lock(&tty_mutex);
1952 release_tty(tty, idx);
1953 mutex_unlock(&tty_mutex);
1959 * tty_open_current_tty - get locked tty of current task
1960 * @device: device number
1961 * @filp: file pointer to tty
1962 * @return: locked tty of the current task iff @device is /dev/tty
1964 * Performs a re-open of the current task's controlling tty.
1966 * We cannot return driver and index like for the other nodes because
1967 * devpts will not work then. It expects inodes to be from devpts FS.
1969 static struct tty_struct *tty_open_current_tty(dev_t device, struct file *filp)
1971 struct tty_struct *tty;
1974 if (device != MKDEV(TTYAUX_MAJOR, 0))
1977 tty = get_current_tty();
1979 return ERR_PTR(-ENXIO);
1981 filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
1984 tty_kref_put(tty); /* safe to drop the kref now */
1986 retval = tty_reopen(tty);
1989 tty = ERR_PTR(retval);
1995 * tty_lookup_driver - lookup a tty driver for a given device file
1996 * @device: device number
1997 * @filp: file pointer to tty
1998 * @index: index for the device in the @return driver
1999 * @return: driver for this inode (with increased refcount)
2001 * If @return is not erroneous, the caller is responsible to decrement the
2002 * refcount by tty_driver_kref_put.
2004 * Locking: tty_mutex protects get_tty_driver
2006 static struct tty_driver *tty_lookup_driver(dev_t device, struct file *filp,
2009 struct tty_driver *driver;
2013 case MKDEV(TTY_MAJOR, 0): {
2014 extern struct tty_driver *console_driver;
2015 driver = tty_driver_kref_get(console_driver);
2016 *index = fg_console;
2020 case MKDEV(TTYAUX_MAJOR, 1): {
2021 struct tty_driver *console_driver = console_device(index);
2022 if (console_driver) {
2023 driver = tty_driver_kref_get(console_driver);
2025 /* Don't let /dev/console block */
2026 filp->f_flags |= O_NONBLOCK;
2030 return ERR_PTR(-ENODEV);
2033 driver = get_tty_driver(device, index);
2035 return ERR_PTR(-ENODEV);
2042 * tty_open_by_driver - open a tty device
2043 * @device: dev_t of device to open
2044 * @inode: inode of device file
2045 * @filp: file pointer to tty
2047 * Performs the driver lookup, checks for a reopen, or otherwise
2048 * performs the first-time tty initialization.
2050 * Returns the locked initialized or re-opened &tty_struct
2052 * Claims the global tty_mutex to serialize:
2053 * - concurrent first-time tty initialization
2054 * - concurrent tty driver removal w/ lookup
2055 * - concurrent tty removal from driver table
2057 static struct tty_struct *tty_open_by_driver(dev_t device, struct inode *inode,
2060 struct tty_struct *tty;
2061 struct tty_driver *driver = NULL;
2065 mutex_lock(&tty_mutex);
2066 driver = tty_lookup_driver(device, filp, &index);
2067 if (IS_ERR(driver)) {
2068 mutex_unlock(&tty_mutex);
2069 return ERR_CAST(driver);
2072 /* check whether we're reopening an existing tty */
2073 tty = tty_driver_lookup_tty(driver, filp, index);
2075 mutex_unlock(&tty_mutex);
2080 mutex_unlock(&tty_mutex);
2081 retval = tty_lock_interruptible(tty);
2082 tty_kref_put(tty); /* drop kref from tty_driver_lookup_tty() */
2084 if (retval == -EINTR)
2085 retval = -ERESTARTSYS;
2086 tty = ERR_PTR(retval);
2089 retval = tty_reopen(tty);
2092 tty = ERR_PTR(retval);
2094 } else { /* Returns with the tty_lock held for now */
2095 tty = tty_init_dev(driver, index);
2096 mutex_unlock(&tty_mutex);
2099 tty_driver_kref_put(driver);
2104 * tty_open - open a tty device
2105 * @inode: inode of device file
2106 * @filp: file pointer to tty
2108 * tty_open and tty_release keep up the tty count that contains the
2109 * number of opens done on a tty. We cannot use the inode-count, as
2110 * different inodes might point to the same tty.
2112 * Open-counting is needed for pty masters, as well as for keeping
2113 * track of serial lines: DTR is dropped when the last close happens.
2114 * (This is not done solely through tty->count, now. - Ted 1/27/92)
2116 * The termios state of a pty is reset on first open so that
2117 * settings don't persist across reuse.
2119 * Locking: tty_mutex protects tty, tty_lookup_driver and tty_init_dev.
2120 * tty->count should protect the rest.
2121 * ->siglock protects ->signal/->sighand
2123 * Note: the tty_unlock/lock cases without a ref are only safe due to
2127 static int tty_open(struct inode *inode, struct file *filp)
2129 struct tty_struct *tty;
2131 dev_t device = inode->i_rdev;
2132 unsigned saved_flags = filp->f_flags;
2134 nonseekable_open(inode, filp);
2137 retval = tty_alloc_file(filp);
2141 tty = tty_open_current_tty(device, filp);
2143 tty = tty_open_by_driver(device, inode, filp);
2146 tty_free_file(filp);
2147 retval = PTR_ERR(tty);
2148 if (retval != -EAGAIN || signal_pending(current))
2154 tty_add_file(tty, filp);
2156 check_tty_count(tty, __func__);
2157 tty_debug_hangup(tty, "opening (count=%d)\n", tty->count);
2160 retval = tty->ops->open(tty, filp);
2163 filp->f_flags = saved_flags;
2166 tty_debug_hangup(tty, "open error %d, releasing\n", retval);
2168 tty_unlock(tty); /* need to call tty_release without BTM */
2169 tty_release(inode, filp);
2170 if (retval != -ERESTARTSYS)
2173 if (signal_pending(current))
2178 * Need to reset f_op in case a hangup happened.
2180 if (tty_hung_up_p(filp))
2181 filp->f_op = &tty_fops;
2184 clear_bit(TTY_HUPPED, &tty->flags);
2187 read_lock(&tasklist_lock);
2188 spin_lock_irq(¤t->sighand->siglock);
2189 noctty = (filp->f_flags & O_NOCTTY) ||
2190 (IS_ENABLED(CONFIG_VT) && device == MKDEV(TTY_MAJOR, 0)) ||
2191 device == MKDEV(TTYAUX_MAJOR, 1) ||
2192 (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
2193 tty->driver->subtype == PTY_TYPE_MASTER);
2196 current->signal->leader &&
2197 !current->signal->tty &&
2198 tty->session == NULL) {
2200 * Don't let a process that only has write access to the tty
2201 * obtain the privileges associated with having a tty as
2202 * controlling terminal (being able to reopen it with full
2203 * access through /dev/tty, being able to perform pushback).
2204 * Many distributions set the group of all ttys to "tty" and
2205 * grant write-only access to all terminals for setgid tty
2206 * binaries, which should not imply full privileges on all ttys.
2208 * This could theoretically break old code that performs open()
2209 * on a write-only file descriptor. In that case, it might be
2210 * necessary to also permit this if
2211 * inode_permission(inode, MAY_READ) == 0.
2213 if (filp->f_mode & FMODE_READ)
2214 __proc_set_tty(tty);
2216 spin_unlock_irq(¤t->sighand->siglock);
2217 read_unlock(&tasklist_lock);
2225 * tty_poll - check tty status
2226 * @filp: file being polled
2227 * @wait: poll wait structures to update
2229 * Call the line discipline polling method to obtain the poll
2230 * status of the device.
2232 * Locking: locks called line discipline but ldisc poll method
2233 * may be re-entered freely by other callers.
2236 static unsigned int tty_poll(struct file *filp, poll_table *wait)
2238 struct tty_struct *tty = file_tty(filp);
2239 struct tty_ldisc *ld;
2242 if (tty_paranoia_check(tty, file_inode(filp), "tty_poll"))
2245 ld = tty_ldisc_ref_wait(tty);
2247 return hung_up_tty_poll(filp, wait);
2249 ret = ld->ops->poll(tty, filp, wait);
2250 tty_ldisc_deref(ld);
2254 static int __tty_fasync(int fd, struct file *filp, int on)
2256 struct tty_struct *tty = file_tty(filp);
2257 unsigned long flags;
2260 if (tty_paranoia_check(tty, file_inode(filp), "tty_fasync"))
2263 retval = fasync_helper(fd, filp, on, &tty->fasync);
2271 spin_lock_irqsave(&tty->ctrl_lock, flags);
2274 type = PIDTYPE_PGID;
2276 pid = task_pid(current);
2280 spin_unlock_irqrestore(&tty->ctrl_lock, flags);
2281 __f_setown(filp, pid, type, 0);
2289 static int tty_fasync(int fd, struct file *filp, int on)
2291 struct tty_struct *tty = file_tty(filp);
2292 int retval = -ENOTTY;
2295 if (!tty_hung_up_p(filp))
2296 retval = __tty_fasync(fd, filp, on);
2303 * tiocsti - fake input character
2304 * @tty: tty to fake input into
2305 * @p: pointer to character
2307 * Fake input to a tty device. Does the necessary locking and
2310 * FIXME: does not honour flow control ??
2313 * Called functions take tty_ldiscs_lock
2314 * current->signal->tty check is safe without locks
2317 static int tiocsti(struct tty_struct *tty, char __user *p)
2320 struct tty_ldisc *ld;
2322 if ((current->signal->tty != tty) && !capable(CAP_SYS_ADMIN))
2324 if (get_user(ch, p))
2326 tty_audit_tiocsti(tty, ch);
2327 ld = tty_ldisc_ref_wait(tty);
2330 tty_buffer_lock_exclusive(tty->port);
2331 if (ld->ops->receive_buf)
2332 ld->ops->receive_buf(tty, &ch, &mbz, 1);
2333 tty_buffer_unlock_exclusive(tty->port);
2334 tty_ldisc_deref(ld);
2339 * tiocgwinsz - implement window query ioctl
2341 * @arg: user buffer for result
2343 * Copies the kernel idea of the window size into the user buffer.
2345 * Locking: tty->winsize_mutex is taken to ensure the winsize data
2349 static int tiocgwinsz(struct tty_struct *tty, struct winsize __user *arg)
2353 mutex_lock(&tty->winsize_mutex);
2354 err = copy_to_user(arg, &tty->winsize, sizeof(*arg));
2355 mutex_unlock(&tty->winsize_mutex);
2357 return err ? -EFAULT: 0;
2361 * tty_do_resize - resize event
2362 * @tty: tty being resized
2363 * @rows: rows (character)
2364 * @cols: cols (character)
2366 * Update the termios variables and send the necessary signals to
2367 * peform a terminal resize correctly
2370 int tty_do_resize(struct tty_struct *tty, struct winsize *ws)
2375 mutex_lock(&tty->winsize_mutex);
2376 if (!memcmp(ws, &tty->winsize, sizeof(*ws)))
2379 /* Signal the foreground process group */
2380 pgrp = tty_get_pgrp(tty);
2382 kill_pgrp(pgrp, SIGWINCH, 1);
2387 mutex_unlock(&tty->winsize_mutex);
2390 EXPORT_SYMBOL(tty_do_resize);
2393 * tiocswinsz - implement window size set ioctl
2394 * @tty; tty side of tty
2395 * @arg: user buffer for result
2397 * Copies the user idea of the window size to the kernel. Traditionally
2398 * this is just advisory information but for the Linux console it
2399 * actually has driver level meaning and triggers a VC resize.
2402 * Driver dependent. The default do_resize method takes the
2403 * tty termios mutex and ctrl_lock. The console takes its own lock
2404 * then calls into the default method.
2407 static int tiocswinsz(struct tty_struct *tty, struct winsize __user *arg)
2409 struct winsize tmp_ws;
2410 if (copy_from_user(&tmp_ws, arg, sizeof(*arg)))
2413 if (tty->ops->resize)
2414 return tty->ops->resize(tty, &tmp_ws);
2416 return tty_do_resize(tty, &tmp_ws);
2420 * tioccons - allow admin to move logical console
2421 * @file: the file to become console
2423 * Allow the administrator to move the redirected console device
2425 * Locking: uses redirect_lock to guard the redirect information
2428 static int tioccons(struct file *file)
2430 if (!capable(CAP_SYS_ADMIN))
2432 if (file->f_op->write == redirected_tty_write) {
2434 spin_lock(&redirect_lock);
2437 spin_unlock(&redirect_lock);
2442 spin_lock(&redirect_lock);
2444 spin_unlock(&redirect_lock);
2447 redirect = get_file(file);
2448 spin_unlock(&redirect_lock);
2453 * fionbio - non blocking ioctl
2454 * @file: file to set blocking value
2455 * @p: user parameter
2457 * Historical tty interfaces had a blocking control ioctl before
2458 * the generic functionality existed. This piece of history is preserved
2459 * in the expected tty API of posix OS's.
2461 * Locking: none, the open file handle ensures it won't go away.
2464 static int fionbio(struct file *file, int __user *p)
2468 if (get_user(nonblock, p))
2471 spin_lock(&file->f_lock);
2473 file->f_flags |= O_NONBLOCK;
2475 file->f_flags &= ~O_NONBLOCK;
2476 spin_unlock(&file->f_lock);
2481 * tiocsctty - set controlling tty
2482 * @tty: tty structure
2483 * @arg: user argument
2485 * This ioctl is used to manage job control. It permits a session
2486 * leader to set this tty as the controlling tty for the session.
2489 * Takes tty_lock() to serialize proc_set_tty() for this tty
2490 * Takes tasklist_lock internally to walk sessions
2491 * Takes ->siglock() when updating signal->tty
2494 static int tiocsctty(struct tty_struct *tty, struct file *file, int arg)
2499 read_lock(&tasklist_lock);
2501 if (current->signal->leader && (task_session(current) == tty->session))
2505 * The process must be a session leader and
2506 * not have a controlling tty already.
2508 if (!current->signal->leader || current->signal->tty) {
2515 * This tty is already the controlling
2516 * tty for another session group!
2518 if (arg == 1 && capable(CAP_SYS_ADMIN)) {
2522 session_clear_tty(tty->session);
2529 /* See the comment in tty_open(). */
2530 if ((file->f_mode & FMODE_READ) == 0 && !capable(CAP_SYS_ADMIN)) {
2537 read_unlock(&tasklist_lock);
2543 * tty_get_pgrp - return a ref counted pgrp pid
2546 * Returns a refcounted instance of the pid struct for the process
2547 * group controlling the tty.
2550 struct pid *tty_get_pgrp(struct tty_struct *tty)
2552 unsigned long flags;
2555 spin_lock_irqsave(&tty->ctrl_lock, flags);
2556 pgrp = get_pid(tty->pgrp);
2557 spin_unlock_irqrestore(&tty->ctrl_lock, flags);
2561 EXPORT_SYMBOL_GPL(tty_get_pgrp);
2564 * This checks not only the pgrp, but falls back on the pid if no
2565 * satisfactory pgrp is found. I dunno - gdb doesn't work correctly
2568 * The caller must hold rcu lock or the tasklist lock.
2570 static struct pid *session_of_pgrp(struct pid *pgrp)
2572 struct task_struct *p;
2573 struct pid *sid = NULL;
2575 p = pid_task(pgrp, PIDTYPE_PGID);
2577 p = pid_task(pgrp, PIDTYPE_PID);
2579 sid = task_session(p);
2585 * tiocgpgrp - get process group
2586 * @tty: tty passed by user
2587 * @real_tty: tty side of the tty passed by the user if a pty else the tty
2590 * Obtain the process group of the tty. If there is no process group
2593 * Locking: none. Reference to current->signal->tty is safe.
2596 static int tiocgpgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
2601 * (tty == real_tty) is a cheap way of
2602 * testing if the tty is NOT a master pty.
2604 if (tty == real_tty && current->signal->tty != real_tty)
2606 pid = tty_get_pgrp(real_tty);
2607 ret = put_user(pid_vnr(pid), p);
2613 * tiocspgrp - attempt to set process group
2614 * @tty: tty passed by user
2615 * @real_tty: tty side device matching tty passed by user
2618 * Set the process group of the tty to the session passed. Only
2619 * permitted where the tty session is our session.
2621 * Locking: RCU, ctrl lock
2624 static int tiocspgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
2628 int retval = tty_check_change(real_tty);
2635 if (get_user(pgrp_nr, p))
2640 spin_lock_irq(&real_tty->ctrl_lock);
2641 if (!current->signal->tty ||
2642 (current->signal->tty != real_tty) ||
2643 (real_tty->session != task_session(current))) {
2645 goto out_unlock_ctrl;
2648 pgrp = find_vpid(pgrp_nr);
2653 if (session_of_pgrp(pgrp) != task_session(current))
2656 put_pid(real_tty->pgrp);
2657 real_tty->pgrp = get_pid(pgrp);
2661 spin_unlock_irq(&real_tty->ctrl_lock);
2666 * tiocgsid - get session id
2667 * @tty: tty passed by user
2668 * @real_tty: tty side of the tty passed by the user if a pty else the tty
2669 * @p: pointer to returned session id
2671 * Obtain the session id of the tty. If there is no session
2675 static int tiocgsid(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
2677 unsigned long flags;
2681 * (tty == real_tty) is a cheap way of
2682 * testing if the tty is NOT a master pty.
2684 if (tty == real_tty && current->signal->tty != real_tty)
2687 spin_lock_irqsave(&real_tty->ctrl_lock, flags);
2688 if (!real_tty->session)
2690 sid = pid_vnr(real_tty->session);
2691 spin_unlock_irqrestore(&real_tty->ctrl_lock, flags);
2693 return put_user(sid, p);
2696 spin_unlock_irqrestore(&real_tty->ctrl_lock, flags);
2701 * tiocsetd - set line discipline
2703 * @p: pointer to user data
2705 * Set the line discipline according to user request.
2707 * Locking: see tty_set_ldisc, this function is just a helper
2710 static int tiocsetd(struct tty_struct *tty, int __user *p)
2715 if (get_user(disc, p))
2718 ret = tty_set_ldisc(tty, disc);
2724 * tiocgetd - get line discipline
2726 * @p: pointer to user data
2728 * Retrieves the line discipline id directly from the ldisc.
2730 * Locking: waits for ldisc reference (in case the line discipline
2731 * is changing or the tty is being hungup)
2734 static int tiocgetd(struct tty_struct *tty, int __user *p)
2736 struct tty_ldisc *ld;
2739 ld = tty_ldisc_ref_wait(tty);
2742 ret = put_user(ld->ops->num, p);
2743 tty_ldisc_deref(ld);
2748 * send_break - performed time break
2749 * @tty: device to break on
2750 * @duration: timeout in mS
2752 * Perform a timed break on hardware that lacks its own driver level
2753 * timed break functionality.
2756 * atomic_write_lock serializes
2760 static int send_break(struct tty_struct *tty, unsigned int duration)
2764 if (tty->ops->break_ctl == NULL)
2767 if (tty->driver->flags & TTY_DRIVER_HARDWARE_BREAK)
2768 retval = tty->ops->break_ctl(tty, duration);
2770 /* Do the work ourselves */
2771 if (tty_write_lock(tty, 0) < 0)
2773 retval = tty->ops->break_ctl(tty, -1);
2776 if (!signal_pending(current))
2777 msleep_interruptible(duration);
2778 retval = tty->ops->break_ctl(tty, 0);
2780 tty_write_unlock(tty);
2781 if (signal_pending(current))
2788 * tty_tiocmget - get modem status
2790 * @file: user file pointer
2791 * @p: pointer to result
2793 * Obtain the modem status bits from the tty driver if the feature
2794 * is supported. Return -ENOTTY if it is not available.
2796 * Locking: none (up to the driver)
2799 static int tty_tiocmget(struct tty_struct *tty, int __user *p)
2801 int retval = -ENOTTY;
2803 if (tty->ops->tiocmget) {
2804 retval = tty->ops->tiocmget(tty);
2807 retval = put_user(retval, p);
2813 * tty_tiocmset - set modem status
2815 * @cmd: command - clear bits, set bits or set all
2816 * @p: pointer to desired bits
2818 * Set the modem status bits from the tty driver if the feature
2819 * is supported. Return -ENOTTY if it is not available.
2821 * Locking: none (up to the driver)
2824 static int tty_tiocmset(struct tty_struct *tty, unsigned int cmd,
2828 unsigned int set, clear, val;
2830 if (tty->ops->tiocmset == NULL)
2833 retval = get_user(val, p);
2849 set &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
2850 clear &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
2851 return tty->ops->tiocmset(tty, set, clear);
2854 static int tty_tiocgicount(struct tty_struct *tty, void __user *arg)
2856 int retval = -EINVAL;
2857 struct serial_icounter_struct icount;
2858 memset(&icount, 0, sizeof(icount));
2859 if (tty->ops->get_icount)
2860 retval = tty->ops->get_icount(tty, &icount);
2863 if (copy_to_user(arg, &icount, sizeof(icount)))
2868 static void tty_warn_deprecated_flags(struct serial_struct __user *ss)
2870 static DEFINE_RATELIMIT_STATE(depr_flags,
2871 DEFAULT_RATELIMIT_INTERVAL,
2872 DEFAULT_RATELIMIT_BURST);
2873 char comm[TASK_COMM_LEN];
2876 if (get_user(flags, &ss->flags))
2879 flags &= ASYNC_DEPRECATED;
2881 if (flags && __ratelimit(&depr_flags))
2882 pr_warning("%s: '%s' is using deprecated serial flags (with no effect): %.8x\n",
2883 __func__, get_task_comm(comm, current), flags);
2887 * if pty, return the slave side (real_tty)
2888 * otherwise, return self
2890 static struct tty_struct *tty_pair_get_tty(struct tty_struct *tty)
2892 if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
2893 tty->driver->subtype == PTY_TYPE_MASTER)
2899 * Split this up, as gcc can choke on it otherwise..
2901 long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2903 struct tty_struct *tty = file_tty(file);
2904 struct tty_struct *real_tty;
2905 void __user *p = (void __user *)arg;
2907 struct tty_ldisc *ld;
2909 if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl"))
2912 real_tty = tty_pair_get_tty(tty);
2915 * Factor out some common prep work
2923 retval = tty_check_change(tty);
2926 if (cmd != TIOCCBRK) {
2927 tty_wait_until_sent(tty, 0);
2928 if (signal_pending(current))
2939 return tiocsti(tty, p);
2941 return tiocgwinsz(real_tty, p);
2943 return tiocswinsz(real_tty, p);
2945 return real_tty != tty ? -EINVAL : tioccons(file);
2947 return fionbio(file, p);
2949 set_bit(TTY_EXCLUSIVE, &tty->flags);
2952 clear_bit(TTY_EXCLUSIVE, &tty->flags);
2956 int excl = test_bit(TTY_EXCLUSIVE, &tty->flags);
2957 return put_user(excl, (int __user *)p);
2960 if (current->signal->tty != tty)
2965 return tiocsctty(real_tty, file, arg);
2967 return tiocgpgrp(tty, real_tty, p);
2969 return tiocspgrp(tty, real_tty, p);
2971 return tiocgsid(tty, real_tty, p);
2973 return tiocgetd(tty, p);
2975 return tiocsetd(tty, p);
2977 if (!capable(CAP_SYS_ADMIN))
2983 unsigned int ret = new_encode_dev(tty_devnum(real_tty));
2984 return put_user(ret, (unsigned int __user *)p);
2989 case TIOCSBRK: /* Turn break on, unconditionally */
2990 if (tty->ops->break_ctl)
2991 return tty->ops->break_ctl(tty, -1);
2993 case TIOCCBRK: /* Turn break off, unconditionally */
2994 if (tty->ops->break_ctl)
2995 return tty->ops->break_ctl(tty, 0);
2997 case TCSBRK: /* SVID version: non-zero arg --> no break */
2998 /* non-zero arg means wait for all output data
2999 * to be sent (performed above) but don't send break.
3000 * This is used by the tcdrain() termios function.
3003 return send_break(tty, 250);
3005 case TCSBRKP: /* support for POSIX tcsendbreak() */
3006 return send_break(tty, arg ? arg*100 : 250);
3009 return tty_tiocmget(tty, p);
3013 return tty_tiocmset(tty, cmd, p);
3015 retval = tty_tiocgicount(tty, p);
3016 /* For the moment allow fall through to the old method */
3017 if (retval != -EINVAL)
3024 /* flush tty buffer and allow ldisc to process ioctl */
3025 tty_buffer_flush(tty, NULL);
3030 tty_warn_deprecated_flags(p);
3033 if (tty->ops->ioctl) {
3034 retval = tty->ops->ioctl(tty, cmd, arg);
3035 if (retval != -ENOIOCTLCMD)
3038 ld = tty_ldisc_ref_wait(tty);
3040 return hung_up_tty_ioctl(file, cmd, arg);
3042 if (ld->ops->ioctl) {
3043 retval = ld->ops->ioctl(tty, file, cmd, arg);
3044 if (retval == -ENOIOCTLCMD)
3047 tty_ldisc_deref(ld);
3051 #ifdef CONFIG_COMPAT
3052 static long tty_compat_ioctl(struct file *file, unsigned int cmd,
3055 struct tty_struct *tty = file_tty(file);
3056 struct tty_ldisc *ld;
3057 int retval = -ENOIOCTLCMD;
3059 if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl"))
3062 if (tty->ops->compat_ioctl) {
3063 retval = tty->ops->compat_ioctl(tty, cmd, arg);
3064 if (retval != -ENOIOCTLCMD)
3068 ld = tty_ldisc_ref_wait(tty);
3070 return hung_up_tty_compat_ioctl(file, cmd, arg);
3071 if (ld->ops->compat_ioctl)
3072 retval = ld->ops->compat_ioctl(tty, file, cmd, arg);
3074 retval = n_tty_compat_ioctl_helper(tty, file, cmd, arg);
3075 tty_ldisc_deref(ld);
3081 static int this_tty(const void *t, struct file *file, unsigned fd)
3083 if (likely(file->f_op->read != tty_read))
3085 return file_tty(file) != t ? 0 : fd + 1;
3089 * This implements the "Secure Attention Key" --- the idea is to
3090 * prevent trojan horses by killing all processes associated with this
3091 * tty when the user hits the "Secure Attention Key". Required for
3092 * super-paranoid applications --- see the Orange Book for more details.
3094 * This code could be nicer; ideally it should send a HUP, wait a few
3095 * seconds, then send a INT, and then a KILL signal. But you then
3096 * have to coordinate with the init process, since all processes associated
3097 * with the current tty must be dead before the new getty is allowed
3100 * Now, if it would be correct ;-/ The current code has a nasty hole -
3101 * it doesn't catch files in flight. We may send the descriptor to ourselves
3102 * via AF_UNIX socket, close it and later fetch from socket. FIXME.
3104 * Nasty bug: do_SAK is being called in interrupt context. This can
3105 * deadlock. We punt it up to process context. AKPM - 16Mar2001
3107 void __do_SAK(struct tty_struct *tty)
3112 struct task_struct *g, *p;
3113 struct pid *session;
3115 unsigned long flags;
3120 spin_lock_irqsave(&tty->ctrl_lock, flags);
3121 session = get_pid(tty->session);
3122 spin_unlock_irqrestore(&tty->ctrl_lock, flags);
3124 tty_ldisc_flush(tty);
3126 tty_driver_flush_buffer(tty);
3128 read_lock(&tasklist_lock);
3129 /* Kill the entire session */
3130 do_each_pid_task(session, PIDTYPE_SID, p) {
3131 tty_notice(tty, "SAK: killed process %d (%s): by session\n",
3132 task_pid_nr(p), p->comm);
3133 send_sig(SIGKILL, p, 1);
3134 } while_each_pid_task(session, PIDTYPE_SID, p);
3136 /* Now kill any processes that happen to have the tty open */
3137 do_each_thread(g, p) {
3138 if (p->signal->tty == tty) {
3139 tty_notice(tty, "SAK: killed process %d (%s): by controlling tty\n",
3140 task_pid_nr(p), p->comm);
3141 send_sig(SIGKILL, p, 1);
3145 i = iterate_fd(p->files, 0, this_tty, tty);
3147 tty_notice(tty, "SAK: killed process %d (%s): by fd#%d\n",
3148 task_pid_nr(p), p->comm, i - 1);
3149 force_sig(SIGKILL, p);
3152 } while_each_thread(g, p);
3153 read_unlock(&tasklist_lock);
3158 static void do_SAK_work(struct work_struct *work)
3160 struct tty_struct *tty =
3161 container_of(work, struct tty_struct, SAK_work);
3166 * The tq handling here is a little racy - tty->SAK_work may already be queued.
3167 * Fortunately we don't need to worry, because if ->SAK_work is already queued,
3168 * the values which we write to it will be identical to the values which it
3169 * already has. --akpm
3171 void do_SAK(struct tty_struct *tty)
3175 schedule_work(&tty->SAK_work);
3178 EXPORT_SYMBOL(do_SAK);
3180 static int dev_match_devt(struct device *dev, const void *data)
3182 const dev_t *devt = data;
3183 return dev->devt == *devt;
3186 /* Must put_device() after it's unused! */
3187 static struct device *tty_get_device(struct tty_struct *tty)
3189 dev_t devt = tty_devnum(tty);
3190 return class_find_device(tty_class, NULL, &devt, dev_match_devt);
3197 * This subroutine allocates and initializes a tty structure.
3199 * Locking: none - tty in question is not exposed at this point
3202 struct tty_struct *alloc_tty_struct(struct tty_driver *driver, int idx)
3204 struct tty_struct *tty;
3206 tty = kzalloc(sizeof(*tty), GFP_KERNEL);
3210 kref_init(&tty->kref);
3211 tty->magic = TTY_MAGIC;
3212 if (tty_ldisc_init(tty)) {
3216 tty->session = NULL;
3218 mutex_init(&tty->legacy_mutex);
3219 mutex_init(&tty->throttle_mutex);
3220 init_rwsem(&tty->termios_rwsem);
3221 mutex_init(&tty->winsize_mutex);
3222 init_ldsem(&tty->ldisc_sem);
3223 init_waitqueue_head(&tty->write_wait);
3224 init_waitqueue_head(&tty->read_wait);
3225 INIT_WORK(&tty->hangup_work, do_tty_hangup);
3226 mutex_init(&tty->atomic_write_lock);
3227 spin_lock_init(&tty->ctrl_lock);
3228 spin_lock_init(&tty->flow_lock);
3229 spin_lock_init(&tty->files_lock);
3230 INIT_LIST_HEAD(&tty->tty_files);
3231 INIT_WORK(&tty->SAK_work, do_SAK_work);
3233 tty->driver = driver;
3234 tty->ops = driver->ops;
3236 tty_line_name(driver, idx, tty->name);
3237 tty->dev = tty_get_device(tty);
3243 * tty_put_char - write one character to a tty
3247 * Write one byte to the tty using the provided put_char method
3248 * if present. Returns the number of characters successfully output.
3250 * Note: the specific put_char operation in the driver layer may go
3251 * away soon. Don't call it directly, use this method
3254 int tty_put_char(struct tty_struct *tty, unsigned char ch)
3256 if (tty->ops->put_char)
3257 return tty->ops->put_char(tty, ch);
3258 return tty->ops->write(tty, &ch, 1);
3260 EXPORT_SYMBOL_GPL(tty_put_char);
3262 struct class *tty_class;
3264 static int tty_cdev_add(struct tty_driver *driver, dev_t dev,
3265 unsigned int index, unsigned int count)
3269 /* init here, since reused cdevs cause crashes */
3270 driver->cdevs[index] = cdev_alloc();
3271 if (!driver->cdevs[index])
3273 driver->cdevs[index]->ops = &tty_fops;
3274 driver->cdevs[index]->owner = driver->owner;
3275 err = cdev_add(driver->cdevs[index], dev, count);
3277 kobject_put(&driver->cdevs[index]->kobj);
3282 * tty_register_device - register a tty device
3283 * @driver: the tty driver that describes the tty device
3284 * @index: the index in the tty driver for this tty device
3285 * @device: a struct device that is associated with this tty device.
3286 * This field is optional, if there is no known struct device
3287 * for this tty device it can be set to NULL safely.
3289 * Returns a pointer to the struct device for this tty device
3290 * (or ERR_PTR(-EFOO) on error).
3292 * This call is required to be made to register an individual tty device
3293 * if the tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set. If
3294 * that bit is not set, this function should not be called by a tty
3300 struct device *tty_register_device(struct tty_driver *driver, unsigned index,
3301 struct device *device)
3303 return tty_register_device_attr(driver, index, device, NULL, NULL);
3305 EXPORT_SYMBOL(tty_register_device);
3307 static void tty_device_create_release(struct device *dev)
3309 dev_dbg(dev, "releasing...\n");
3314 * tty_register_device_attr - register a tty device
3315 * @driver: the tty driver that describes the tty device
3316 * @index: the index in the tty driver for this tty device
3317 * @device: a struct device that is associated with this tty device.
3318 * This field is optional, if there is no known struct device
3319 * for this tty device it can be set to NULL safely.
3320 * @drvdata: Driver data to be set to device.
3321 * @attr_grp: Attribute group to be set on device.
3323 * Returns a pointer to the struct device for this tty device
3324 * (or ERR_PTR(-EFOO) on error).
3326 * This call is required to be made to register an individual tty device
3327 * if the tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set. If
3328 * that bit is not set, this function should not be called by a tty
3333 struct device *tty_register_device_attr(struct tty_driver *driver,
3334 unsigned index, struct device *device,
3336 const struct attribute_group **attr_grp)
3339 dev_t devt = MKDEV(driver->major, driver->minor_start) + index;
3340 struct device *dev = NULL;
3341 int retval = -ENODEV;
3344 if (index >= driver->num) {
3345 pr_err("%s: Attempt to register invalid tty line number (%d)\n",
3346 driver->name, index);
3347 return ERR_PTR(-EINVAL);
3350 if (driver->type == TTY_DRIVER_TYPE_PTY)
3351 pty_line_name(driver, index, name);
3353 tty_line_name(driver, index, name);
3355 if (!(driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
3356 retval = tty_cdev_add(driver, devt, index, 1);
3362 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3369 dev->class = tty_class;
3370 dev->parent = device;
3371 dev->release = tty_device_create_release;
3372 dev_set_name(dev, "%s", name);
3373 dev->groups = attr_grp;
3374 dev_set_drvdata(dev, drvdata);
3376 retval = device_register(dev);
3385 cdev_del(driver->cdevs[index]);
3386 driver->cdevs[index] = NULL;
3388 return ERR_PTR(retval);
3390 EXPORT_SYMBOL_GPL(tty_register_device_attr);
3393 * tty_unregister_device - unregister a tty device
3394 * @driver: the tty driver that describes the tty device
3395 * @index: the index in the tty driver for this tty device
3397 * If a tty device is registered with a call to tty_register_device() then
3398 * this function must be called when the tty device is gone.
3403 void tty_unregister_device(struct tty_driver *driver, unsigned index)
3405 device_destroy(tty_class,
3406 MKDEV(driver->major, driver->minor_start) + index);
3407 if (!(driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
3408 cdev_del(driver->cdevs[index]);
3409 driver->cdevs[index] = NULL;
3412 EXPORT_SYMBOL(tty_unregister_device);
3415 * __tty_alloc_driver -- allocate tty driver
3416 * @lines: count of lines this driver can handle at most
3417 * @owner: module which is repsonsible for this driver
3418 * @flags: some of TTY_DRIVER_* flags, will be set in driver->flags
3420 * This should not be called directly, some of the provided macros should be
3421 * used instead. Use IS_ERR and friends on @retval.
3423 struct tty_driver *__tty_alloc_driver(unsigned int lines, struct module *owner,
3424 unsigned long flags)
3426 struct tty_driver *driver;
3427 unsigned int cdevs = 1;
3430 if (!lines || (flags & TTY_DRIVER_UNNUMBERED_NODE && lines > 1))
3431 return ERR_PTR(-EINVAL);
3433 driver = kzalloc(sizeof(struct tty_driver), GFP_KERNEL);
3435 return ERR_PTR(-ENOMEM);
3437 kref_init(&driver->kref);
3438 driver->magic = TTY_DRIVER_MAGIC;
3439 driver->num = lines;
3440 driver->owner = owner;
3441 driver->flags = flags;
3443 if (!(flags & TTY_DRIVER_DEVPTS_MEM)) {
3444 driver->ttys = kcalloc(lines, sizeof(*driver->ttys),
3446 driver->termios = kcalloc(lines, sizeof(*driver->termios),
3448 if (!driver->ttys || !driver->termios) {
3454 if (!(flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
3455 driver->ports = kcalloc(lines, sizeof(*driver->ports),
3457 if (!driver->ports) {
3464 driver->cdevs = kcalloc(cdevs, sizeof(*driver->cdevs), GFP_KERNEL);
3465 if (!driver->cdevs) {
3472 kfree(driver->ports);
3473 kfree(driver->ttys);
3474 kfree(driver->termios);
3475 kfree(driver->cdevs);
3477 return ERR_PTR(err);
3479 EXPORT_SYMBOL(__tty_alloc_driver);
3481 static void destruct_tty_driver(struct kref *kref)
3483 struct tty_driver *driver = container_of(kref, struct tty_driver, kref);
3485 struct ktermios *tp;
3487 if (driver->flags & TTY_DRIVER_INSTALLED) {
3489 * Free the termios and termios_locked structures because
3490 * we don't want to get memory leaks when modular tty
3491 * drivers are removed from the kernel.
3493 for (i = 0; i < driver->num; i++) {
3494 tp = driver->termios[i];
3496 driver->termios[i] = NULL;
3499 if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV))
3500 tty_unregister_device(driver, i);
3502 proc_tty_unregister_driver(driver);
3503 if (driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)
3504 cdev_del(driver->cdevs[0]);
3506 kfree(driver->cdevs);
3507 kfree(driver->ports);
3508 kfree(driver->termios);
3509 kfree(driver->ttys);
3513 void tty_driver_kref_put(struct tty_driver *driver)
3515 kref_put(&driver->kref, destruct_tty_driver);
3517 EXPORT_SYMBOL(tty_driver_kref_put);
3519 void tty_set_operations(struct tty_driver *driver,
3520 const struct tty_operations *op)
3524 EXPORT_SYMBOL(tty_set_operations);
3526 void put_tty_driver(struct tty_driver *d)
3528 tty_driver_kref_put(d);
3530 EXPORT_SYMBOL(put_tty_driver);
3533 * Called by a tty driver to register itself.
3535 int tty_register_driver(struct tty_driver *driver)
3542 if (!driver->major) {
3543 error = alloc_chrdev_region(&dev, driver->minor_start,
3544 driver->num, driver->name);
3546 driver->major = MAJOR(dev);
3547 driver->minor_start = MINOR(dev);
3550 dev = MKDEV(driver->major, driver->minor_start);
3551 error = register_chrdev_region(dev, driver->num, driver->name);
3556 if (driver->flags & TTY_DRIVER_DYNAMIC_ALLOC) {
3557 error = tty_cdev_add(driver, dev, 0, driver->num);
3559 goto err_unreg_char;
3562 mutex_lock(&tty_mutex);
3563 list_add(&driver->tty_drivers, &tty_drivers);
3564 mutex_unlock(&tty_mutex);
3566 if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV)) {
3567 for (i = 0; i < driver->num; i++) {
3568 d = tty_register_device(driver, i, NULL);
3571 goto err_unreg_devs;
3575 proc_tty_register_driver(driver);
3576 driver->flags |= TTY_DRIVER_INSTALLED;
3580 for (i--; i >= 0; i--)
3581 tty_unregister_device(driver, i);
3583 mutex_lock(&tty_mutex);
3584 list_del(&driver->tty_drivers);
3585 mutex_unlock(&tty_mutex);
3588 unregister_chrdev_region(dev, driver->num);
3592 EXPORT_SYMBOL(tty_register_driver);
3595 * Called by a tty driver to unregister itself.
3597 int tty_unregister_driver(struct tty_driver *driver)
3601 if (driver->refcount)
3604 unregister_chrdev_region(MKDEV(driver->major, driver->minor_start),
3606 mutex_lock(&tty_mutex);
3607 list_del(&driver->tty_drivers);
3608 mutex_unlock(&tty_mutex);
3612 EXPORT_SYMBOL(tty_unregister_driver);
3614 dev_t tty_devnum(struct tty_struct *tty)
3616 return MKDEV(tty->driver->major, tty->driver->minor_start) + tty->index;
3618 EXPORT_SYMBOL(tty_devnum);
3620 void tty_default_fops(struct file_operations *fops)
3626 * Initialize the console device. This is called *early*, so
3627 * we can't necessarily depend on lots of kernel help here.
3628 * Just do some early initializations, and do the complex setup
3631 void __init console_init(void)
3635 /* Setup the default TTY line discipline. */
3639 * set up the console device so that later boot sequences can
3640 * inform about problems etc..
3642 call = __con_initcall_start;
3643 while (call < __con_initcall_end) {
3649 static char *tty_devnode(struct device *dev, umode_t *mode)
3653 if (dev->devt == MKDEV(TTYAUX_MAJOR, 0) ||
3654 dev->devt == MKDEV(TTYAUX_MAJOR, 2))
3659 static int __init tty_class_init(void)
3661 tty_class = class_create(THIS_MODULE, "tty");
3662 if (IS_ERR(tty_class))
3663 return PTR_ERR(tty_class);
3664 tty_class->devnode = tty_devnode;
3668 postcore_initcall(tty_class_init);
3670 /* 3/2004 jmc: why do these devices exist? */
3671 static struct cdev tty_cdev, console_cdev;
3673 static ssize_t show_cons_active(struct device *dev,
3674 struct device_attribute *attr, char *buf)
3676 struct console *cs[16];
3682 for_each_console(c) {
3687 if ((c->flags & CON_ENABLED) == 0)
3690 if (i >= ARRAY_SIZE(cs))
3694 int index = cs[i]->index;
3695 struct tty_driver *drv = cs[i]->device(cs[i], &index);
3697 /* don't resolve tty0 as some programs depend on it */
3698 if (drv && (cs[i]->index > 0 || drv->major != TTY_MAJOR))
3699 count += tty_line_name(drv, index, buf + count);
3701 count += sprintf(buf + count, "%s%d",
3702 cs[i]->name, cs[i]->index);
3704 count += sprintf(buf + count, "%c", i ? ' ':'\n');
3710 static DEVICE_ATTR(active, S_IRUGO, show_cons_active, NULL);
3712 static struct attribute *cons_dev_attrs[] = {
3713 &dev_attr_active.attr,
3717 ATTRIBUTE_GROUPS(cons_dev);
3719 static struct device *consdev;
3721 void console_sysfs_notify(void)
3724 sysfs_notify(&consdev->kobj, NULL, "active");
3728 * Ok, now we can initialize the rest of the tty devices and can count
3729 * on memory allocations, interrupts etc..
3731 int __init tty_init(void)
3734 cdev_init(&tty_cdev, &tty_fops);
3735 if (cdev_add(&tty_cdev, MKDEV(TTYAUX_MAJOR, 0), 1) ||
3736 register_chrdev_region(MKDEV(TTYAUX_MAJOR, 0), 1, "/dev/tty") < 0)
3737 panic("Couldn't register /dev/tty driver\n");
3738 device_create(tty_class, NULL, MKDEV(TTYAUX_MAJOR, 0), NULL, "tty");
3740 cdev_init(&console_cdev, &console_fops);
3741 if (cdev_add(&console_cdev, MKDEV(TTYAUX_MAJOR, 1), 1) ||
3742 register_chrdev_region(MKDEV(TTYAUX_MAJOR, 1), 1, "/dev/console") < 0)
3743 panic("Couldn't register /dev/console driver\n");
3744 consdev = device_create_with_groups(tty_class, NULL,
3745 MKDEV(TTYAUX_MAJOR, 1), NULL,
3746 cons_dev_groups, "console");
3747 if (IS_ERR(consdev))
3751 vty_init(&console_fops);