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