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