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