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