source: trunk/packages/xen-3.1/xen-3.1/linux-2.6-xen-sparse/drivers/char/tty_io.c @ 34

Last change on this file since 34 was 34, checked in by hartmans, 18 years ago

Add xen and xen-common

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