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