This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / 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() -- Andrew Morton <andrewm@uow.edu.eu> 17Mar01
66  */
67
68 #include <linux/config.h>
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/console.h>
82 #include <linux/timer.h>
83 #include <linux/ctype.h>
84 #include <linux/kd.h>
85 #include <linux/mm.h>
86 #include <linux/string.h>
87 #include <linux/slab.h>
88 #include <linux/poll.h>
89 #include <linux/proc_fs.h>
90 #include <linux/init.h>
91 #include <linux/module.h>
92 #include <linux/smp_lock.h>
93 #include <linux/device.h>
94 #include <linux/idr.h>
95
96 #include <asm/uaccess.h>
97 #include <asm/system.h>
98 #include <asm/bitops.h>
99
100 #include <linux/kbd_kern.h>
101 #include <linux/vt_kern.h>
102 #include <linux/selection.h>
103 #include <linux/devfs_fs_kernel.h>
104
105 #include <linux/kmod.h>
106
107 #undef TTY_DEBUG_HANGUP
108
109 #define TTY_PARANOIA_CHECK 1
110 #define CHECK_TTY_COUNT 1
111
112 struct termios tty_std_termios = {      /* for the benefit of tty drivers  */
113         .c_iflag = ICRNL | IXON,
114         .c_oflag = OPOST | ONLCR,
115         .c_cflag = B38400 | CS8 | CREAD | HUPCL,
116         .c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK |
117                    ECHOCTL | ECHOKE | IEXTEN,
118         .c_cc = INIT_C_CC
119 };
120
121 EXPORT_SYMBOL(tty_std_termios);
122
123 LIST_HEAD(tty_drivers);                 /* linked list of tty drivers */
124 struct tty_ldisc ldiscs[NR_LDISCS];     /* line disc dispatch table     */
125
126 /* Semaphore to protect creating and releasing a tty */
127 DECLARE_MUTEX(tty_sem);
128
129 #ifdef CONFIG_UNIX98_PTYS
130 extern struct tty_driver *ptm_driver;   /* Unix98 pty masters; for /dev/ptmx */
131 extern int pty_limit;           /* Config limit on Unix98 ptys */
132 static DEFINE_IDR(allocated_ptys);
133 static DECLARE_MUTEX(allocated_ptys_lock);
134 #endif
135
136 extern void disable_early_printk(void);
137
138 static void initialize_tty_struct(struct tty_struct *tty);
139
140 static ssize_t tty_read(struct file *, char __user *, size_t, loff_t *);
141 static ssize_t tty_write(struct file *, const char __user *, size_t, loff_t *);
142 ssize_t redirected_tty_write(struct file *, const char __user *, size_t, loff_t *);
143 static unsigned int tty_poll(struct file *, poll_table *);
144 static int tty_open(struct inode *, struct file *);
145 static int tty_release(struct inode *, struct file *);
146 int tty_ioctl(struct inode * inode, struct file * file,
147               unsigned int cmd, unsigned long arg);
148 static int tty_fasync(int fd, struct file * filp, int on);
149 extern void rs_360_init(void);
150 static void release_mem(struct tty_struct *tty, int idx);
151
152
153 static struct tty_struct *alloc_tty_struct(void)
154 {
155         struct tty_struct *tty;
156
157         tty = kmalloc(sizeof(struct tty_struct), GFP_KERNEL);
158         if (tty)
159                 memset(tty, 0, sizeof(struct tty_struct));
160         return tty;
161 }
162
163 static inline void free_tty_struct(struct tty_struct *tty)
164 {
165         kfree(tty);
166 }
167
168 #define TTY_NUMBER(tty) ((tty)->index + (tty)->driver->name_base)
169
170 char *tty_name(struct tty_struct *tty, char *buf)
171 {
172         if (!tty) /* Hmm.  NULL pointer.  That's fun. */
173                 strcpy(buf, "NULL tty");
174         else
175                 strcpy(buf, tty->name);
176         return buf;
177 }
178
179 EXPORT_SYMBOL(tty_name);
180
181 inline int tty_paranoia_check(struct tty_struct *tty, struct inode *inode,
182                               const char *routine)
183 {
184 #ifdef TTY_PARANOIA_CHECK
185         if (!tty) {
186                 printk(KERN_WARNING
187                         "null TTY for (%d:%d) in %s\n",
188                         imajor(inode), iminor(inode), routine);
189                 return 1;
190         }
191         if (tty->magic != TTY_MAGIC) {
192                 printk(KERN_WARNING
193                         "bad magic number for tty struct (%d:%d) in %s\n",
194                         imajor(inode), iminor(inode), routine);
195                 return 1;
196         }
197 #endif
198         return 0;
199 }
200
201 static int check_tty_count(struct tty_struct *tty, const char *routine)
202 {
203 #ifdef CHECK_TTY_COUNT
204         struct list_head *p;
205         int count = 0;
206         
207         file_list_lock();
208         list_for_each(p, &tty->tty_files) {
209                 count++;
210         }
211         file_list_unlock();
212         if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
213             tty->driver->subtype == PTY_TYPE_SLAVE &&
214             tty->link && tty->link->count)
215                 count++;
216         if (tty->count != count) {
217                 printk(KERN_WARNING "Warning: dev (%s) tty->count(%d) "
218                                     "!= #fd's(%d) in %s\n",
219                        tty->name, tty->count, count, routine);
220                 return count;
221        }        
222 #endif
223         return 0;
224 }
225
226 int tty_register_ldisc(int disc, struct tty_ldisc *new_ldisc)
227 {
228         if (disc < N_TTY || disc >= NR_LDISCS)
229                 return -EINVAL;
230         
231         if (new_ldisc) {
232                 ldiscs[disc] = *new_ldisc;
233                 ldiscs[disc].flags |= LDISC_FLAG_DEFINED;
234                 ldiscs[disc].num = disc;
235         } else
236                 memset(&ldiscs[disc], 0, sizeof(struct tty_ldisc));
237         
238         return 0;
239 }
240
241 EXPORT_SYMBOL(tty_register_ldisc);
242
243 /* Set the discipline of a tty line. */
244 static int tty_set_ldisc(struct tty_struct *tty, int ldisc)
245 {
246         int     retval = 0;
247         struct  tty_ldisc o_ldisc;
248         char buf[64];
249
250         if ((ldisc < N_TTY) || (ldisc >= NR_LDISCS))
251                 return -EINVAL;
252         /* Eduardo Blanco <ejbs@cs.cs.com.uy> */
253         /* Cyrus Durgin <cider@speakeasy.org> */
254         if (!(ldiscs[ldisc].flags & LDISC_FLAG_DEFINED)) {
255                 request_module("tty-ldisc-%d", ldisc);
256         }
257         if (!(ldiscs[ldisc].flags & LDISC_FLAG_DEFINED))
258                 return -EINVAL;
259
260         if (tty->ldisc.num == ldisc)
261                 return 0;       /* We are already in the desired discipline */
262
263         if (!try_module_get(ldiscs[ldisc].owner))
264                 return -EINVAL;
265         
266         o_ldisc = tty->ldisc;
267
268         tty_wait_until_sent(tty, 0);
269         
270         /* Shutdown the current discipline. */
271         if (tty->ldisc.close)
272                 (tty->ldisc.close)(tty);
273
274         /* Now set up the new line discipline. */
275         tty->ldisc = ldiscs[ldisc];
276         tty->termios->c_line = ldisc;
277         if (tty->ldisc.open)
278                 retval = (tty->ldisc.open)(tty);
279         if (retval < 0) {
280                 tty->ldisc = o_ldisc;
281                 tty->termios->c_line = tty->ldisc.num;
282                 if (tty->ldisc.open && (tty->ldisc.open(tty) < 0)) {
283                         tty->ldisc = ldiscs[N_TTY];
284                         tty->termios->c_line = N_TTY;
285                         if (tty->ldisc.open) {
286                                 int r = tty->ldisc.open(tty);
287
288                                 if (r < 0)
289                                         panic("Couldn't open N_TTY ldisc for "
290                                               "%s --- error %d.",
291                                               tty_name(tty, buf), r);
292                         }
293                 }
294         } else {
295                 module_put(o_ldisc.owner);
296         }
297         
298         if (tty->ldisc.num != o_ldisc.num && tty->driver->set_ldisc)
299                 tty->driver->set_ldisc(tty);
300         return retval;
301 }
302
303 /*
304  * This routine returns a tty driver structure, given a device number
305  */
306 struct tty_driver *get_tty_driver(dev_t device, int *index)
307 {
308         struct tty_driver *p;
309
310         list_for_each_entry(p, &tty_drivers, tty_drivers) {
311                 dev_t base = MKDEV(p->major, p->minor_start);
312                 if (device < base || device >= base + p->num)
313                         continue;
314                 *index = device - base;
315                 return p;
316         }
317         return NULL;
318 }
319
320 /*
321  * If we try to write to, or set the state of, a terminal and we're
322  * not in the foreground, send a SIGTTOU.  If the signal is blocked or
323  * ignored, go ahead and perform the operation.  (POSIX 7.2)
324  */
325 int tty_check_change(struct tty_struct * tty)
326 {
327         if (current->signal->tty != tty)
328                 return 0;
329         if (tty->pgrp <= 0) {
330                 printk(KERN_WARNING "tty_check_change: tty->pgrp <= 0!\n");
331                 return 0;
332         }
333         if (process_group(current) == tty->pgrp)
334                 return 0;
335         if (is_ignored(SIGTTOU))
336                 return 0;
337         if (is_orphaned_pgrp(process_group(current)))
338                 return -EIO;
339         (void) kill_pg(process_group(current), SIGTTOU, 1);
340         return -ERESTARTSYS;
341 }
342
343 EXPORT_SYMBOL(tty_check_change);
344
345 static ssize_t hung_up_tty_read(struct file * file, char __user * buf,
346                                 size_t count, loff_t *ppos)
347 {
348         /* Can't seek (pread) on ttys.  */
349         if (ppos != &file->f_pos)
350                 return -ESPIPE;
351         return 0;
352 }
353
354 static ssize_t hung_up_tty_write(struct file * file, const char __user * buf,
355                                  size_t count, loff_t *ppos)
356 {
357         /* Can't seek (pwrite) on ttys.  */
358         if (ppos != &file->f_pos)
359                 return -ESPIPE;
360         return -EIO;
361 }
362
363 /* No kernel lock held - none needed ;) */
364 static unsigned int hung_up_tty_poll(struct file * filp, poll_table * wait)
365 {
366         return POLLIN | POLLOUT | POLLERR | POLLHUP | POLLRDNORM | POLLWRNORM;
367 }
368
369 static int hung_up_tty_ioctl(struct inode * inode, struct file * file,
370                              unsigned int cmd, unsigned long arg)
371 {
372         return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
373 }
374
375 static struct file_operations tty_fops = {
376         .llseek         = no_llseek,
377         .read           = tty_read,
378         .write          = tty_write,
379         .poll           = tty_poll,
380         .ioctl          = tty_ioctl,
381         .open           = tty_open,
382         .release        = tty_release,
383         .fasync         = tty_fasync,
384 };
385
386 static struct file_operations console_fops = {
387         .llseek         = no_llseek,
388         .read           = tty_read,
389         .write          = redirected_tty_write,
390         .poll           = tty_poll,
391         .ioctl          = tty_ioctl,
392         .open           = tty_open,
393         .release        = tty_release,
394         .fasync         = tty_fasync,
395 };
396
397 static struct file_operations hung_up_tty_fops = {
398         .llseek         = no_llseek,
399         .read           = hung_up_tty_read,
400         .write          = hung_up_tty_write,
401         .poll           = hung_up_tty_poll,
402         .ioctl          = hung_up_tty_ioctl,
403         .release        = tty_release,
404 };
405
406 static spinlock_t redirect_lock = SPIN_LOCK_UNLOCKED;
407 static struct file *redirect;
408 /*
409  * This can be called by the "eventd" kernel thread.  That is process synchronous,
410  * but doesn't hold any locks, so we need to make sure we have the appropriate
411  * locks for what we're doing..
412  */
413 void do_tty_hangup(void *data)
414 {
415         struct tty_struct *tty = (struct tty_struct *) data;
416         struct file * cons_filp = NULL;
417         struct file *filp, *f = NULL;
418         struct task_struct *p;
419         struct pid *pid;
420         int    closecount = 0, n;
421
422         if (!tty)
423                 return;
424
425         /* inuse_filps is protected by the single kernel lock */
426         lock_kernel();
427
428         spin_lock(&redirect_lock);
429         if (redirect && redirect->private_data == tty) {
430                 f = redirect;
431                 redirect = NULL;
432         }
433         spin_unlock(&redirect_lock);
434         
435         check_tty_count(tty, "do_tty_hangup");
436         file_list_lock();
437         list_for_each_entry(filp, &tty->tty_files, f_list) {
438                 if (filp->f_op->write == redirected_tty_write)
439                         cons_filp = filp;
440                 if (filp->f_op->write != tty_write)
441                         continue;
442                 closecount++;
443                 tty_fasync(-1, filp, 0);        /* can't block */
444                 filp->f_op = &hung_up_tty_fops;
445         }
446         file_list_unlock();
447         
448         /* FIXME! What are the locking issues here? This may me overdoing things..
449         * this question is especially important now that we've removed the irqlock. */
450         {
451                 unsigned long flags;
452
453                 local_irq_save(flags); // FIXME: is this safe?
454                 if (tty->ldisc.flush_buffer)
455                         tty->ldisc.flush_buffer(tty);
456                 if (tty->driver->flush_buffer)
457                         tty->driver->flush_buffer(tty);
458                 if ((test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) &&
459                     tty->ldisc.write_wakeup)
460                         (tty->ldisc.write_wakeup)(tty);
461                 local_irq_restore(flags); // FIXME: is this safe?
462         }
463
464         wake_up_interruptible(&tty->write_wait);
465         wake_up_interruptible(&tty->read_wait);
466
467         /*
468          * Shutdown the current line discipline, and reset it to
469          * N_TTY.
470          */
471         if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
472                 *tty->termios = tty->driver->init_termios;
473         if (tty->ldisc.num != ldiscs[N_TTY].num) {
474                 if (tty->ldisc.close)
475                         (tty->ldisc.close)(tty);
476                 module_put(tty->ldisc.owner);
477                 
478                 tty->ldisc = ldiscs[N_TTY];
479                 tty->termios->c_line = N_TTY;
480                 if (tty->ldisc.open) {
481                         int i = (tty->ldisc.open)(tty);
482                         if (i < 0)
483                                 printk(KERN_ERR "do_tty_hangup: N_TTY open: "
484                                                 "error %d\n", -i);
485                 }
486         }
487         
488         read_lock(&tasklist_lock);
489         if (tty->session > 0) {
490                 struct list_head *l;
491                 for_each_task_pid(tty->session, PIDTYPE_SID, p, l, pid) {
492                         if (p->signal->tty == tty)
493                                 p->signal->tty = NULL;
494                         if (!p->signal->leader)
495                                 continue;
496                         send_group_sig_info(SIGHUP, SEND_SIG_PRIV, p);
497                         send_group_sig_info(SIGCONT, SEND_SIG_PRIV, p);
498                         if (tty->pgrp > 0)
499                                 p->signal->tty_old_pgrp = tty->pgrp;
500                 }
501         }
502         read_unlock(&tasklist_lock);
503
504         tty->flags = 0;
505         tty->session = 0;
506         tty->pgrp = -1;
507         tty->ctrl_status = 0;
508         /*
509          *      If one of the devices matches a console pointer, we
510          *      cannot just call hangup() because that will cause
511          *      tty->count and state->count to go out of sync.
512          *      So we just call close() the right number of times.
513          */
514         if (cons_filp) {
515                 if (tty->driver->close)
516                         for (n = 0; n < closecount; n++)
517                                 tty->driver->close(tty, cons_filp);
518         } else if (tty->driver->hangup)
519                 (tty->driver->hangup)(tty);
520         unlock_kernel();
521         if (f)
522                 fput(f);
523 }
524
525 void tty_hangup(struct tty_struct * tty)
526 {
527 #ifdef TTY_DEBUG_HANGUP
528         char    buf[64];
529         
530         printk(KERN_DEBUG "%s hangup...\n", tty_name(tty, buf));
531 #endif
532         schedule_work(&tty->hangup_work);
533 }
534
535 EXPORT_SYMBOL(tty_hangup);
536
537 void tty_vhangup(struct tty_struct * tty)
538 {
539 #ifdef TTY_DEBUG_HANGUP
540         char    buf[64];
541
542         printk(KERN_DEBUG "%s vhangup...\n", tty_name(tty, buf));
543 #endif
544         do_tty_hangup((void *) tty);
545 }
546 EXPORT_SYMBOL(tty_vhangup);
547
548 int tty_hung_up_p(struct file * filp)
549 {
550         return (filp->f_op == &hung_up_tty_fops);
551 }
552
553 EXPORT_SYMBOL(tty_hung_up_p);
554
555 /*
556  * This function is typically called only by the session leader, when
557  * it wants to disassociate itself from its controlling tty.
558  *
559  * It performs the following functions:
560  *      (1)  Sends a SIGHUP and SIGCONT to the foreground process group
561  *      (2)  Clears the tty from being controlling the session
562  *      (3)  Clears the controlling tty for all processes in the
563  *              session group.
564  *
565  * The argument on_exit is set to 1 if called when a process is
566  * exiting; it is 0 if called by the ioctl TIOCNOTTY.
567  */
568 void disassociate_ctty(int on_exit)
569 {
570         struct tty_struct *tty;
571         struct task_struct *p;
572         struct list_head *l;
573         struct pid *pid;
574         int tty_pgrp = -1;
575
576         lock_kernel();
577
578         tty = current->signal->tty;
579         if (tty) {
580                 tty_pgrp = tty->pgrp;
581                 if (on_exit && tty->driver->type != TTY_DRIVER_TYPE_PTY)
582                         tty_vhangup(tty);
583         } else {
584                 if (current->signal->tty_old_pgrp) {
585                         kill_pg(current->signal->tty_old_pgrp, SIGHUP, on_exit);
586                         kill_pg(current->signal->tty_old_pgrp, SIGCONT, on_exit);
587                 }
588                 unlock_kernel();        
589                 return;
590         }
591         if (tty_pgrp > 0) {
592                 kill_pg(tty_pgrp, SIGHUP, on_exit);
593                 if (!on_exit)
594                         kill_pg(tty_pgrp, SIGCONT, on_exit);
595         }
596
597         current->signal->tty_old_pgrp = 0;
598         tty->session = 0;
599         tty->pgrp = -1;
600
601         read_lock(&tasklist_lock);
602         for_each_task_pid(current->signal->session, PIDTYPE_SID, p, l, pid)
603                 p->signal->tty = NULL;
604         read_unlock(&tasklist_lock);
605         unlock_kernel();
606 }
607
608 void stop_tty(struct tty_struct *tty)
609 {
610         if (tty->stopped)
611                 return;
612         tty->stopped = 1;
613         if (tty->link && tty->link->packet) {
614                 tty->ctrl_status &= ~TIOCPKT_START;
615                 tty->ctrl_status |= TIOCPKT_STOP;
616                 wake_up_interruptible(&tty->link->read_wait);
617         }
618         if (tty->driver->stop)
619                 (tty->driver->stop)(tty);
620 }
621
622 EXPORT_SYMBOL(stop_tty);
623
624 void start_tty(struct tty_struct *tty)
625 {
626         if (!tty->stopped || tty->flow_stopped)
627                 return;
628         tty->stopped = 0;
629         if (tty->link && tty->link->packet) {
630                 tty->ctrl_status &= ~TIOCPKT_STOP;
631                 tty->ctrl_status |= TIOCPKT_START;
632                 wake_up_interruptible(&tty->link->read_wait);
633         }
634         if (tty->driver->start)
635                 (tty->driver->start)(tty);
636         if ((test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) &&
637             tty->ldisc.write_wakeup)
638                 (tty->ldisc.write_wakeup)(tty);
639         wake_up_interruptible(&tty->write_wait);
640 }
641
642 EXPORT_SYMBOL(start_tty);
643
644 static ssize_t tty_read(struct file * file, char __user * buf, size_t count, 
645                         loff_t *ppos)
646 {
647         int i;
648         struct tty_struct * tty;
649         struct inode *inode;
650
651         /* Can't seek (pread) on ttys.  */
652         if (ppos != &file->f_pos)
653                 return -ESPIPE;
654
655         tty = (struct tty_struct *)file->private_data;
656         inode = file->f_dentry->d_inode;
657         if (tty_paranoia_check(tty, inode, "tty_read"))
658                 return -EIO;
659         if (!tty || (test_bit(TTY_IO_ERROR, &tty->flags)))
660                 return -EIO;
661
662         lock_kernel();
663         if (tty->ldisc.read)
664                 i = (tty->ldisc.read)(tty,file,buf,count);
665         else
666                 i = -EIO;
667         unlock_kernel();
668         if (i > 0)
669                 inode->i_atime = CURRENT_TIME;
670         return i;
671 }
672
673 /*
674  * Split writes up in sane blocksizes to avoid
675  * denial-of-service type attacks
676  */
677 static inline ssize_t do_tty_write(
678         ssize_t (*write)(struct tty_struct *, struct file *, const unsigned char __user *, size_t),
679         struct tty_struct *tty,
680         struct file *file,
681         const unsigned char __user *buf,
682         size_t count)
683 {
684         ssize_t ret = 0, written = 0;
685         
686         if (down_interruptible(&tty->atomic_write)) {
687                 return -ERESTARTSYS;
688         }
689         if ( test_bit(TTY_NO_WRITE_SPLIT, &tty->flags) ) {
690                 lock_kernel();
691                 written = write(tty, file, buf, count);
692                 unlock_kernel();
693         } else {
694                 for (;;) {
695                         unsigned long size = max((unsigned long)PAGE_SIZE*2, 16384UL);
696                         if (size > count)
697                                 size = count;
698                         lock_kernel();
699                         ret = write(tty, file, buf, size);
700                         unlock_kernel();
701                         if (ret <= 0)
702                                 break;
703                         written += ret;
704                         buf += ret;
705                         count -= ret;
706                         if (!count)
707                                 break;
708                         ret = -ERESTARTSYS;
709                         if (signal_pending(current))
710                                 break;
711                         cond_resched();
712                 }
713         }
714         if (written) {
715                 file->f_dentry->d_inode->i_mtime = CURRENT_TIME;
716                 ret = written;
717         }
718         up(&tty->atomic_write);
719         return ret;
720 }
721
722
723 static ssize_t tty_write(struct file * file, const char __user * buf, size_t count,
724                          loff_t *ppos)
725 {
726         struct tty_struct * tty;
727         struct inode *inode = file->f_dentry->d_inode;
728
729         /* Can't seek (pwrite) on ttys.  */
730         if (ppos != &file->f_pos)
731                 return -ESPIPE;
732
733         tty = (struct tty_struct *)file->private_data;
734         if (tty_paranoia_check(tty, inode, "tty_write"))
735                 return -EIO;
736         if (!tty || !tty->driver->write || (test_bit(TTY_IO_ERROR, &tty->flags)))
737                 return -EIO;
738         if (!tty->ldisc.write)
739                 return -EIO;
740         return do_tty_write(tty->ldisc.write, tty, file,
741                             (const unsigned char __user *)buf, count);
742 }
743
744 ssize_t redirected_tty_write(struct file * file, const char __user * buf, size_t count,
745                          loff_t *ppos)
746 {
747         struct file *p = NULL;
748
749         spin_lock(&redirect_lock);
750         if (redirect) {
751                 get_file(redirect);
752                 p = redirect;
753         }
754         spin_unlock(&redirect_lock);
755
756         if (p) {
757                 ssize_t res;
758                 /* Can't seek (pwrite) on ttys.  */
759                 if (ppos != &file->f_pos)
760                         return -ESPIPE;
761                 res = vfs_write(p, buf, count, &p->f_pos);
762                 fput(p);
763                 return res;
764         }
765
766         return tty_write(file, buf, count, ppos);
767 }
768
769 static inline void tty_line_name(struct tty_driver *driver, int index, char *p)
770 {
771         sprintf(p, "%s%d", driver->name, index + driver->name_base);
772 }
773
774 /*
775  * WSH 06/09/97: Rewritten to remove races and properly clean up after a
776  * failed open.  The new code protects the open with a semaphore, so it's
777  * really quite straightforward.  The semaphore locking can probably be
778  * relaxed for the (most common) case of reopening a tty.
779  */
780 static int init_dev(struct tty_driver *driver, int idx,
781         struct tty_struct **ret_tty)
782 {
783         struct tty_struct *tty, *o_tty;
784         struct termios *tp, **tp_loc, *o_tp, **o_tp_loc;
785         struct termios *ltp, **ltp_loc, *o_ltp, **o_ltp_loc;
786         int retval=0;
787
788         /* 
789          * Check whether we need to acquire the tty semaphore to avoid
790          * race conditions.  For now, play it safe.
791          */
792         down(&tty_sem);
793
794         /* check whether we're reopening an existing tty */
795         if (driver->flags & TTY_DRIVER_DEVPTS_MEM) {
796                 tty = devpts_get_tty(idx);
797                 if (tty && driver->subtype == PTY_TYPE_MASTER)
798                         tty = tty->link;
799         } else {
800                 tty = driver->ttys[idx];
801         }
802         if (tty) goto fast_track;
803
804         /*
805          * First time open is complex, especially for PTY devices.
806          * This code guarantees that either everything succeeds and the
807          * TTY is ready for operation, or else the table slots are vacated
808          * and the allocated memory released.  (Except that the termios 
809          * and locked termios may be retained.)
810          */
811
812         if (!try_module_get(driver->owner)) {
813                 retval = -ENODEV;
814                 goto end_init;
815         }
816
817         o_tty = NULL;
818         tp = o_tp = NULL;
819         ltp = o_ltp = NULL;
820
821         tty = alloc_tty_struct();
822         if(!tty)
823                 goto fail_no_mem;
824         initialize_tty_struct(tty);
825         tty->driver = driver;
826         tty->index = idx;
827         tty_line_name(driver, idx, tty->name);
828
829         if (driver->flags & TTY_DRIVER_DEVPTS_MEM) {
830                 tp_loc = &tty->termios;
831                 ltp_loc = &tty->termios_locked;
832         } else {
833                 tp_loc = &driver->termios[idx];
834                 ltp_loc = &driver->termios_locked[idx];
835         }
836
837         if (!*tp_loc) {
838                 tp = (struct termios *) kmalloc(sizeof(struct termios),
839                                                 GFP_KERNEL);
840                 if (!tp)
841                         goto free_mem_out;
842                 *tp = driver->init_termios;
843         }
844
845         if (!*ltp_loc) {
846                 ltp = (struct termios *) kmalloc(sizeof(struct termios),
847                                                  GFP_KERNEL);
848                 if (!ltp)
849                         goto free_mem_out;
850                 memset(ltp, 0, sizeof(struct termios));
851         }
852
853         if (driver->type == TTY_DRIVER_TYPE_PTY) {
854                 o_tty = alloc_tty_struct();
855                 if (!o_tty)
856                         goto free_mem_out;
857                 initialize_tty_struct(o_tty);
858                 o_tty->driver = driver->other;
859                 o_tty->index = idx;
860                 tty_line_name(driver->other, idx, o_tty->name);
861
862                 if (driver->flags & TTY_DRIVER_DEVPTS_MEM) {
863                         o_tp_loc = &o_tty->termios;
864                         o_ltp_loc = &o_tty->termios_locked;
865                 } else {
866                         o_tp_loc = &driver->other->termios[idx];
867                         o_ltp_loc = &driver->other->termios_locked[idx];
868                 }
869
870                 if (!*o_tp_loc) {
871                         o_tp = (struct termios *)
872                                 kmalloc(sizeof(struct termios), GFP_KERNEL);
873                         if (!o_tp)
874                                 goto free_mem_out;
875                         *o_tp = driver->other->init_termios;
876                 }
877
878                 if (!*o_ltp_loc) {
879                         o_ltp = (struct termios *)
880                                 kmalloc(sizeof(struct termios), GFP_KERNEL);
881                         if (!o_ltp)
882                                 goto free_mem_out;
883                         memset(o_ltp, 0, sizeof(struct termios));
884                 }
885
886                 /*
887                  * Everything allocated ... set up the o_tty structure.
888                  */
889                 if (!(driver->other->flags & TTY_DRIVER_DEVPTS_MEM)) {
890                         driver->other->ttys[idx] = o_tty;
891                 }
892                 if (!*o_tp_loc)
893                         *o_tp_loc = o_tp;
894                 if (!*o_ltp_loc)
895                         *o_ltp_loc = o_ltp;
896                 o_tty->termios = *o_tp_loc;
897                 o_tty->termios_locked = *o_ltp_loc;
898                 driver->other->refcount++;
899                 if (driver->subtype == PTY_TYPE_MASTER)
900                         o_tty->count++;
901
902                 /* Establish the links in both directions */
903                 tty->link   = o_tty;
904                 o_tty->link = tty;
905         }
906
907         /* 
908          * All structures have been allocated, so now we install them.
909          * Failures after this point use release_mem to clean up, so 
910          * there's no need to null out the local pointers.
911          */
912         if (!(driver->flags & TTY_DRIVER_DEVPTS_MEM)) {
913                 driver->ttys[idx] = tty;
914         }
915         
916         if (!*tp_loc)
917                 *tp_loc = tp;
918         if (!*ltp_loc)
919                 *ltp_loc = ltp;
920         tty->termios = *tp_loc;
921         tty->termios_locked = *ltp_loc;
922         driver->refcount++;
923         tty->count++;
924
925         /* 
926          * Structures all installed ... call the ldisc open routines.
927          * If we fail here just call release_mem to clean up.  No need
928          * to decrement the use counts, as release_mem doesn't care.
929          */
930         if (tty->ldisc.open) {
931                 retval = (tty->ldisc.open)(tty);
932                 if (retval)
933                         goto release_mem_out;
934         }
935         if (o_tty && o_tty->ldisc.open) {
936                 retval = (o_tty->ldisc.open)(o_tty);
937                 if (retval) {
938                         if (tty->ldisc.close)
939                                 (tty->ldisc.close)(tty);
940                         goto release_mem_out;
941                 }
942         }
943         goto success;
944
945         /*
946          * This fast open can be used if the tty is already open.
947          * No memory is allocated, and the only failures are from
948          * attempting to open a closing tty or attempting multiple
949          * opens on a pty master.
950          */
951 fast_track:
952         if (test_bit(TTY_CLOSING, &tty->flags)) {
953                 retval = -EIO;
954                 goto end_init;
955         }
956         if (driver->type == TTY_DRIVER_TYPE_PTY &&
957             driver->subtype == PTY_TYPE_MASTER) {
958                 /*
959                  * special case for PTY masters: only one open permitted, 
960                  * and the slave side open count is incremented as well.
961                  */
962                 if (tty->count) {
963                         retval = -EIO;
964                         goto end_init;
965                 }
966                 tty->link->count++;
967         }
968         tty->count++;
969         tty->driver = driver; /* N.B. why do this every time?? */
970
971 success:
972         *ret_tty = tty;
973         
974         /* All paths come through here to release the semaphore */
975 end_init:
976         up(&tty_sem);
977         return retval;
978
979         /* Release locally allocated memory ... nothing placed in slots */
980 free_mem_out:
981         if (o_tp)
982                 kfree(o_tp);
983         if (o_tty)
984                 free_tty_struct(o_tty);
985         if (ltp)
986                 kfree(ltp);
987         if (tp)
988                 kfree(tp);
989         free_tty_struct(tty);
990
991 fail_no_mem:
992         module_put(driver->owner);
993         retval = -ENOMEM;
994         goto end_init;
995
996         /* call the tty release_mem routine to clean out this slot */
997 release_mem_out:
998         printk(KERN_INFO "init_dev: ldisc open failed, "
999                          "clearing slot %d\n", idx);
1000         release_mem(tty, idx);
1001         goto end_init;
1002 }
1003
1004 /*
1005  * Releases memory associated with a tty structure, and clears out the
1006  * driver table slots.
1007  */
1008 static void release_mem(struct tty_struct *tty, int idx)
1009 {
1010         struct tty_struct *o_tty;
1011         struct termios *tp;
1012         int devpts = tty->driver->flags & TTY_DRIVER_DEVPTS_MEM;
1013
1014         if ((o_tty = tty->link) != NULL) {
1015                 if (!devpts)
1016                         o_tty->driver->ttys[idx] = NULL;
1017                 if (o_tty->driver->flags & TTY_DRIVER_RESET_TERMIOS) {
1018                         tp = o_tty->termios;
1019                         if (!devpts)
1020                                 o_tty->driver->termios[idx] = NULL;
1021                         kfree(tp);
1022
1023                         tp = o_tty->termios_locked;
1024                         if (!devpts)
1025                                 o_tty->driver->termios_locked[idx] = NULL;
1026                         kfree(tp);
1027                 }
1028                 o_tty->magic = 0;
1029                 o_tty->driver->refcount--;
1030                 file_list_lock();
1031                 list_del_init(&o_tty->tty_files);
1032                 file_list_unlock();
1033                 free_tty_struct(o_tty);
1034         }
1035
1036         if (!devpts)
1037                 tty->driver->ttys[idx] = NULL;
1038         if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS) {
1039                 tp = tty->termios;
1040                 if (!devpts)
1041                         tty->driver->termios[idx] = NULL;
1042                 kfree(tp);
1043
1044                 tp = tty->termios_locked;
1045                 if (!devpts)
1046                         tty->driver->termios_locked[idx] = NULL;
1047                 kfree(tp);
1048         }
1049
1050         tty->magic = 0;
1051         tty->driver->refcount--;
1052         file_list_lock();
1053         list_del_init(&tty->tty_files);
1054         file_list_unlock();
1055         module_put(tty->driver->owner);
1056         free_tty_struct(tty);
1057 }
1058
1059 /*
1060  * Even releasing the tty structures is a tricky business.. We have
1061  * to be very careful that the structures are all released at the
1062  * same time, as interrupts might otherwise get the wrong pointers.
1063  *
1064  * WSH 09/09/97: rewritten to avoid some nasty race conditions that could
1065  * lead to double frees or releasing memory still in use.
1066  */
1067 static void release_dev(struct file * filp)
1068 {
1069         struct tty_struct *tty, *o_tty;
1070         int     pty_master, tty_closing, o_tty_closing, do_sleep;
1071         int     devpts_master;
1072         int     idx;
1073         char    buf[64];
1074         
1075         tty = (struct tty_struct *)filp->private_data;
1076         if (tty_paranoia_check(tty, filp->f_dentry->d_inode, "release_dev"))
1077                 return;
1078
1079         check_tty_count(tty, "release_dev");
1080
1081         tty_fasync(-1, filp, 0);
1082
1083         idx = tty->index;
1084         pty_master = (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
1085                       tty->driver->subtype == PTY_TYPE_MASTER);
1086         devpts_master = pty_master && (tty->driver->flags & TTY_DRIVER_DEVPTS_MEM);
1087         o_tty = tty->link;
1088
1089 #ifdef TTY_PARANOIA_CHECK
1090         if (idx < 0 || idx >= tty->driver->num) {
1091                 printk(KERN_DEBUG "release_dev: bad idx when trying to "
1092                                   "free (%s)\n", tty->name);
1093                 return;
1094         }
1095         if (!(tty->driver->flags & TTY_DRIVER_DEVPTS_MEM)) {
1096                 if (tty != tty->driver->ttys[idx]) {
1097                         printk(KERN_DEBUG "release_dev: driver.table[%d] not tty "
1098                                "for (%s)\n", idx, tty->name);
1099                         return;
1100                 }
1101                 if (tty->termios != tty->driver->termios[idx]) {
1102                         printk(KERN_DEBUG "release_dev: driver.termios[%d] not termios "
1103                                "for (%s)\n",
1104                                idx, tty->name);
1105                         return;
1106                 }
1107                 if (tty->termios_locked != tty->driver->termios_locked[idx]) {
1108                         printk(KERN_DEBUG "release_dev: driver.termios_locked[%d] not "
1109                                "termios_locked for (%s)\n",
1110                                idx, tty->name);
1111                         return;
1112                 }
1113         }
1114 #endif
1115
1116 #ifdef TTY_DEBUG_HANGUP
1117         printk(KERN_DEBUG "release_dev of %s (tty count=%d)...",
1118                tty_name(tty, buf), tty->count);
1119 #endif
1120
1121 #ifdef TTY_PARANOIA_CHECK
1122         if (tty->driver->other &&
1123              !(tty->driver->flags & TTY_DRIVER_DEVPTS_MEM)) {
1124                 if (o_tty != tty->driver->other->ttys[idx]) {
1125                         printk(KERN_DEBUG "release_dev: other->table[%d] "
1126                                           "not o_tty for (%s)\n",
1127                                idx, tty->name);
1128                         return;
1129                 }
1130                 if (o_tty->termios != tty->driver->other->termios[idx]) {
1131                         printk(KERN_DEBUG "release_dev: other->termios[%d] "
1132                                           "not o_termios for (%s)\n",
1133                                idx, tty->name);
1134                         return;
1135                 }
1136                 if (o_tty->termios_locked != 
1137                       tty->driver->other->termios_locked[idx]) {
1138                         printk(KERN_DEBUG "release_dev: other->termios_locked["
1139                                           "%d] not o_termios_locked for (%s)\n",
1140                                idx, tty->name);
1141                         return;
1142                 }
1143                 if (o_tty->link != tty) {
1144                         printk(KERN_DEBUG "release_dev: bad pty pointers\n");
1145                         return;
1146                 }
1147         }
1148 #endif
1149
1150         if (tty->driver->close)
1151                 tty->driver->close(tty, filp);
1152
1153         /*
1154          * Sanity check: if tty->count is going to zero, there shouldn't be
1155          * any waiters on tty->read_wait or tty->write_wait.  We test the
1156          * wait queues and kick everyone out _before_ actually starting to
1157          * close.  This ensures that we won't block while releasing the tty
1158          * structure.
1159          *
1160          * The test for the o_tty closing is necessary, since the master and
1161          * slave sides may close in any order.  If the slave side closes out
1162          * first, its count will be one, since the master side holds an open.
1163          * Thus this test wouldn't be triggered at the time the slave closes,
1164          * so we do it now.
1165          *
1166          * Note that it's possible for the tty to be opened again while we're
1167          * flushing out waiters.  By recalculating the closing flags before
1168          * each iteration we avoid any problems.
1169          */
1170         while (1) {
1171                 tty_closing = tty->count <= 1;
1172                 o_tty_closing = o_tty &&
1173                         (o_tty->count <= (pty_master ? 1 : 0));
1174                 do_sleep = 0;
1175
1176                 if (tty_closing) {
1177                         if (waitqueue_active(&tty->read_wait)) {
1178                                 wake_up(&tty->read_wait);
1179                                 do_sleep++;
1180                         }
1181                         if (waitqueue_active(&tty->write_wait)) {
1182                                 wake_up(&tty->write_wait);
1183                                 do_sleep++;
1184                         }
1185                 }
1186                 if (o_tty_closing) {
1187                         if (waitqueue_active(&o_tty->read_wait)) {
1188                                 wake_up(&o_tty->read_wait);
1189                                 do_sleep++;
1190                         }
1191                         if (waitqueue_active(&o_tty->write_wait)) {
1192                                 wake_up(&o_tty->write_wait);
1193                                 do_sleep++;
1194                         }
1195                 }
1196                 if (!do_sleep)
1197                         break;
1198
1199                 printk(KERN_WARNING "release_dev: %s: read/write wait queue "
1200                                     "active!\n", tty_name(tty, buf));
1201                 schedule();
1202         }       
1203
1204         /*
1205          * The closing flags are now consistent with the open counts on 
1206          * both sides, and we've completed the last operation that could 
1207          * block, so it's safe to proceed with closing.
1208          */
1209         if (pty_master) {
1210                 if (--o_tty->count < 0) {
1211                         printk(KERN_WARNING "release_dev: bad pty slave count "
1212                                             "(%d) for %s\n",
1213                                o_tty->count, tty_name(o_tty, buf));
1214                         o_tty->count = 0;
1215                 }
1216         }
1217         if (--tty->count < 0) {
1218                 printk(KERN_WARNING "release_dev: bad tty->count (%d) for %s\n",
1219                        tty->count, tty_name(tty, buf));
1220                 tty->count = 0;
1221         }
1222
1223         /*
1224          * We've decremented tty->count, so we need to remove this file
1225          * descriptor off the tty->tty_files list; this serves two
1226          * purposes:
1227          *  - check_tty_count sees the correct number of file descriptors
1228          *    associated with this tty.
1229          *  - do_tty_hangup no longer sees this file descriptor as
1230          *    something that needs to be handled for hangups.
1231          */
1232         file_kill(filp);
1233         filp->private_data = NULL;
1234
1235         /*
1236          * Perform some housekeeping before deciding whether to return.
1237          *
1238          * Set the TTY_CLOSING flag if this was the last open.  In the
1239          * case of a pty we may have to wait around for the other side
1240          * to close, and TTY_CLOSING makes sure we can't be reopened.
1241          */
1242         if(tty_closing)
1243                 set_bit(TTY_CLOSING, &tty->flags);
1244         if(o_tty_closing)
1245                 set_bit(TTY_CLOSING, &o_tty->flags);
1246
1247         /*
1248          * If _either_ side is closing, make sure there aren't any
1249          * processes that still think tty or o_tty is their controlling
1250          * tty.
1251          */
1252         if (tty_closing || o_tty_closing) {
1253                 struct task_struct *p;
1254                 struct list_head *l;
1255                 struct pid *pid;
1256
1257                 read_lock(&tasklist_lock);
1258                 for_each_task_pid(tty->session, PIDTYPE_SID, p, l, pid)
1259                         p->signal->tty = NULL;
1260                 if (o_tty)
1261                         for_each_task_pid(o_tty->session, PIDTYPE_SID, p,l, pid)
1262                                 p->signal->tty = NULL;
1263                 read_unlock(&tasklist_lock);
1264         }
1265
1266         /* check whether both sides are closing ... */
1267         if (!tty_closing || (o_tty && !o_tty_closing))
1268                 return;
1269         
1270 #ifdef TTY_DEBUG_HANGUP
1271         printk(KERN_DEBUG "freeing tty structure...");
1272 #endif
1273
1274         /*
1275          * Prevent flush_to_ldisc() from rescheduling the work for later.  Then
1276          * kill any delayed work.
1277          */
1278         clear_bit(TTY_DONT_FLIP, &tty->flags);
1279         cancel_delayed_work(&tty->flip.work);
1280
1281         /*
1282          * Wait for ->hangup_work and ->flip.work handlers to terminate
1283          */
1284         flush_scheduled_work();
1285
1286         /*
1287          * Shutdown the current line discipline, and reset it to N_TTY.
1288          * N.B. why reset ldisc when we're releasing the memory??
1289          */
1290         if (tty->ldisc.close)
1291                 (tty->ldisc.close)(tty);
1292         module_put(tty->ldisc.owner);
1293         
1294         tty->ldisc = ldiscs[N_TTY];
1295         tty->termios->c_line = N_TTY;
1296         if (o_tty) {
1297                 if (o_tty->ldisc.close)
1298                         (o_tty->ldisc.close)(o_tty);
1299                 module_put(o_tty->ldisc.owner);
1300                 o_tty->ldisc = ldiscs[N_TTY];
1301         }
1302
1303         /*
1304          * The release_mem function takes care of the details of clearing
1305          * the slots and preserving the termios structure.
1306          */
1307         release_mem(tty, idx);
1308
1309 #ifdef CONFIG_UNIX98_PTYS
1310         /* Make this pty number available for reallocation */
1311         if (devpts_master) {
1312                 down(&allocated_ptys_lock);
1313                 idr_remove(&allocated_ptys, idx);
1314                 up(&allocated_ptys_lock);
1315         }
1316 #endif
1317
1318 }
1319
1320 /*
1321  * tty_open and tty_release keep up the tty count that contains the
1322  * number of opens done on a tty. We cannot use the inode-count, as
1323  * different inodes might point to the same tty.
1324  *
1325  * Open-counting is needed for pty masters, as well as for keeping
1326  * track of serial lines: DTR is dropped when the last close happens.
1327  * (This is not done solely through tty->count, now.  - Ted 1/27/92)
1328  *
1329  * The termios state of a pty is reset on first open so that
1330  * settings don't persist across reuse.
1331  */
1332 static int tty_open(struct inode * inode, struct file * filp)
1333 {
1334         struct tty_struct *tty;
1335         int noctty, retval;
1336         struct tty_driver *driver;
1337         int index;
1338         dev_t device = inode->i_rdev;
1339         unsigned short saved_flags = filp->f_flags;
1340
1341 retry_open:
1342         noctty = filp->f_flags & O_NOCTTY;
1343         index  = -1;
1344         retval = 0;
1345
1346         if (device == MKDEV(TTYAUX_MAJOR,0)) {
1347                 if (!current->signal->tty)
1348                         return -ENXIO;
1349                 driver = current->signal->tty->driver;
1350                 index = current->signal->tty->index;
1351                 filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
1352                 /* noctty = 1; */
1353                 goto got_driver;
1354         }
1355 #ifdef CONFIG_VT
1356         if (device == MKDEV(TTY_MAJOR,0)) {
1357                 extern int fg_console;
1358                 extern struct tty_driver *console_driver;
1359                 driver = console_driver;
1360                 index = fg_console;
1361                 noctty = 1;
1362                 goto got_driver;
1363         }
1364 #endif
1365         if (device == MKDEV(TTYAUX_MAJOR,1)) {
1366                 struct console *c = console_drivers;
1367                 for (c = console_drivers; c; c = c->next) {
1368                         if (!c->device)
1369                                 continue;
1370                         driver = c->device(c, &index);
1371                         if (!driver)
1372                                 continue;
1373                         /* Don't let /dev/console block */
1374                         filp->f_flags |= O_NONBLOCK;
1375                         noctty = 1;
1376                         goto got_driver;
1377                 }
1378                 return -ENODEV;
1379         }
1380
1381 #ifdef CONFIG_UNIX98_PTYS
1382         if (device == MKDEV(TTYAUX_MAJOR,2)) {
1383                 int idr_ret;
1384
1385                 /* find a device that is not in use. */
1386                 down(&allocated_ptys_lock);
1387                 if (!idr_pre_get(&allocated_ptys, GFP_KERNEL)) {
1388                         up(&allocated_ptys_lock);
1389                         return -ENOMEM;
1390                 }
1391                 idr_ret = idr_get_new(&allocated_ptys, NULL, &index);
1392                 if (idr_ret < 0) {
1393                         up(&allocated_ptys_lock);
1394                         if (idr_ret == -EAGAIN)
1395                                 return -ENOMEM;
1396                         return -EIO;
1397                 }
1398                 if (index >= pty_limit) {
1399                         idr_remove(&allocated_ptys, index);
1400                         up(&allocated_ptys_lock);
1401                         return -EIO;
1402                 }
1403                 up(&allocated_ptys_lock);
1404
1405                 driver = ptm_driver;
1406                 retval = init_dev(driver, index, &tty);
1407                 if (retval) {
1408                         down(&allocated_ptys_lock);
1409                         idr_remove(&allocated_ptys, index);
1410                         up(&allocated_ptys_lock);
1411                         return retval;
1412                 }
1413
1414                 set_bit(TTY_PTY_LOCK, &tty->flags); /* LOCK THE SLAVE */
1415                 if (devpts_pty_new(tty->link))
1416                         retval = -ENOMEM;
1417         } else
1418 #endif
1419         {
1420                 driver = get_tty_driver(device, &index);
1421                 if (!driver)
1422                         return -ENODEV;
1423 got_driver:
1424                 retval = init_dev(driver, index, &tty);
1425                 if (retval)
1426                         return retval;
1427         }
1428
1429         filp->private_data = tty;
1430         file_move(filp, &tty->tty_files);
1431         check_tty_count(tty, "tty_open");
1432         if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
1433             tty->driver->subtype == PTY_TYPE_MASTER)
1434                 noctty = 1;
1435 #ifdef TTY_DEBUG_HANGUP
1436         printk(KERN_DEBUG "opening %s...", tty->name);
1437 #endif
1438         if (!retval) {
1439                 if (tty->driver->open)
1440                         retval = tty->driver->open(tty, filp);
1441                 else
1442                         retval = -ENODEV;
1443         }
1444         filp->f_flags = saved_flags;
1445
1446         if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) && !capable(CAP_SYS_ADMIN))
1447                 retval = -EBUSY;
1448
1449         if (retval) {
1450 #ifdef TTY_DEBUG_HANGUP
1451                 printk(KERN_DEBUG "error %d in opening %s...", retval,
1452                        tty->name);
1453 #endif
1454
1455 #ifdef CONFIG_UNIX98_PTYS
1456                 if (index != -1) {
1457                         down(&allocated_ptys_lock);
1458                         idr_remove(&allocated_ptys, index);
1459                         up(&allocated_ptys_lock);
1460                 }
1461 #endif
1462
1463                 release_dev(filp);
1464                 if (retval != -ERESTARTSYS)
1465                         return retval;
1466                 if (signal_pending(current))
1467                         return retval;
1468                 schedule();
1469                 /*
1470                  * Need to reset f_op in case a hangup happened.
1471                  */
1472                 if (filp->f_op == &hung_up_tty_fops)
1473                         filp->f_op = &tty_fops;
1474                 goto retry_open;
1475         }
1476         if (!noctty &&
1477             current->signal->leader &&
1478             !current->signal->tty &&
1479             tty->session == 0) {
1480                 task_lock(current);
1481                 current->signal->tty = tty;
1482                 task_unlock(current);
1483                 current->signal->tty_old_pgrp = 0;
1484                 tty->session = current->signal->session;
1485                 tty->pgrp = process_group(current);
1486         }
1487         return 0;
1488 }
1489
1490 static int tty_release(struct inode * inode, struct file * filp)
1491 {
1492         lock_kernel();
1493         release_dev(filp);
1494         unlock_kernel();
1495         return 0;
1496 }
1497
1498 /* No kernel lock held - fine */
1499 static unsigned int tty_poll(struct file * filp, poll_table * wait)
1500 {
1501         struct tty_struct * tty;
1502
1503         tty = (struct tty_struct *)filp->private_data;
1504         if (tty_paranoia_check(tty, filp->f_dentry->d_inode, "tty_poll"))
1505                 return 0;
1506
1507         if (tty->ldisc.poll)
1508                 return (tty->ldisc.poll)(tty, filp, wait);
1509         return 0;
1510 }
1511
1512 static int tty_fasync(int fd, struct file * filp, int on)
1513 {
1514         struct tty_struct * tty;
1515         int retval;
1516
1517         tty = (struct tty_struct *)filp->private_data;
1518         if (tty_paranoia_check(tty, filp->f_dentry->d_inode, "tty_fasync"))
1519                 return 0;
1520         
1521         retval = fasync_helper(fd, filp, on, &tty->fasync);
1522         if (retval <= 0)
1523                 return retval;
1524
1525         if (on) {
1526                 if (!waitqueue_active(&tty->read_wait))
1527                         tty->minimum_to_wake = 1;
1528                 retval = f_setown(filp, (-tty->pgrp) ? : current->pid, 0);
1529                 if (retval)
1530                         return retval;
1531         } else {
1532                 if (!tty->fasync && !waitqueue_active(&tty->read_wait))
1533                         tty->minimum_to_wake = N_TTY_BUF_SIZE;
1534         }
1535         return 0;
1536 }
1537
1538 static int tiocsti(struct tty_struct *tty, char __user *p)
1539 {
1540         char ch, mbz = 0;
1541
1542         if ((current->signal->tty != tty) && !capable(CAP_SYS_ADMIN))
1543                 return -EPERM;
1544         if (get_user(ch, p))
1545                 return -EFAULT;
1546         tty->ldisc.receive_buf(tty, &ch, &mbz, 1);
1547         return 0;
1548 }
1549
1550 static int tiocgwinsz(struct tty_struct *tty, struct winsize __user * arg)
1551 {
1552         if (copy_to_user(arg, &tty->winsize, sizeof(*arg)))
1553                 return -EFAULT;
1554         return 0;
1555 }
1556
1557 static int tiocswinsz(struct tty_struct *tty, struct tty_struct *real_tty,
1558         struct winsize __user * arg)
1559 {
1560         struct winsize tmp_ws;
1561
1562         if (copy_from_user(&tmp_ws, arg, sizeof(*arg)))
1563                 return -EFAULT;
1564         if (!memcmp(&tmp_ws, &tty->winsize, sizeof(*arg)))
1565                 return 0;
1566 #ifdef CONFIG_VT
1567         if (tty->driver->type == TTY_DRIVER_TYPE_CONSOLE) {
1568                 unsigned int currcons = tty->index;
1569                 int rc;
1570
1571                 acquire_console_sem();
1572                 rc = vc_resize(currcons, tmp_ws.ws_col, tmp_ws.ws_row);
1573                 release_console_sem();
1574                 if (rc)
1575                         return -ENXIO;
1576         }
1577 #endif
1578         if (tty->pgrp > 0)
1579                 kill_pg(tty->pgrp, SIGWINCH, 1);
1580         if ((real_tty->pgrp != tty->pgrp) && (real_tty->pgrp > 0))
1581                 kill_pg(real_tty->pgrp, SIGWINCH, 1);
1582         tty->winsize = tmp_ws;
1583         real_tty->winsize = tmp_ws;
1584         return 0;
1585 }
1586
1587 static int tioccons(struct file *file)
1588 {
1589         if (file->f_op->write == redirected_tty_write) {
1590                 struct file *f;
1591                 if (!capable(CAP_SYS_ADMIN))
1592                         return -EPERM;
1593                 spin_lock(&redirect_lock);
1594                 f = redirect;
1595                 redirect = NULL;
1596                 spin_unlock(&redirect_lock);
1597                 if (f)
1598                         fput(f);
1599                 return 0;
1600         }
1601         spin_lock(&redirect_lock);
1602         if (redirect) {
1603                 spin_unlock(&redirect_lock);
1604                 return -EBUSY;
1605         }
1606         get_file(file);
1607         redirect = file;
1608         spin_unlock(&redirect_lock);
1609         return 0;
1610 }
1611
1612
1613 static int fionbio(struct file *file, int __user *p)
1614 {
1615         int nonblock;
1616
1617         if (get_user(nonblock, p))
1618                 return -EFAULT;
1619
1620         if (nonblock)
1621                 file->f_flags |= O_NONBLOCK;
1622         else
1623                 file->f_flags &= ~O_NONBLOCK;
1624         return 0;
1625 }
1626
1627 static int tiocsctty(struct tty_struct *tty, int arg)
1628 {
1629         struct list_head *l;
1630         struct pid *pid;
1631         task_t *p;
1632
1633         if (current->signal->leader &&
1634             (current->signal->session == tty->session))
1635                 return 0;
1636         /*
1637          * The process must be a session leader and
1638          * not have a controlling tty already.
1639          */
1640         if (!current->signal->leader || current->signal->tty)
1641                 return -EPERM;
1642         if (tty->session > 0) {
1643                 /*
1644                  * This tty is already the controlling
1645                  * tty for another session group!
1646                  */
1647                 if ((arg == 1) && capable(CAP_SYS_ADMIN)) {
1648                         /*
1649                          * Steal it away
1650                          */
1651
1652                         read_lock(&tasklist_lock);
1653                         for_each_task_pid(tty->session, PIDTYPE_SID, p, l, pid)
1654                                 p->signal->tty = NULL;
1655                         read_unlock(&tasklist_lock);
1656                 } else
1657                         return -EPERM;
1658         }
1659         task_lock(current);
1660         current->signal->tty = tty;
1661         task_unlock(current);
1662         current->signal->tty_old_pgrp = 0;
1663         tty->session = current->signal->session;
1664         tty->pgrp = process_group(current);
1665         return 0;
1666 }
1667
1668 static int tiocgpgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
1669 {
1670         /*
1671          * (tty == real_tty) is a cheap way of
1672          * testing if the tty is NOT a master pty.
1673          */
1674         if (tty == real_tty && current->signal->tty != real_tty)
1675                 return -ENOTTY;
1676         return put_user(real_tty->pgrp, p);
1677 }
1678
1679 static int tiocspgrp(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
1680 {
1681         pid_t pgrp;
1682         int retval = tty_check_change(real_tty);
1683
1684         if (retval == -EIO)
1685                 return -ENOTTY;
1686         if (retval)
1687                 return retval;
1688         if (!current->signal->tty ||
1689             (current->signal->tty != real_tty) ||
1690             (real_tty->session != current->signal->session))
1691                 return -ENOTTY;
1692         if (get_user(pgrp, p))
1693                 return -EFAULT;
1694         if (pgrp < 0)
1695                 return -EINVAL;
1696         if (session_of_pgrp(pgrp) != current->signal->session)
1697                 return -EPERM;
1698         real_tty->pgrp = pgrp;
1699         return 0;
1700 }
1701
1702 static int tiocgsid(struct tty_struct *tty, struct tty_struct *real_tty, pid_t __user *p)
1703 {
1704         /*
1705          * (tty == real_tty) is a cheap way of
1706          * testing if the tty is NOT a master pty.
1707         */
1708         if (tty == real_tty && current->signal->tty != real_tty)
1709                 return -ENOTTY;
1710         if (real_tty->session <= 0)
1711                 return -ENOTTY;
1712         return put_user(real_tty->session, p);
1713 }
1714
1715 static int tiocsetd(struct tty_struct *tty, int __user *p)
1716 {
1717         int ldisc;
1718
1719         if (get_user(ldisc, p))
1720                 return -EFAULT;
1721         return tty_set_ldisc(tty, ldisc);
1722 }
1723
1724 static int send_break(struct tty_struct *tty, int duration)
1725 {
1726         set_current_state(TASK_INTERRUPTIBLE);
1727
1728         tty->driver->break_ctl(tty, -1);
1729         if (!signal_pending(current))
1730                 schedule_timeout(duration);
1731         tty->driver->break_ctl(tty, 0);
1732         if (signal_pending(current))
1733                 return -EINTR;
1734         return 0;
1735 }
1736
1737 static int
1738 tty_tiocmget(struct tty_struct *tty, struct file *file, int __user *p)
1739 {
1740         int retval = -EINVAL;
1741
1742         if (tty->driver->tiocmget) {
1743                 retval = tty->driver->tiocmget(tty, file);
1744
1745                 if (retval >= 0)
1746                         retval = put_user(retval, p);
1747         }
1748         return retval;
1749 }
1750
1751 static int
1752 tty_tiocmset(struct tty_struct *tty, struct file *file, unsigned int cmd,
1753              unsigned __user *p)
1754 {
1755         int retval = -EINVAL;
1756
1757         if (tty->driver->tiocmset) {
1758                 unsigned int set, clear, val;
1759
1760                 retval = get_user(val, p);
1761                 if (retval)
1762                         return retval;
1763
1764                 set = clear = 0;
1765                 switch (cmd) {
1766                 case TIOCMBIS:
1767                         set = val;
1768                         break;
1769                 case TIOCMBIC:
1770                         clear = val;
1771                         break;
1772                 case TIOCMSET:
1773                         set = val;
1774                         clear = ~val;
1775                         break;
1776                 }
1777
1778                 set &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
1779                 clear &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
1780
1781                 retval = tty->driver->tiocmset(tty, file, set, clear);
1782         }
1783         return retval;
1784 }
1785
1786 /*
1787  * Split this up, as gcc can choke on it otherwise..
1788  */
1789 int tty_ioctl(struct inode * inode, struct file * file,
1790               unsigned int cmd, unsigned long arg)
1791 {
1792         struct tty_struct *tty, *real_tty;
1793         void __user *p = (void __user *)arg;
1794         int retval;
1795         
1796         tty = (struct tty_struct *)file->private_data;
1797         if (tty_paranoia_check(tty, inode, "tty_ioctl"))
1798                 return -EINVAL;
1799
1800         real_tty = tty;
1801         if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
1802             tty->driver->subtype == PTY_TYPE_MASTER)
1803                 real_tty = tty->link;
1804
1805         /*
1806          * Break handling by driver
1807          */
1808         if (!tty->driver->break_ctl) {
1809                 switch(cmd) {
1810                 case TIOCSBRK:
1811                 case TIOCCBRK:
1812                         if (tty->driver->ioctl)
1813                                 return tty->driver->ioctl(tty, file, cmd, arg);
1814                         return -EINVAL;
1815                         
1816                 /* These two ioctl's always return success; even if */
1817                 /* the driver doesn't support them. */
1818                 case TCSBRK:
1819                 case TCSBRKP:
1820                         if (!tty->driver->ioctl)
1821                                 return 0;
1822                         retval = tty->driver->ioctl(tty, file, cmd, arg);
1823                         if (retval == -ENOIOCTLCMD)
1824                                 retval = 0;
1825                         return retval;
1826                 }
1827         }
1828
1829         /*
1830          * Factor out some common prep work
1831          */
1832         switch (cmd) {
1833         case TIOCSETD:
1834         case TIOCSBRK:
1835         case TIOCCBRK:
1836         case TCSBRK:
1837         case TCSBRKP:                   
1838                 retval = tty_check_change(tty);
1839                 if (retval)
1840                         return retval;
1841                 if (cmd != TIOCCBRK) {
1842                         tty_wait_until_sent(tty, 0);
1843                         if (signal_pending(current))
1844                                 return -EINTR;
1845                 }
1846                 break;
1847         }
1848
1849         switch (cmd) {
1850                 case TIOCSTI:
1851                         return tiocsti(tty, p);
1852                 case TIOCGWINSZ:
1853                         return tiocgwinsz(tty, p);
1854                 case TIOCSWINSZ:
1855                         return tiocswinsz(tty, real_tty, p);
1856                 case TIOCCONS:
1857                         return real_tty!=tty ? -EINVAL : tioccons(file);
1858                 case FIONBIO:
1859                         return fionbio(file, p);
1860                 case TIOCEXCL:
1861                         set_bit(TTY_EXCLUSIVE, &tty->flags);
1862                         return 0;
1863                 case TIOCNXCL:
1864                         clear_bit(TTY_EXCLUSIVE, &tty->flags);
1865                         return 0;
1866                 case TIOCNOTTY:
1867                         if (current->signal->tty != tty)
1868                                 return -ENOTTY;
1869                         if (current->signal->leader)
1870                                 disassociate_ctty(0);
1871                         task_lock(current);
1872                         current->signal->tty = NULL;
1873                         task_unlock(current);
1874                         return 0;
1875                 case TIOCSCTTY:
1876                         return tiocsctty(tty, arg);
1877                 case TIOCGPGRP:
1878                         return tiocgpgrp(tty, real_tty, p);
1879                 case TIOCSPGRP:
1880                         return tiocspgrp(tty, real_tty, p);
1881                 case TIOCGSID:
1882                         return tiocgsid(tty, real_tty, p);
1883                 case TIOCGETD:
1884                         return put_user(tty->ldisc.num, (int __user *)p);
1885                 case TIOCSETD:
1886                         return tiocsetd(tty, p);
1887 #ifdef CONFIG_VT
1888                 case TIOCLINUX:
1889                         return tioclinux(tty, arg);
1890 #endif
1891                 /*
1892                  * Break handling
1893                  */
1894                 case TIOCSBRK:  /* Turn break on, unconditionally */
1895                         tty->driver->break_ctl(tty, -1);
1896                         return 0;
1897                         
1898                 case TIOCCBRK:  /* Turn break off, unconditionally */
1899                         tty->driver->break_ctl(tty, 0);
1900                         return 0;
1901                 case TCSBRK:   /* SVID version: non-zero arg --> no break */
1902                         /*
1903                          * XXX is the above comment correct, or the
1904                          * code below correct?  Is this ioctl used at
1905                          * all by anyone?
1906                          */
1907                         if (!arg)
1908                                 return send_break(tty, HZ/4);
1909                         return 0;
1910                 case TCSBRKP:   /* support for POSIX tcsendbreak() */   
1911                         return send_break(tty, arg ? arg*(HZ/10) : HZ/4);
1912
1913                 case TIOCMGET:
1914                         return tty_tiocmget(tty, file, p);
1915
1916                 case TIOCMSET:
1917                 case TIOCMBIC:
1918                 case TIOCMBIS:
1919                         return tty_tiocmset(tty, file, cmd, p);
1920         }
1921         if (tty->driver->ioctl) {
1922                 int retval = (tty->driver->ioctl)(tty, file, cmd, arg);
1923                 if (retval != -ENOIOCTLCMD)
1924                         return retval;
1925         }
1926         if (tty->ldisc.ioctl) {
1927                 int retval = (tty->ldisc.ioctl)(tty, file, cmd, arg);
1928                 if (retval != -ENOIOCTLCMD)
1929                         return retval;
1930         }
1931         return -EINVAL;
1932 }
1933
1934
1935 /*
1936  * This implements the "Secure Attention Key" ---  the idea is to
1937  * prevent trojan horses by killing all processes associated with this
1938  * tty when the user hits the "Secure Attention Key".  Required for
1939  * super-paranoid applications --- see the Orange Book for more details.
1940  * 
1941  * This code could be nicer; ideally it should send a HUP, wait a few
1942  * seconds, then send a INT, and then a KILL signal.  But you then
1943  * have to coordinate with the init process, since all processes associated
1944  * with the current tty must be dead before the new getty is allowed
1945  * to spawn.
1946  *
1947  * Now, if it would be correct ;-/ The current code has a nasty hole -
1948  * it doesn't catch files in flight. We may send the descriptor to ourselves
1949  * via AF_UNIX socket, close it and later fetch from socket. FIXME.
1950  *
1951  * Nasty bug: do_SAK is being called in interrupt context.  This can
1952  * deadlock.  We punt it up to process context.  AKPM - 16Mar2001
1953  */
1954 static void __do_SAK(void *arg)
1955 {
1956 #ifdef TTY_SOFT_SAK
1957         tty_hangup(tty);
1958 #else
1959         struct tty_struct *tty = arg;
1960         struct task_struct *p;
1961         struct list_head *l;
1962         struct pid *pid;
1963         int session;
1964         int             i;
1965         struct file     *filp;
1966         
1967         if (!tty)
1968                 return;
1969         session  = tty->session;
1970         if (tty->ldisc.flush_buffer)
1971                 tty->ldisc.flush_buffer(tty);
1972         if (tty->driver->flush_buffer)
1973                 tty->driver->flush_buffer(tty);
1974         read_lock(&tasklist_lock);
1975         for_each_task_pid(session, PIDTYPE_SID, p, l, pid) {
1976                 if (p->signal->tty == tty || session > 0) {
1977                         printk(KERN_NOTICE "SAK: killed process %d"
1978                             " (%s): p->signal->session==tty->session\n",
1979                             p->pid, p->comm);
1980                         send_sig(SIGKILL, p, 1);
1981                         continue;
1982                 }
1983                 task_lock(p);
1984                 if (p->files) {
1985                         spin_lock(&p->files->file_lock);
1986                         for (i=0; i < p->files->max_fds; i++) {
1987                                 filp = fcheck_files(p->files, i);
1988                                 if (!filp)
1989                                         continue;
1990                                 if (filp->f_op->read == tty_read &&
1991                                     filp->private_data == tty) {
1992                                         printk(KERN_NOTICE "SAK: killed process %d"
1993                                             " (%s): fd#%d opened to the tty\n",
1994                                             p->pid, p->comm, i);
1995                                         send_sig(SIGKILL, p, 1);
1996                                         break;
1997                                 }
1998                         }
1999                         spin_unlock(&p->files->file_lock);
2000                 }
2001                 task_unlock(p);
2002         }
2003         read_unlock(&tasklist_lock);
2004 #endif
2005 }
2006
2007 /*
2008  * The tq handling here is a little racy - tty->SAK_work may already be queued.
2009  * Fortunately we don't need to worry, because if ->SAK_work is already queued,
2010  * the values which we write to it will be identical to the values which it
2011  * already has. --akpm
2012  */
2013 void do_SAK(struct tty_struct *tty)
2014 {
2015         if (!tty)
2016                 return;
2017         PREPARE_WORK(&tty->SAK_work, __do_SAK, tty);
2018         schedule_work(&tty->SAK_work);
2019 }
2020
2021 EXPORT_SYMBOL(do_SAK);
2022
2023 /*
2024  * This routine is called out of the software interrupt to flush data
2025  * from the flip buffer to the line discipline.
2026  */
2027 static void flush_to_ldisc(void *private_)
2028 {
2029         struct tty_struct *tty = (struct tty_struct *) private_;
2030         unsigned char   *cp;
2031         char            *fp;
2032         int             count;
2033         unsigned long flags;
2034
2035         if (test_bit(TTY_DONT_FLIP, &tty->flags)) {
2036                 /*
2037                  * Do it after the next timer tick:
2038                  */
2039                 schedule_delayed_work(&tty->flip.work, 1);
2040                 return;
2041         }
2042
2043         spin_lock_irqsave(&tty->read_lock, flags);
2044         if (tty->flip.buf_num) {
2045                 cp = tty->flip.char_buf + TTY_FLIPBUF_SIZE;
2046                 fp = tty->flip.flag_buf + TTY_FLIPBUF_SIZE;
2047                 tty->flip.buf_num = 0;
2048                 tty->flip.char_buf_ptr = tty->flip.char_buf;
2049                 tty->flip.flag_buf_ptr = tty->flip.flag_buf;
2050         } else {
2051                 cp = tty->flip.char_buf;
2052                 fp = tty->flip.flag_buf;
2053                 tty->flip.buf_num = 1;
2054                 tty->flip.char_buf_ptr = tty->flip.char_buf + TTY_FLIPBUF_SIZE;
2055                 tty->flip.flag_buf_ptr = tty->flip.flag_buf + TTY_FLIPBUF_SIZE;
2056         }
2057         count = tty->flip.count;
2058         tty->flip.count = 0;
2059         spin_unlock_irqrestore(&tty->read_lock, flags);
2060
2061         tty->ldisc.receive_buf(tty, cp, fp, count);
2062 }
2063
2064 /*
2065  * Routine which returns the baud rate of the tty
2066  *
2067  * Note that the baud_table needs to be kept in sync with the
2068  * include/asm/termbits.h file.
2069  */
2070 static int baud_table[] = {
2071         0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
2072         9600, 19200, 38400, 57600, 115200, 230400, 460800,
2073 #ifdef __sparc__
2074         76800, 153600, 307200, 614400, 921600
2075 #else
2076         500000, 576000, 921600, 1000000, 1152000, 1500000, 2000000,
2077         2500000, 3000000, 3500000, 4000000
2078 #endif
2079 };
2080
2081 static int n_baud_table = ARRAY_SIZE(baud_table);
2082
2083 int tty_termios_baud_rate(struct termios *termios)
2084 {
2085         unsigned int cbaud = termios->c_cflag & CBAUD;
2086
2087         if (cbaud & CBAUDEX) {
2088                 cbaud &= ~CBAUDEX;
2089
2090                 if (cbaud < 1 || cbaud + 15 > n_baud_table)
2091                         termios->c_cflag &= ~CBAUDEX;
2092                 else
2093                         cbaud += 15;
2094         }
2095
2096         return baud_table[cbaud];
2097 }
2098
2099 EXPORT_SYMBOL(tty_termios_baud_rate);
2100
2101 int tty_get_baud_rate(struct tty_struct *tty)
2102 {
2103         int baud = tty_termios_baud_rate(tty->termios);
2104
2105         if (baud == 38400 && tty->alt_speed) {
2106                 if (!tty->warned) {
2107                         printk(KERN_WARNING "Use of setserial/setrocket to "
2108                                             "set SPD_* flags is deprecated\n");
2109                         tty->warned = 1;
2110                 }
2111                 baud = tty->alt_speed;
2112         }
2113         
2114         return baud;
2115 }
2116
2117 EXPORT_SYMBOL(tty_get_baud_rate);
2118
2119 void tty_flip_buffer_push(struct tty_struct *tty)
2120 {
2121         if (tty->low_latency)
2122                 flush_to_ldisc((void *) tty);
2123         else
2124                 schedule_delayed_work(&tty->flip.work, 1);
2125 }
2126
2127 EXPORT_SYMBOL(tty_flip_buffer_push);
2128
2129 /*
2130  * This subroutine initializes a tty structure.
2131  */
2132 static void initialize_tty_struct(struct tty_struct *tty)
2133 {
2134         memset(tty, 0, sizeof(struct tty_struct));
2135         tty->magic = TTY_MAGIC;
2136         tty->ldisc = ldiscs[N_TTY];
2137         tty->pgrp = -1;
2138         tty->flip.char_buf_ptr = tty->flip.char_buf;
2139         tty->flip.flag_buf_ptr = tty->flip.flag_buf;
2140         INIT_WORK(&tty->flip.work, flush_to_ldisc, tty);
2141         init_MUTEX(&tty->flip.pty_sem);
2142         init_waitqueue_head(&tty->write_wait);
2143         init_waitqueue_head(&tty->read_wait);
2144         INIT_WORK(&tty->hangup_work, do_tty_hangup, tty);
2145         sema_init(&tty->atomic_read, 1);
2146         sema_init(&tty->atomic_write, 1);
2147         spin_lock_init(&tty->read_lock);
2148         INIT_LIST_HEAD(&tty->tty_files);
2149         INIT_WORK(&tty->SAK_work, NULL, NULL);
2150 }
2151
2152 /*
2153  * The default put_char routine if the driver did not define one.
2154  */
2155 static void tty_default_put_char(struct tty_struct *tty, unsigned char ch)
2156 {
2157         tty->driver->write(tty, 0, &ch, 1);
2158 }
2159
2160 static struct class_simple *tty_class;
2161
2162 /**
2163  * tty_register_device - register a tty device
2164  * @driver: the tty driver that describes the tty device
2165  * @index: the index in the tty driver for this tty device
2166  * @device: a struct device that is associated with this tty device.
2167  *      This field is optional, if there is no known struct device for this
2168  *      tty device it can be set to NULL safely.
2169  *
2170  * This call is required to be made to register an individual tty device if
2171  * the tty driver's flags have the TTY_DRIVER_NO_DEVFS bit set.  If that
2172  * bit is not set, this function should not be called.
2173  */
2174 void tty_register_device(struct tty_driver *driver, unsigned index,
2175                          struct device *device)
2176 {
2177         dev_t dev = MKDEV(driver->major, driver->minor_start) + index;
2178
2179         if (index >= driver->num) {
2180                 printk(KERN_ERR "Attempt to register invalid tty line number "
2181                        " (%d).\n", index);
2182                 return;
2183         }
2184
2185         devfs_mk_cdev(dev, S_IFCHR | S_IRUSR | S_IWUSR,
2186                         "%s%d", driver->devfs_name, index + driver->name_base);
2187
2188         /* we don't care about the ptys */
2189         /* how nice to hide this behind some crappy interface.. */
2190         if (driver->type != TTY_DRIVER_TYPE_PTY) {
2191                 char name[64];
2192                 tty_line_name(driver, index, name);
2193                 class_simple_device_add(tty_class, dev, device, name);
2194         }
2195 }
2196
2197 /**
2198  * tty_unregister_device - unregister a tty device
2199  * @driver: the tty driver that describes the tty device
2200  * @index: the index in the tty driver for this tty device
2201  *
2202  * If a tty device is registered with a call to tty_register_device() then
2203  * this function must be made when the tty device is gone.
2204  */
2205 void tty_unregister_device(struct tty_driver *driver, unsigned index)
2206 {
2207         devfs_remove("%s%d", driver->devfs_name, index + driver->name_base);
2208         class_simple_device_remove(MKDEV(driver->major, driver->minor_start) + index);
2209 }
2210
2211 EXPORT_SYMBOL(tty_register_device);
2212 EXPORT_SYMBOL(tty_unregister_device);
2213
2214 struct tty_driver *alloc_tty_driver(int lines)
2215 {
2216         struct tty_driver *driver;
2217
2218         driver = kmalloc(sizeof(struct tty_driver), GFP_KERNEL);
2219         if (driver) {
2220                 memset(driver, 0, sizeof(struct tty_driver));
2221                 driver->magic = TTY_DRIVER_MAGIC;
2222                 driver->num = lines;
2223                 /* later we'll move allocation of tables here */
2224         }
2225         return driver;
2226 }
2227
2228 void put_tty_driver(struct tty_driver *driver)
2229 {
2230         kfree(driver);
2231 }
2232
2233 void tty_set_operations(struct tty_driver *driver, struct tty_operations *op)
2234 {
2235         driver->open = op->open;
2236         driver->close = op->close;
2237         driver->write = op->write;
2238         driver->put_char = op->put_char;
2239         driver->flush_chars = op->flush_chars;
2240         driver->write_room = op->write_room;
2241         driver->chars_in_buffer = op->chars_in_buffer;
2242         driver->ioctl = op->ioctl;
2243         driver->set_termios = op->set_termios;
2244         driver->throttle = op->throttle;
2245         driver->unthrottle = op->unthrottle;
2246         driver->stop = op->stop;
2247         driver->start = op->start;
2248         driver->hangup = op->hangup;
2249         driver->break_ctl = op->break_ctl;
2250         driver->flush_buffer = op->flush_buffer;
2251         driver->set_ldisc = op->set_ldisc;
2252         driver->wait_until_sent = op->wait_until_sent;
2253         driver->send_xchar = op->send_xchar;
2254         driver->read_proc = op->read_proc;
2255         driver->write_proc = op->write_proc;
2256         driver->tiocmget = op->tiocmget;
2257         driver->tiocmset = op->tiocmset;
2258 }
2259
2260
2261 EXPORT_SYMBOL(alloc_tty_driver);
2262 EXPORT_SYMBOL(put_tty_driver);
2263 EXPORT_SYMBOL(tty_set_operations);
2264
2265 /*
2266  * Called by a tty driver to register itself.
2267  */
2268 int tty_register_driver(struct tty_driver *driver)
2269 {
2270         int error;
2271         int i;
2272         dev_t dev;
2273         void **p = NULL;
2274
2275         if (driver->flags & TTY_DRIVER_INSTALLED)
2276                 return 0;
2277
2278         if (!(driver->flags & TTY_DRIVER_DEVPTS_MEM)) {
2279                 p = kmalloc(driver->num * 3 * sizeof(void *), GFP_KERNEL);
2280                 if (!p)
2281                         return -ENOMEM;
2282                 memset(p, 0, driver->num * 3 * sizeof(void *));
2283         }
2284
2285         if (!driver->major) {
2286                 error = alloc_chrdev_region(&dev, driver->minor_start, driver->num,
2287                                                 (char*)driver->name);
2288                 if (!error) {
2289                         driver->major = MAJOR(dev);
2290                         driver->minor_start = MINOR(dev);
2291                 }
2292         } else {
2293                 dev = MKDEV(driver->major, driver->minor_start);
2294                 error = register_chrdev_region(dev, driver->num,
2295                                                 (char*)driver->name);
2296         }
2297         if (error < 0) {
2298                 kfree(p);
2299                 return error;
2300         }
2301
2302         if (p) {
2303                 driver->ttys = (struct tty_struct **)p;
2304                 driver->termios = (struct termios **)(p + driver->num);
2305                 driver->termios_locked = (struct termios **)(p + driver->num * 2);
2306         } else {
2307                 driver->ttys = NULL;
2308                 driver->termios = NULL;
2309                 driver->termios_locked = NULL;
2310         }
2311
2312         cdev_init(&driver->cdev, &tty_fops);
2313         driver->cdev.owner = driver->owner;
2314         error = cdev_add(&driver->cdev, dev, driver->num);
2315         if (error) {
2316                 cdev_del(&driver->cdev);
2317                 unregister_chrdev_region(dev, driver->num);
2318                 driver->ttys = NULL;
2319                 driver->termios = driver->termios_locked = NULL;
2320                 kfree(p);
2321                 return error;
2322         }
2323
2324         if (!driver->put_char)
2325                 driver->put_char = tty_default_put_char;
2326         
2327         list_add(&driver->tty_drivers, &tty_drivers);
2328         
2329         if ( !(driver->flags & TTY_DRIVER_NO_DEVFS) ) {
2330                 for(i = 0; i < driver->num; i++)
2331                     tty_register_device(driver, i, NULL);
2332         }
2333         proc_tty_register_driver(driver);
2334         return 0;
2335 }
2336
2337 EXPORT_SYMBOL(tty_register_driver);
2338
2339 /*
2340  * Called by a tty driver to unregister itself.
2341  */
2342 int tty_unregister_driver(struct tty_driver *driver)
2343 {
2344         int i;
2345         struct termios *tp;
2346         void *p;
2347
2348         if (driver->refcount)
2349                 return -EBUSY;
2350
2351         unregister_chrdev_region(MKDEV(driver->major, driver->minor_start),
2352                                 driver->num);
2353
2354         list_del(&driver->tty_drivers);
2355
2356         /*
2357          * Free the termios and termios_locked structures because
2358          * we don't want to get memory leaks when modular tty
2359          * drivers are removed from the kernel.
2360          */
2361         for (i = 0; i < driver->num; i++) {
2362                 tp = driver->termios[i];
2363                 if (tp) {
2364                         driver->termios[i] = NULL;
2365                         kfree(tp);
2366                 }
2367                 tp = driver->termios_locked[i];
2368                 if (tp) {
2369                         driver->termios_locked[i] = NULL;
2370                         kfree(tp);
2371                 }
2372                 if (!(driver->flags & TTY_DRIVER_NO_DEVFS))
2373                         tty_unregister_device(driver, i);
2374         }
2375         p = driver->ttys;
2376         proc_tty_unregister_driver(driver);
2377         driver->ttys = NULL;
2378         driver->termios = driver->termios_locked = NULL;
2379         kfree(p);
2380         cdev_del(&driver->cdev);
2381         return 0;
2382 }
2383
2384 EXPORT_SYMBOL(tty_unregister_driver);
2385
2386
2387 /*
2388  * Initialize the console device. This is called *early*, so
2389  * we can't necessarily depend on lots of kernel help here.
2390  * Just do some early initializations, and do the complex setup
2391  * later.
2392  */
2393 void __init console_init(void)
2394 {
2395         initcall_t *call;
2396
2397         /* Setup the default TTY line discipline. */
2398         (void) tty_register_ldisc(N_TTY, &tty_ldisc_N_TTY);
2399
2400         /*
2401          * set up the console device so that later boot sequences can 
2402          * inform about problems etc..
2403          */
2404 #ifdef CONFIG_EARLY_PRINTK
2405         disable_early_printk();
2406 #endif
2407 #ifdef CONFIG_SERIAL_68360
2408         /* This is not a console initcall. I know not what it's doing here.
2409            So I haven't moved it. dwmw2 */
2410         rs_360_init();
2411 #endif
2412         call = &__con_initcall_start;
2413         while (call < &__con_initcall_end) {
2414                 (*call)();
2415                 call++;
2416         }
2417 }
2418
2419 #ifdef CONFIG_VT
2420 extern int vty_init(void);
2421 #endif
2422
2423 static int __init tty_class_init(void)
2424 {
2425         tty_class = class_simple_create(THIS_MODULE, "tty");
2426         if (IS_ERR(tty_class))
2427                 return PTR_ERR(tty_class);
2428         return 0;
2429 }
2430
2431 postcore_initcall(tty_class_init);
2432
2433 /* 3/2004 jmc: why do these devices exist? */
2434
2435 static struct cdev tty_cdev, console_cdev;
2436 #ifdef CONFIG_UNIX98_PTYS
2437 static struct cdev ptmx_cdev;
2438 #endif
2439 #ifdef CONFIG_VT
2440 static struct cdev vc0_cdev;
2441 #endif
2442
2443 /*
2444  * Ok, now we can initialize the rest of the tty devices and can count
2445  * on memory allocations, interrupts etc..
2446  */
2447 static int __init tty_init(void)
2448 {
2449         cdev_init(&tty_cdev, &tty_fops);
2450         if (cdev_add(&tty_cdev, MKDEV(TTYAUX_MAJOR, 0), 1) ||
2451             register_chrdev_region(MKDEV(TTYAUX_MAJOR, 0), 1, "/dev/tty") < 0)
2452                 panic("Couldn't register /dev/tty driver\n");
2453         devfs_mk_cdev(MKDEV(TTYAUX_MAJOR, 0), S_IFCHR|S_IRUGO|S_IWUGO, "tty");
2454         class_simple_device_add(tty_class, MKDEV(TTYAUX_MAJOR, 0), NULL, "tty");
2455
2456         cdev_init(&console_cdev, &console_fops);
2457         if (cdev_add(&console_cdev, MKDEV(TTYAUX_MAJOR, 1), 1) ||
2458             register_chrdev_region(MKDEV(TTYAUX_MAJOR, 1), 1, "/dev/console") < 0)
2459                 panic("Couldn't register /dev/console driver\n");
2460         devfs_mk_cdev(MKDEV(TTYAUX_MAJOR, 1), S_IFCHR|S_IRUSR|S_IWUSR, "console");
2461         class_simple_device_add(tty_class, MKDEV(TTYAUX_MAJOR, 1), NULL, "console");
2462
2463 #ifdef CONFIG_UNIX98_PTYS
2464         cdev_init(&ptmx_cdev, &tty_fops);
2465         if (cdev_add(&ptmx_cdev, MKDEV(TTYAUX_MAJOR, 2), 1) ||
2466             register_chrdev_region(MKDEV(TTYAUX_MAJOR, 2), 1, "/dev/ptmx") < 0)
2467                 panic("Couldn't register /dev/ptmx driver\n");
2468         devfs_mk_cdev(MKDEV(TTYAUX_MAJOR, 2), S_IFCHR|S_IRUGO|S_IWUGO, "ptmx");
2469         class_simple_device_add(tty_class, MKDEV(TTYAUX_MAJOR, 2), NULL, "ptmx");
2470 #endif
2471
2472 #ifdef CONFIG_VT
2473         cdev_init(&vc0_cdev, &console_fops);
2474         if (cdev_add(&vc0_cdev, MKDEV(TTY_MAJOR, 0), 1) ||
2475             register_chrdev_region(MKDEV(TTY_MAJOR, 0), 1, "/dev/vc/0") < 0)
2476                 panic("Couldn't register /dev/tty0 driver\n");
2477         devfs_mk_cdev(MKDEV(TTY_MAJOR, 0), S_IFCHR|S_IRUSR|S_IWUSR, "vc/0");
2478         class_simple_device_add(tty_class, MKDEV(TTY_MAJOR, 0), NULL, "tty0");
2479
2480         vty_init();
2481 #endif
2482         return 0;
2483 }
2484 module_init(tty_init);