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