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