328ff5b544a5622405d98bf6c1da9107bdf74ef6
[firefly-linux-kernel-4.4.55.git] / drivers / tty / tty_ldisc.c
1 #include <linux/types.h>
2 #include <linux/errno.h>
3 #include <linux/kmod.h>
4 #include <linux/sched.h>
5 #include <linux/interrupt.h>
6 #include <linux/tty.h>
7 #include <linux/tty_driver.h>
8 #include <linux/file.h>
9 #include <linux/mm.h>
10 #include <linux/string.h>
11 #include <linux/slab.h>
12 #include <linux/poll.h>
13 #include <linux/proc_fs.h>
14 #include <linux/init.h>
15 #include <linux/module.h>
16 #include <linux/device.h>
17 #include <linux/wait.h>
18 #include <linux/bitops.h>
19 #include <linux/seq_file.h>
20 #include <linux/uaccess.h>
21 #include <linux/ratelimit.h>
22
23 #undef LDISC_DEBUG_HANGUP
24
25 #ifdef LDISC_DEBUG_HANGUP
26 #define tty_ldisc_debug(tty, f, args...) ({                                    \
27         char __b[64];                                                          \
28         printk(KERN_DEBUG "%s: %s: " f, __func__, tty_name(tty, __b), ##args); \
29 })
30 #else
31 #define tty_ldisc_debug(tty, f, args...)
32 #endif
33
34 /*
35  *      This guards the refcounted line discipline lists. The lock
36  *      must be taken with irqs off because there are hangup path
37  *      callers who will do ldisc lookups and cannot sleep.
38  */
39
40 static DEFINE_RAW_SPINLOCK(tty_ldisc_lock);
41 static DECLARE_WAIT_QUEUE_HEAD(tty_ldisc_wait);
42 /* Line disc dispatch table */
43 static struct tty_ldisc_ops *tty_ldiscs[NR_LDISCS];
44
45 static inline struct tty_ldisc *get_ldisc(struct tty_ldisc *ld)
46 {
47         if (ld)
48                 atomic_inc(&ld->users);
49         return ld;
50 }
51
52 static void put_ldisc(struct tty_ldisc *ld)
53 {
54         unsigned long flags;
55
56         if (WARN_ON_ONCE(!ld))
57                 return;
58
59         /*
60          * If this is the last user, free the ldisc, and
61          * release the ldisc ops.
62          *
63          * We really want an "atomic_dec_and_raw_lock_irqsave()",
64          * but we don't have it, so this does it by hand.
65          */
66         raw_spin_lock_irqsave(&tty_ldisc_lock, flags);
67         if (atomic_dec_and_test(&ld->users)) {
68                 struct tty_ldisc_ops *ldo = ld->ops;
69
70                 ldo->refcount--;
71                 module_put(ldo->owner);
72                 raw_spin_unlock_irqrestore(&tty_ldisc_lock, flags);
73
74                 kfree(ld);
75                 return;
76         }
77         raw_spin_unlock_irqrestore(&tty_ldisc_lock, flags);
78
79         if (waitqueue_active(&ld->wq_idle))
80                 wake_up(&ld->wq_idle);
81 }
82
83 /**
84  *      tty_register_ldisc      -       install a line discipline
85  *      @disc: ldisc number
86  *      @new_ldisc: pointer to the ldisc object
87  *
88  *      Installs a new line discipline into the kernel. The discipline
89  *      is set up as unreferenced and then made available to the kernel
90  *      from this point onwards.
91  *
92  *      Locking:
93  *              takes tty_ldisc_lock to guard against ldisc races
94  */
95
96 int tty_register_ldisc(int disc, struct tty_ldisc_ops *new_ldisc)
97 {
98         unsigned long flags;
99         int ret = 0;
100
101         if (disc < N_TTY || disc >= NR_LDISCS)
102                 return -EINVAL;
103
104         raw_spin_lock_irqsave(&tty_ldisc_lock, flags);
105         tty_ldiscs[disc] = new_ldisc;
106         new_ldisc->num = disc;
107         new_ldisc->refcount = 0;
108         raw_spin_unlock_irqrestore(&tty_ldisc_lock, flags);
109
110         return ret;
111 }
112 EXPORT_SYMBOL(tty_register_ldisc);
113
114 /**
115  *      tty_unregister_ldisc    -       unload a line discipline
116  *      @disc: ldisc number
117  *      @new_ldisc: pointer to the ldisc object
118  *
119  *      Remove a line discipline from the kernel providing it is not
120  *      currently in use.
121  *
122  *      Locking:
123  *              takes tty_ldisc_lock to guard against ldisc races
124  */
125
126 int tty_unregister_ldisc(int disc)
127 {
128         unsigned long flags;
129         int ret = 0;
130
131         if (disc < N_TTY || disc >= NR_LDISCS)
132                 return -EINVAL;
133
134         raw_spin_lock_irqsave(&tty_ldisc_lock, flags);
135         if (tty_ldiscs[disc]->refcount)
136                 ret = -EBUSY;
137         else
138                 tty_ldiscs[disc] = NULL;
139         raw_spin_unlock_irqrestore(&tty_ldisc_lock, flags);
140
141         return ret;
142 }
143 EXPORT_SYMBOL(tty_unregister_ldisc);
144
145 static struct tty_ldisc_ops *get_ldops(int disc)
146 {
147         unsigned long flags;
148         struct tty_ldisc_ops *ldops, *ret;
149
150         raw_spin_lock_irqsave(&tty_ldisc_lock, flags);
151         ret = ERR_PTR(-EINVAL);
152         ldops = tty_ldiscs[disc];
153         if (ldops) {
154                 ret = ERR_PTR(-EAGAIN);
155                 if (try_module_get(ldops->owner)) {
156                         ldops->refcount++;
157                         ret = ldops;
158                 }
159         }
160         raw_spin_unlock_irqrestore(&tty_ldisc_lock, flags);
161         return ret;
162 }
163
164 static void put_ldops(struct tty_ldisc_ops *ldops)
165 {
166         unsigned long flags;
167
168         raw_spin_lock_irqsave(&tty_ldisc_lock, flags);
169         ldops->refcount--;
170         module_put(ldops->owner);
171         raw_spin_unlock_irqrestore(&tty_ldisc_lock, flags);
172 }
173
174 /**
175  *      tty_ldisc_get           -       take a reference to an ldisc
176  *      @disc: ldisc number
177  *
178  *      Takes a reference to a line discipline. Deals with refcounts and
179  *      module locking counts. Returns NULL if the discipline is not available.
180  *      Returns a pointer to the discipline and bumps the ref count if it is
181  *      available
182  *
183  *      Locking:
184  *              takes tty_ldisc_lock to guard against ldisc races
185  */
186
187 static struct tty_ldisc *tty_ldisc_get(int disc)
188 {
189         struct tty_ldisc *ld;
190         struct tty_ldisc_ops *ldops;
191
192         if (disc < N_TTY || disc >= NR_LDISCS)
193                 return ERR_PTR(-EINVAL);
194
195         /*
196          * Get the ldisc ops - we may need to request them to be loaded
197          * dynamically and try again.
198          */
199         ldops = get_ldops(disc);
200         if (IS_ERR(ldops)) {
201                 request_module("tty-ldisc-%d", disc);
202                 ldops = get_ldops(disc);
203                 if (IS_ERR(ldops))
204                         return ERR_CAST(ldops);
205         }
206
207         ld = kmalloc(sizeof(struct tty_ldisc), GFP_KERNEL);
208         if (ld == NULL) {
209                 put_ldops(ldops);
210                 return ERR_PTR(-ENOMEM);
211         }
212
213         ld->ops = ldops;
214         atomic_set(&ld->users, 1);
215         init_waitqueue_head(&ld->wq_idle);
216
217         return ld;
218 }
219
220 static void *tty_ldiscs_seq_start(struct seq_file *m, loff_t *pos)
221 {
222         return (*pos < NR_LDISCS) ? pos : NULL;
223 }
224
225 static void *tty_ldiscs_seq_next(struct seq_file *m, void *v, loff_t *pos)
226 {
227         (*pos)++;
228         return (*pos < NR_LDISCS) ? pos : NULL;
229 }
230
231 static void tty_ldiscs_seq_stop(struct seq_file *m, void *v)
232 {
233 }
234
235 static int tty_ldiscs_seq_show(struct seq_file *m, void *v)
236 {
237         int i = *(loff_t *)v;
238         struct tty_ldisc_ops *ldops;
239
240         ldops = get_ldops(i);
241         if (IS_ERR(ldops))
242                 return 0;
243         seq_printf(m, "%-10s %2d\n", ldops->name ? ldops->name : "???", i);
244         put_ldops(ldops);
245         return 0;
246 }
247
248 static const struct seq_operations tty_ldiscs_seq_ops = {
249         .start  = tty_ldiscs_seq_start,
250         .next   = tty_ldiscs_seq_next,
251         .stop   = tty_ldiscs_seq_stop,
252         .show   = tty_ldiscs_seq_show,
253 };
254
255 static int proc_tty_ldiscs_open(struct inode *inode, struct file *file)
256 {
257         return seq_open(file, &tty_ldiscs_seq_ops);
258 }
259
260 const struct file_operations tty_ldiscs_proc_fops = {
261         .owner          = THIS_MODULE,
262         .open           = proc_tty_ldiscs_open,
263         .read           = seq_read,
264         .llseek         = seq_lseek,
265         .release        = seq_release,
266 };
267
268 /**
269  *      tty_ldisc_assign        -       set ldisc on a tty
270  *      @tty: tty to assign
271  *      @ld: line discipline
272  *
273  *      Install an instance of a line discipline into a tty structure. The
274  *      ldisc must have a reference count above zero to ensure it remains.
275  *      The tty instance refcount starts at zero.
276  *
277  *      Locking:
278  *              Caller must hold references
279  */
280
281 static void tty_ldisc_assign(struct tty_struct *tty, struct tty_ldisc *ld)
282 {
283         tty->ldisc = ld;
284 }
285
286 /**
287  *      tty_ldisc_try           -       internal helper
288  *      @tty: the tty
289  *
290  *      Make a single attempt to grab and bump the refcount on
291  *      the tty ldisc. Return 0 on failure or 1 on success. This is
292  *      used to implement both the waiting and non waiting versions
293  *      of tty_ldisc_ref
294  *
295  *      Locking: takes tty_ldisc_lock
296  */
297
298 static struct tty_ldisc *tty_ldisc_try(struct tty_struct *tty)
299 {
300         unsigned long flags;
301         struct tty_ldisc *ld;
302
303         raw_spin_lock_irqsave(&tty_ldisc_lock, flags);
304         ld = NULL;
305         if (test_bit(TTY_LDISC, &tty->flags))
306                 ld = get_ldisc(tty->ldisc);
307         raw_spin_unlock_irqrestore(&tty_ldisc_lock, flags);
308         return ld;
309 }
310
311 /**
312  *      tty_ldisc_ref_wait      -       wait for the tty ldisc
313  *      @tty: tty device
314  *
315  *      Dereference the line discipline for the terminal and take a
316  *      reference to it. If the line discipline is in flux then
317  *      wait patiently until it changes.
318  *
319  *      Note: Must not be called from an IRQ/timer context. The caller
320  *      must also be careful not to hold other locks that will deadlock
321  *      against a discipline change, such as an existing ldisc reference
322  *      (which we check for)
323  *
324  *      Locking: call functions take tty_ldisc_lock
325  */
326
327 struct tty_ldisc *tty_ldisc_ref_wait(struct tty_struct *tty)
328 {
329         struct tty_ldisc *ld;
330
331         /* wait_event is a macro */
332         wait_event(tty_ldisc_wait, (ld = tty_ldisc_try(tty)) != NULL);
333         return ld;
334 }
335 EXPORT_SYMBOL_GPL(tty_ldisc_ref_wait);
336
337 /**
338  *      tty_ldisc_ref           -       get the tty ldisc
339  *      @tty: tty device
340  *
341  *      Dereference the line discipline for the terminal and take a
342  *      reference to it. If the line discipline is in flux then
343  *      return NULL. Can be called from IRQ and timer functions.
344  *
345  *      Locking: called functions take tty_ldisc_lock
346  */
347
348 struct tty_ldisc *tty_ldisc_ref(struct tty_struct *tty)
349 {
350         return tty_ldisc_try(tty);
351 }
352 EXPORT_SYMBOL_GPL(tty_ldisc_ref);
353
354 /**
355  *      tty_ldisc_deref         -       free a tty ldisc reference
356  *      @ld: reference to free up
357  *
358  *      Undoes the effect of tty_ldisc_ref or tty_ldisc_ref_wait. May
359  *      be called in IRQ context.
360  *
361  *      Locking: takes tty_ldisc_lock
362  */
363
364 void tty_ldisc_deref(struct tty_ldisc *ld)
365 {
366         put_ldisc(ld);
367 }
368 EXPORT_SYMBOL_GPL(tty_ldisc_deref);
369
370 static inline void tty_ldisc_put(struct tty_ldisc *ld)
371 {
372         put_ldisc(ld);
373 }
374
375 /**
376  *      tty_ldisc_enable        -       allow ldisc use
377  *      @tty: terminal to activate ldisc on
378  *
379  *      Set the TTY_LDISC flag when the line discipline can be called
380  *      again. Do necessary wakeups for existing sleepers. Clear the LDISC
381  *      changing flag to indicate any ldisc change is now over.
382  *
383  *      Note: nobody should set the TTY_LDISC bit except via this function.
384  *      Clearing directly is allowed.
385  */
386
387 static void tty_ldisc_enable(struct tty_struct *tty)
388 {
389         clear_bit(TTY_LDISC_HALTED, &tty->flags);
390         set_bit(TTY_LDISC, &tty->flags);
391         clear_bit(TTY_LDISC_CHANGING, &tty->flags);
392         wake_up(&tty_ldisc_wait);
393 }
394
395 /**
396  *      tty_ldisc_flush -       flush line discipline queue
397  *      @tty: tty
398  *
399  *      Flush the line discipline queue (if any) for this tty. If there
400  *      is no line discipline active this is a no-op.
401  */
402
403 void tty_ldisc_flush(struct tty_struct *tty)
404 {
405         struct tty_ldisc *ld = tty_ldisc_ref(tty);
406         if (ld) {
407                 if (ld->ops->flush_buffer)
408                         ld->ops->flush_buffer(tty);
409                 tty_ldisc_deref(ld);
410         }
411         tty_buffer_flush(tty);
412 }
413 EXPORT_SYMBOL_GPL(tty_ldisc_flush);
414
415 /**
416  *      tty_set_termios_ldisc           -       set ldisc field
417  *      @tty: tty structure
418  *      @num: line discipline number
419  *
420  *      This is probably overkill for real world processors but
421  *      they are not on hot paths so a little discipline won't do
422  *      any harm.
423  *
424  *      Locking: takes termios_mutex
425  */
426
427 static void tty_set_termios_ldisc(struct tty_struct *tty, int num)
428 {
429         mutex_lock(&tty->termios_mutex);
430         tty->termios.c_line = num;
431         mutex_unlock(&tty->termios_mutex);
432 }
433
434 /**
435  *      tty_ldisc_open          -       open a line discipline
436  *      @tty: tty we are opening the ldisc on
437  *      @ld: discipline to open
438  *
439  *      A helper opening method. Also a convenient debugging and check
440  *      point.
441  *
442  *      Locking: always called with BTM already held.
443  */
444
445 static int tty_ldisc_open(struct tty_struct *tty, struct tty_ldisc *ld)
446 {
447         WARN_ON(test_and_set_bit(TTY_LDISC_OPEN, &tty->flags));
448         if (ld->ops->open) {
449                 int ret;
450                 /* BTM here locks versus a hangup event */
451                 ret = ld->ops->open(tty);
452                 if (ret)
453                         clear_bit(TTY_LDISC_OPEN, &tty->flags);
454                 return ret;
455         }
456         return 0;
457 }
458
459 /**
460  *      tty_ldisc_close         -       close a line discipline
461  *      @tty: tty we are opening the ldisc on
462  *      @ld: discipline to close
463  *
464  *      A helper close method. Also a convenient debugging and check
465  *      point.
466  */
467
468 static void tty_ldisc_close(struct tty_struct *tty, struct tty_ldisc *ld)
469 {
470         WARN_ON(!test_bit(TTY_LDISC_OPEN, &tty->flags));
471         clear_bit(TTY_LDISC_OPEN, &tty->flags);
472         if (ld->ops->close)
473                 ld->ops->close(tty);
474 }
475
476 /**
477  *      tty_ldisc_restore       -       helper for tty ldisc change
478  *      @tty: tty to recover
479  *      @old: previous ldisc
480  *
481  *      Restore the previous line discipline or N_TTY when a line discipline
482  *      change fails due to an open error
483  */
484
485 static void tty_ldisc_restore(struct tty_struct *tty, struct tty_ldisc *old)
486 {
487         char buf[64];
488         struct tty_ldisc *new_ldisc;
489         int r;
490
491         /* There is an outstanding reference here so this is safe */
492         old = tty_ldisc_get(old->ops->num);
493         WARN_ON(IS_ERR(old));
494         tty_ldisc_assign(tty, old);
495         tty_set_termios_ldisc(tty, old->ops->num);
496         if (tty_ldisc_open(tty, old) < 0) {
497                 tty_ldisc_put(old);
498                 /* This driver is always present */
499                 new_ldisc = tty_ldisc_get(N_TTY);
500                 if (IS_ERR(new_ldisc))
501                         panic("n_tty: get");
502                 tty_ldisc_assign(tty, new_ldisc);
503                 tty_set_termios_ldisc(tty, N_TTY);
504                 r = tty_ldisc_open(tty, new_ldisc);
505                 if (r < 0)
506                         panic("Couldn't open N_TTY ldisc for "
507                               "%s --- error %d.",
508                               tty_name(tty, buf), r);
509         }
510 }
511
512 /**
513  *      tty_ldisc_wait_idle     -       wait for the ldisc to become idle
514  *      @tty: tty to wait for
515  *      @timeout: for how long to wait at most
516  *
517  *      Wait for the line discipline to become idle. The discipline must
518  *      have been halted for this to guarantee it remains idle.
519  */
520 static int tty_ldisc_wait_idle(struct tty_struct *tty, long timeout)
521 {
522         long ret;
523         ret = wait_event_timeout(tty->ldisc->wq_idle,
524                         atomic_read(&tty->ldisc->users) == 1, timeout);
525         return ret > 0 ? 0 : -EBUSY;
526 }
527
528 /**
529  *      tty_ldisc_halt          -       shut down the line discipline
530  *      @tty: tty device
531  *      @o_tty: paired pty device (can be NULL)
532  *      @timeout: # of jiffies to wait for ldisc refs to be released
533  *
534  *      Shut down the line discipline and work queue for this tty device and
535  *      its paired pty (if exists). Clearing the TTY_LDISC flag ensures
536  *      no further references can be obtained, while waiting for existing
537  *      references to be released ensures no more data is fed to the ldisc.
538  *
539  *      You need to do a 'flush_scheduled_work()' (outside the ldisc_mutex)
540  *      in order to make sure any currently executing ldisc work is also
541  *      flushed.
542  */
543
544 static int tty_ldisc_halt(struct tty_struct *tty, struct tty_struct *o_tty,
545                           long timeout)
546 {
547         int retval;
548
549         clear_bit(TTY_LDISC, &tty->flags);
550         if (o_tty)
551                 clear_bit(TTY_LDISC, &o_tty->flags);
552
553         retval = tty_ldisc_wait_idle(tty, timeout);
554         if (!retval && o_tty)
555                 retval = tty_ldisc_wait_idle(o_tty, timeout);
556         if (retval)
557                 return retval;
558
559         set_bit(TTY_LDISC_HALTED, &tty->flags);
560         if (o_tty)
561                 set_bit(TTY_LDISC_HALTED, &o_tty->flags);
562
563         return 0;
564 }
565
566 /**
567  *      tty_ldisc_hangup_halt - halt the line discipline for hangup
568  *      @tty: tty being hung up
569  *
570  *      Shut down the line discipline and work queue for the tty device
571  *      being hungup. Clear the TTY_LDISC flag to ensure no further
572  *      references can be obtained and wait for remaining references to be
573  *      released to ensure no more data is fed to this ldisc.
574  *      Caller must hold legacy and ->ldisc_mutex.
575  *
576  *      NB: tty_set_ldisc() is prevented from changing the ldisc concurrently
577  *      with this function by checking the TTY_HUPPING flag.
578  */
579 static bool tty_ldisc_hangup_halt(struct tty_struct *tty)
580 {
581         char cur_n[TASK_COMM_LEN], tty_n[64];
582         long timeout = 3 * HZ;
583
584         clear_bit(TTY_LDISC, &tty->flags);
585
586         if (tty->ldisc) {       /* Not yet closed */
587                 tty_unlock(tty);
588
589                 while (tty_ldisc_wait_idle(tty, timeout) == -EBUSY) {
590                         timeout = MAX_SCHEDULE_TIMEOUT;
591                         printk_ratelimited(KERN_WARNING
592                                 "%s: waiting (%s) for %s took too long, but we keep waiting...\n",
593                                 __func__, get_task_comm(cur_n, current),
594                                 tty_name(tty, tty_n));
595                 }
596
597                 set_bit(TTY_LDISC_HALTED, &tty->flags);
598
599                 /* must reacquire both locks and preserve lock order */
600                 mutex_unlock(&tty->ldisc_mutex);
601                 tty_lock(tty);
602                 mutex_lock(&tty->ldisc_mutex);
603         }
604         return !!tty->ldisc;
605 }
606
607 /**
608  *      tty_set_ldisc           -       set line discipline
609  *      @tty: the terminal to set
610  *      @ldisc: the line discipline
611  *
612  *      Set the discipline of a tty line. Must be called from a process
613  *      context. The ldisc change logic has to protect itself against any
614  *      overlapping ldisc change (including on the other end of pty pairs),
615  *      the close of one side of a tty/pty pair, and eventually hangup.
616  *
617  *      Locking: takes tty_ldisc_lock, termios_mutex
618  */
619
620 int tty_set_ldisc(struct tty_struct *tty, int ldisc)
621 {
622         int retval;
623         struct tty_ldisc *o_ldisc, *new_ldisc;
624         struct tty_struct *o_tty;
625
626         new_ldisc = tty_ldisc_get(ldisc);
627         if (IS_ERR(new_ldisc))
628                 return PTR_ERR(new_ldisc);
629
630         tty_lock(tty);
631         /*
632          *      We need to look at the tty locking here for pty/tty pairs
633          *      when both sides try to change in parallel.
634          */
635
636         o_tty = tty->link;      /* o_tty is the pty side or NULL */
637
638
639         /*
640          *      Check the no-op case
641          */
642
643         if (tty->ldisc->ops->num == ldisc) {
644                 tty_unlock(tty);
645                 tty_ldisc_put(new_ldisc);
646                 return 0;
647         }
648
649         tty_unlock(tty);
650         /*
651          *      Problem: What do we do if this blocks ?
652          *      We could deadlock here
653          */
654
655         tty_wait_until_sent(tty, 0);
656
657         tty_lock(tty);
658         mutex_lock(&tty->ldisc_mutex);
659
660         /*
661          *      We could be midstream of another ldisc change which has
662          *      dropped the lock during processing. If so we need to wait.
663          */
664
665         while (test_bit(TTY_LDISC_CHANGING, &tty->flags)) {
666                 mutex_unlock(&tty->ldisc_mutex);
667                 tty_unlock(tty);
668                 wait_event(tty_ldisc_wait,
669                         test_bit(TTY_LDISC_CHANGING, &tty->flags) == 0);
670                 tty_lock(tty);
671                 mutex_lock(&tty->ldisc_mutex);
672         }
673
674         set_bit(TTY_LDISC_CHANGING, &tty->flags);
675
676         /*
677          *      No more input please, we are switching. The new ldisc
678          *      will update this value in the ldisc open function
679          */
680
681         tty->receive_room = 0;
682
683         o_ldisc = tty->ldisc;
684
685         tty_unlock(tty);
686         /*
687          *      Make sure we don't change while someone holds a
688          *      reference to the line discipline. The TTY_LDISC bit
689          *      prevents anyone taking a reference once it is clear.
690          *      We need the lock to avoid racing reference takers.
691          *
692          *      We must clear the TTY_LDISC bit here to avoid a livelock
693          *      with a userspace app continually trying to use the tty in
694          *      parallel to the change and re-referencing the tty.
695          */
696
697         retval = tty_ldisc_halt(tty, o_tty, 5 * HZ);
698
699         /*
700          * Wait for hangup to complete, if pending.
701          * We must drop the mutex here in case a hangup is also in process.
702          */
703
704         mutex_unlock(&tty->ldisc_mutex);
705
706         flush_work(&tty->hangup_work);
707
708         tty_lock(tty);
709         mutex_lock(&tty->ldisc_mutex);
710
711         /* handle wait idle failure locked */
712         if (retval) {
713                 tty_ldisc_put(new_ldisc);
714                 goto enable;
715         }
716
717         if (test_bit(TTY_HUPPING, &tty->flags)) {
718                 /* We were raced by the hangup method. It will have stomped
719                    the ldisc data and closed the ldisc down */
720                 clear_bit(TTY_LDISC_CHANGING, &tty->flags);
721                 mutex_unlock(&tty->ldisc_mutex);
722                 tty_ldisc_put(new_ldisc);
723                 tty_unlock(tty);
724                 return -EIO;
725         }
726
727         /* Shutdown the current discipline. */
728         tty_ldisc_close(tty, o_ldisc);
729
730         /* Now set up the new line discipline. */
731         tty_ldisc_assign(tty, new_ldisc);
732         tty_set_termios_ldisc(tty, ldisc);
733
734         retval = tty_ldisc_open(tty, new_ldisc);
735         if (retval < 0) {
736                 /* Back to the old one or N_TTY if we can't */
737                 tty_ldisc_put(new_ldisc);
738                 tty_ldisc_restore(tty, o_ldisc);
739         }
740
741         /* At this point we hold a reference to the new ldisc and a
742            a reference to the old ldisc. If we ended up flipping back
743            to the existing ldisc we have two references to it */
744
745         if (tty->ldisc->ops->num != o_ldisc->ops->num && tty->ops->set_ldisc)
746                 tty->ops->set_ldisc(tty);
747
748         tty_ldisc_put(o_ldisc);
749
750 enable:
751         /*
752          *      Allow ldisc referencing to occur again
753          */
754
755         tty_ldisc_enable(tty);
756         if (o_tty)
757                 tty_ldisc_enable(o_tty);
758
759         /* Restart the work queue in case no characters kick it off. Safe if
760            already running */
761         schedule_work(&tty->port->buf.work);
762         if (o_tty)
763                 schedule_work(&o_tty->port->buf.work);
764
765         mutex_unlock(&tty->ldisc_mutex);
766         tty_unlock(tty);
767         return retval;
768 }
769
770 /**
771  *      tty_reset_termios       -       reset terminal state
772  *      @tty: tty to reset
773  *
774  *      Restore a terminal to the driver default state.
775  */
776
777 static void tty_reset_termios(struct tty_struct *tty)
778 {
779         mutex_lock(&tty->termios_mutex);
780         tty->termios = tty->driver->init_termios;
781         tty->termios.c_ispeed = tty_termios_input_baud_rate(&tty->termios);
782         tty->termios.c_ospeed = tty_termios_baud_rate(&tty->termios);
783         mutex_unlock(&tty->termios_mutex);
784 }
785
786
787 /**
788  *      tty_ldisc_reinit        -       reinitialise the tty ldisc
789  *      @tty: tty to reinit
790  *      @ldisc: line discipline to reinitialize
791  *
792  *      Switch the tty to a line discipline and leave the ldisc
793  *      state closed
794  */
795
796 static int tty_ldisc_reinit(struct tty_struct *tty, int ldisc)
797 {
798         struct tty_ldisc *ld = tty_ldisc_get(ldisc);
799
800         if (IS_ERR(ld))
801                 return -1;
802
803         tty_ldisc_close(tty, tty->ldisc);
804         tty_ldisc_put(tty->ldisc);
805         tty->ldisc = NULL;
806         /*
807          *      Switch the line discipline back
808          */
809         tty_ldisc_assign(tty, ld);
810         tty_set_termios_ldisc(tty, ldisc);
811
812         return 0;
813 }
814
815 /**
816  *      tty_ldisc_hangup                -       hangup ldisc reset
817  *      @tty: tty being hung up
818  *
819  *      Some tty devices reset their termios when they receive a hangup
820  *      event. In that situation we must also switch back to N_TTY properly
821  *      before we reset the termios data.
822  *
823  *      Locking: We can take the ldisc mutex as the rest of the code is
824  *      careful to allow for this.
825  *
826  *      In the pty pair case this occurs in the close() path of the
827  *      tty itself so we must be careful about locking rules.
828  */
829
830 void tty_ldisc_hangup(struct tty_struct *tty)
831 {
832         struct tty_ldisc *ld;
833         int reset = tty->driver->flags & TTY_DRIVER_RESET_TERMIOS;
834         int err = 0;
835
836         tty_ldisc_debug(tty, "closing ldisc: %p\n", tty->ldisc);
837
838         /*
839          * FIXME! What are the locking issues here? This may me overdoing
840          * things... This question is especially important now that we've
841          * removed the irqlock.
842          */
843         ld = tty_ldisc_ref(tty);
844         if (ld != NULL) {
845                 /* We may have no line discipline at this point */
846                 if (ld->ops->flush_buffer)
847                         ld->ops->flush_buffer(tty);
848                 tty_driver_flush_buffer(tty);
849                 if ((test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) &&
850                     ld->ops->write_wakeup)
851                         ld->ops->write_wakeup(tty);
852                 if (ld->ops->hangup)
853                         ld->ops->hangup(tty);
854                 tty_ldisc_deref(ld);
855         }
856         /*
857          * FIXME: Once we trust the LDISC code better we can wait here for
858          * ldisc completion and fix the driver call race
859          */
860         wake_up_interruptible_poll(&tty->write_wait, POLLOUT);
861         wake_up_interruptible_poll(&tty->read_wait, POLLIN);
862         /*
863          * Shutdown the current line discipline, and reset it to
864          * N_TTY if need be.
865          *
866          * Avoid racing set_ldisc or tty_ldisc_release
867          */
868         mutex_lock(&tty->ldisc_mutex);
869
870         if (tty_ldisc_hangup_halt(tty)) {
871
872                 /* At this point we have a halted ldisc; we want to close it and
873                    reopen a new ldisc. We could defer the reopen to the next
874                    open but it means auditing a lot of other paths so this is
875                    a FIXME */
876                 if (reset == 0) {
877
878                         if (!tty_ldisc_reinit(tty, tty->termios.c_line))
879                                 err = tty_ldisc_open(tty, tty->ldisc);
880                         else
881                                 err = 1;
882                 }
883                 /* If the re-open fails or we reset then go to N_TTY. The
884                    N_TTY open cannot fail */
885                 if (reset || err) {
886                         BUG_ON(tty_ldisc_reinit(tty, N_TTY));
887                         WARN_ON(tty_ldisc_open(tty, tty->ldisc));
888                 }
889                 tty_ldisc_enable(tty);
890         }
891         mutex_unlock(&tty->ldisc_mutex);
892         if (reset)
893                 tty_reset_termios(tty);
894
895         tty_ldisc_debug(tty, "re-opened ldisc: %p\n", tty->ldisc);
896 }
897
898 /**
899  *      tty_ldisc_setup                 -       open line discipline
900  *      @tty: tty being shut down
901  *      @o_tty: pair tty for pty/tty pairs
902  *
903  *      Called during the initial open of a tty/pty pair in order to set up the
904  *      line disciplines and bind them to the tty. This has no locking issues
905  *      as the device isn't yet active.
906  */
907
908 int tty_ldisc_setup(struct tty_struct *tty, struct tty_struct *o_tty)
909 {
910         struct tty_ldisc *ld = tty->ldisc;
911         int retval;
912
913         retval = tty_ldisc_open(tty, ld);
914         if (retval)
915                 return retval;
916
917         if (o_tty) {
918                 retval = tty_ldisc_open(o_tty, o_tty->ldisc);
919                 if (retval) {
920                         tty_ldisc_close(tty, ld);
921                         return retval;
922                 }
923                 tty_ldisc_enable(o_tty);
924         }
925         tty_ldisc_enable(tty);
926         return 0;
927 }
928
929 static void tty_ldisc_kill(struct tty_struct *tty)
930 {
931         mutex_lock(&tty->ldisc_mutex);
932         /*
933          * Now kill off the ldisc
934          */
935         tty_ldisc_close(tty, tty->ldisc);
936         tty_ldisc_put(tty->ldisc);
937         /* Force an oops if we mess this up */
938         tty->ldisc = NULL;
939
940         /* Ensure the next open requests the N_TTY ldisc */
941         tty_set_termios_ldisc(tty, N_TTY);
942         mutex_unlock(&tty->ldisc_mutex);
943 }
944
945 /**
946  *      tty_ldisc_release               -       release line discipline
947  *      @tty: tty being shut down
948  *      @o_tty: pair tty for pty/tty pairs
949  *
950  *      Called during the final close of a tty/pty pair in order to shut down
951  *      the line discpline layer. On exit the ldisc assigned is N_TTY and the
952  *      ldisc has not been opened.
953  */
954
955 void tty_ldisc_release(struct tty_struct *tty, struct tty_struct *o_tty)
956 {
957         /*
958          * Shutdown this line discipline. As this is the final close,
959          * it does not race with the set_ldisc code path.
960          */
961
962         tty_ldisc_debug(tty, "closing ldisc: %p\n", tty->ldisc);
963
964         tty_ldisc_halt(tty, o_tty, MAX_SCHEDULE_TIMEOUT);
965
966         tty_lock_pair(tty, o_tty);
967         /* This will need doing differently if we need to lock */
968         tty_ldisc_kill(tty);
969         if (o_tty)
970                 tty_ldisc_kill(o_tty);
971
972         tty_unlock_pair(tty, o_tty);
973         /* And the memory resources remaining (buffers, termios) will be
974            disposed of when the kref hits zero */
975
976         tty_ldisc_debug(tty, "ldisc closed\n");
977 }
978
979 /**
980  *      tty_ldisc_init          -       ldisc setup for new tty
981  *      @tty: tty being allocated
982  *
983  *      Set up the line discipline objects for a newly allocated tty. Note that
984  *      the tty structure is not completely set up when this call is made.
985  */
986
987 void tty_ldisc_init(struct tty_struct *tty)
988 {
989         struct tty_ldisc *ld = tty_ldisc_get(N_TTY);
990         if (IS_ERR(ld))
991                 panic("n_tty: init_tty");
992         tty_ldisc_assign(tty, ld);
993 }
994
995 /**
996  *      tty_ldisc_init          -       ldisc cleanup for new tty
997  *      @tty: tty that was allocated recently
998  *
999  *      The tty structure must not becompletely set up (tty_ldisc_setup) when
1000  *      this call is made.
1001  */
1002 void tty_ldisc_deinit(struct tty_struct *tty)
1003 {
1004         put_ldisc(tty->ldisc);
1005         tty_ldisc_assign(tty, NULL);
1006 }
1007
1008 void tty_ldisc_begin(void)
1009 {
1010         /* Setup the default TTY line discipline. */
1011         (void) tty_register_ldisc(N_TTY, &tty_ldisc_N_TTY);
1012 }