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