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