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