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