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