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