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