USB: mos7840: Clean up old checks and stuff
[pandora-kernel.git] / drivers / char / hvc_console.c
1 /*
2  * Copyright (C) 2001 Anton Blanchard <anton@au.ibm.com>, IBM
3  * Copyright (C) 2001 Paul Mackerras <paulus@au.ibm.com>, IBM
4  * Copyright (C) 2004 Benjamin Herrenschmidt <benh@kernel.crashing.org>, IBM Corp.
5  * Copyright (C) 2004 IBM Corporation
6  *
7  * Additional Author(s):
8  *  Ryan S. Arnold <rsa@us.ibm.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  * 
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  * 
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
23  */
24
25 #include <linux/console.h>
26 #include <linux/cpumask.h>
27 #include <linux/init.h>
28 #include <linux/kbd_kern.h>
29 #include <linux/kernel.h>
30 #include <linux/kobject.h>
31 #include <linux/kthread.h>
32 #include <linux/list.h>
33 #include <linux/module.h>
34 #include <linux/major.h>
35 #include <linux/sysrq.h>
36 #include <linux/tty.h>
37 #include <linux/tty_flip.h>
38 #include <linux/sched.h>
39 #include <linux/spinlock.h>
40 #include <linux/delay.h>
41 #include <linux/freezer.h>
42
43 #include <asm/uaccess.h>
44
45 #include "hvc_console.h"
46
47 #define HVC_MAJOR       229
48 #define HVC_MINOR       0
49
50 /*
51  * Wait this long per iteration while trying to push buffered data to the
52  * hypervisor before allowing the tty to complete a close operation.
53  */
54 #define HVC_CLOSE_WAIT (HZ/100) /* 1/10 of a second */
55
56 /*
57  * These sizes are most efficient for vio, because they are the
58  * native transfer size. We could make them selectable in the
59  * future to better deal with backends that want other buffer sizes.
60  */
61 #define N_OUTBUF        16
62 #define N_INBUF         16
63
64 #define __ALIGNED__ __attribute__((__aligned__(sizeof(long))))
65
66 static struct tty_driver *hvc_driver;
67 static struct task_struct *hvc_task;
68
69 /* Picks up late kicks after list walk but before schedule() */
70 static int hvc_kicked;
71
72 static int hvc_init(void);
73
74 #ifdef CONFIG_MAGIC_SYSRQ
75 static int sysrq_pressed;
76 #endif
77
78 struct hvc_struct {
79         spinlock_t lock;
80         int index;
81         struct tty_struct *tty;
82         unsigned int count;
83         int do_wakeup;
84         char *outbuf;
85         int outbuf_size;
86         int n_outbuf;
87         uint32_t vtermno;
88         struct hv_ops *ops;
89         int irq_requested;
90         int irq;
91         struct list_head next;
92         struct kobject kobj; /* ref count & hvc_struct lifetime */
93 };
94
95 /* dynamic list of hvc_struct instances */
96 static struct list_head hvc_structs = LIST_HEAD_INIT(hvc_structs);
97
98 /*
99  * Protect the list of hvc_struct instances from inserts and removals during
100  * list traversal.
101  */
102 static DEFINE_SPINLOCK(hvc_structs_lock);
103
104 /*
105  * This value is used to assign a tty->index value to a hvc_struct based
106  * upon order of exposure via hvc_probe(), when we can not match it to
107  * a console candidate registered with hvc_instantiate().
108  */
109 static int last_hvc = -1;
110
111 /*
112  * Do not call this function with either the hvc_structs_lock or the hvc_struct
113  * lock held.  If successful, this function increments the kobject reference
114  * count against the target hvc_struct so it should be released when finished.
115  */
116 static struct hvc_struct *hvc_get_by_index(int index)
117 {
118         struct hvc_struct *hp;
119         unsigned long flags;
120
121         spin_lock(&hvc_structs_lock);
122
123         list_for_each_entry(hp, &hvc_structs, next) {
124                 spin_lock_irqsave(&hp->lock, flags);
125                 if (hp->index == index) {
126                         kobject_get(&hp->kobj);
127                         spin_unlock_irqrestore(&hp->lock, flags);
128                         spin_unlock(&hvc_structs_lock);
129                         return hp;
130                 }
131                 spin_unlock_irqrestore(&hp->lock, flags);
132         }
133         hp = NULL;
134
135         spin_unlock(&hvc_structs_lock);
136         return hp;
137 }
138
139
140 /*
141  * Initial console vtermnos for console API usage prior to full console
142  * initialization.  Any vty adapter outside this range will not have usable
143  * console interfaces but can still be used as a tty device.  This has to be
144  * static because kmalloc will not work during early console init.
145  */
146 static struct hv_ops *cons_ops[MAX_NR_HVC_CONSOLES];
147 static uint32_t vtermnos[MAX_NR_HVC_CONSOLES] =
148         {[0 ... MAX_NR_HVC_CONSOLES - 1] = -1};
149
150 /*
151  * Console APIs, NOT TTY.  These APIs are available immediately when
152  * hvc_console_setup() finds adapters.
153  */
154
155 static void hvc_console_print(struct console *co, const char *b,
156                               unsigned count)
157 {
158         char c[N_OUTBUF] __ALIGNED__;
159         unsigned i = 0, n = 0;
160         int r, donecr = 0, index = co->index;
161
162         /* Console access attempt outside of acceptable console range. */
163         if (index >= MAX_NR_HVC_CONSOLES)
164                 return;
165
166         /* This console adapter was removed so it is not usable. */
167         if (vtermnos[index] < 0)
168                 return;
169
170         while (count > 0 || i > 0) {
171                 if (count > 0 && i < sizeof(c)) {
172                         if (b[n] == '\n' && !donecr) {
173                                 c[i++] = '\r';
174                                 donecr = 1;
175                         } else {
176                                 c[i++] = b[n++];
177                                 donecr = 0;
178                                 --count;
179                         }
180                 } else {
181                         r = cons_ops[index]->put_chars(vtermnos[index], c, i);
182                         if (r < 0) {
183                                 /* throw away chars on error */
184                                 i = 0;
185                         } else if (r > 0) {
186                                 i -= r;
187                                 if (i > 0)
188                                         memmove(c, c+r, i);
189                         }
190                 }
191         }
192 }
193
194 static struct tty_driver *hvc_console_device(struct console *c, int *index)
195 {
196         if (vtermnos[c->index] == -1)
197                 return NULL;
198
199         *index = c->index;
200         return hvc_driver;
201 }
202
203 static int __init hvc_console_setup(struct console *co, char *options)
204 {
205         if (co->index < 0 || co->index >= MAX_NR_HVC_CONSOLES)
206                 return -ENODEV;
207
208         if (vtermnos[co->index] == -1)
209                 return -ENODEV;
210
211         return 0;
212 }
213
214 static struct console hvc_con_driver = {
215         .name           = "hvc",
216         .write          = hvc_console_print,
217         .device         = hvc_console_device,
218         .setup          = hvc_console_setup,
219         .flags          = CON_PRINTBUFFER,
220         .index          = -1,
221 };
222
223 /*
224  * Early console initialization.  Precedes driver initialization.
225  *
226  * (1) we are first, and the user specified another driver
227  * -- index will remain -1
228  * (2) we are first and the user specified no driver
229  * -- index will be set to 0, then we will fail setup.
230  * (3)  we are first and the user specified our driver
231  * -- index will be set to user specified driver, and we will fail
232  * (4) we are after driver, and this initcall will register us
233  * -- if the user didn't specify a driver then the console will match
234  *
235  * Note that for cases 2 and 3, we will match later when the io driver
236  * calls hvc_instantiate() and call register again.
237  */
238 static int __init hvc_console_init(void)
239 {
240         register_console(&hvc_con_driver);
241         return 0;
242 }
243 console_initcall(hvc_console_init);
244
245 /*
246  * hvc_instantiate() is an early console discovery method which locates
247  * consoles * prior to the vio subsystem discovering them.  Hotplugged
248  * vty adapters do NOT get an hvc_instantiate() callback since they
249  * appear after early console init.
250  */
251 int hvc_instantiate(uint32_t vtermno, int index, struct hv_ops *ops)
252 {
253         struct hvc_struct *hp;
254
255         if (index < 0 || index >= MAX_NR_HVC_CONSOLES)
256                 return -1;
257
258         if (vtermnos[index] != -1)
259                 return -1;
260
261         /* make sure no no tty has been registered in this index */
262         hp = hvc_get_by_index(index);
263         if (hp) {
264                 kobject_put(&hp->kobj);
265                 return -1;
266         }
267
268         vtermnos[index] = vtermno;
269         cons_ops[index] = ops;
270
271         /* reserve all indices up to and including this index */
272         if (last_hvc < index)
273                 last_hvc = index;
274
275         /* if this index is what the user requested, then register
276          * now (setup won't fail at this point).  It's ok to just
277          * call register again if previously .setup failed.
278          */
279         if (index == hvc_con_driver.index)
280                 register_console(&hvc_con_driver);
281
282         return 0;
283 }
284
285 /* Wake the sleeping khvcd */
286 static void hvc_kick(void)
287 {
288         hvc_kicked = 1;
289         wake_up_process(hvc_task);
290 }
291
292 static int hvc_poll(struct hvc_struct *hp);
293
294 /*
295  * NOTE: This API isn't used if the console adapter doesn't support interrupts.
296  * In this case the console is poll driven.
297  */
298 static irqreturn_t hvc_handle_interrupt(int irq, void *dev_instance)
299 {
300         /* if hvc_poll request a repoll, then kick the hvcd thread */
301         if (hvc_poll(dev_instance))
302                 hvc_kick();
303         return IRQ_HANDLED;
304 }
305
306 static void hvc_unthrottle(struct tty_struct *tty)
307 {
308         hvc_kick();
309 }
310
311 /*
312  * The TTY interface won't be used until after the vio layer has exposed the vty
313  * adapter to the kernel.
314  */
315 static int hvc_open(struct tty_struct *tty, struct file * filp)
316 {
317         struct hvc_struct *hp;
318         unsigned long flags;
319         int irq = 0;
320         int rc = 0;
321         struct kobject *kobjp;
322
323         /* Auto increments kobject reference if found. */
324         if (!(hp = hvc_get_by_index(tty->index)))
325                 return -ENODEV;
326
327         spin_lock_irqsave(&hp->lock, flags);
328         /* Check and then increment for fast path open. */
329         if (hp->count++ > 0) {
330                 spin_unlock_irqrestore(&hp->lock, flags);
331                 hvc_kick();
332                 return 0;
333         } /* else count == 0 */
334
335         tty->driver_data = hp;
336         tty->low_latency = 1; /* Makes flushes to ldisc synchronous. */
337
338         hp->tty = tty;
339         /* Save for request_irq outside of spin_lock. */
340         irq = hp->irq;
341         if (irq)
342                 hp->irq_requested = 1;
343
344         kobjp = &hp->kobj;
345
346         spin_unlock_irqrestore(&hp->lock, flags);
347         /* check error, fallback to non-irq */
348         if (irq)
349                 rc = request_irq(irq, hvc_handle_interrupt, IRQF_DISABLED, "hvc_console", hp);
350
351         /*
352          * If the request_irq() fails and we return an error.  The tty layer
353          * will call hvc_close() after a failed open but we don't want to clean
354          * up there so we'll clean up here and clear out the previously set
355          * tty fields and return the kobject reference.
356          */
357         if (rc) {
358                 spin_lock_irqsave(&hp->lock, flags);
359                 hp->tty = NULL;
360                 hp->irq_requested = 0;
361                 spin_unlock_irqrestore(&hp->lock, flags);
362                 tty->driver_data = NULL;
363                 kobject_put(kobjp);
364                 printk(KERN_ERR "hvc_open: request_irq failed with rc %d.\n", rc);
365         }
366         /* Force wakeup of the polling thread */
367         hvc_kick();
368
369         return rc;
370 }
371
372 static void hvc_close(struct tty_struct *tty, struct file * filp)
373 {
374         struct hvc_struct *hp;
375         struct kobject *kobjp;
376         int irq = 0;
377         unsigned long flags;
378
379         if (tty_hung_up_p(filp))
380                 return;
381
382         /*
383          * No driver_data means that this close was issued after a failed
384          * hvc_open by the tty layer's release_dev() function and we can just
385          * exit cleanly because the kobject reference wasn't made.
386          */
387         if (!tty->driver_data)
388                 return;
389
390         hp = tty->driver_data;
391         spin_lock_irqsave(&hp->lock, flags);
392
393         kobjp = &hp->kobj;
394         if (--hp->count == 0) {
395                 if (hp->irq_requested)
396                         irq = hp->irq;
397                 hp->irq_requested = 0;
398
399                 /* We are done with the tty pointer now. */
400                 hp->tty = NULL;
401                 spin_unlock_irqrestore(&hp->lock, flags);
402
403                 /*
404                  * Chain calls chars_in_buffer() and returns immediately if
405                  * there is no buffered data otherwise sleeps on a wait queue
406                  * waking periodically to check chars_in_buffer().
407                  */
408                 tty_wait_until_sent(tty, HVC_CLOSE_WAIT);
409
410                 if (irq)
411                         free_irq(irq, hp);
412
413         } else {
414                 if (hp->count < 0)
415                         printk(KERN_ERR "hvc_close %X: oops, count is %d\n",
416                                 hp->vtermno, hp->count);
417                 spin_unlock_irqrestore(&hp->lock, flags);
418         }
419
420         kobject_put(kobjp);
421 }
422
423 static void hvc_hangup(struct tty_struct *tty)
424 {
425         struct hvc_struct *hp = tty->driver_data;
426         unsigned long flags;
427         int irq = 0;
428         int temp_open_count;
429         struct kobject *kobjp;
430
431         if (!hp)
432                 return;
433
434         spin_lock_irqsave(&hp->lock, flags);
435
436         /*
437          * The N_TTY line discipline has problems such that in a close vs
438          * open->hangup case this can be called after the final close so prevent
439          * that from happening for now.
440          */
441         if (hp->count <= 0) {
442                 spin_unlock_irqrestore(&hp->lock, flags);
443                 return;
444         }
445
446         kobjp = &hp->kobj;
447         temp_open_count = hp->count;
448         hp->count = 0;
449         hp->n_outbuf = 0;
450         hp->tty = NULL;
451         if (hp->irq_requested)
452                 /* Saved for use outside of spin_lock. */
453                 irq = hp->irq;
454         hp->irq_requested = 0;
455         spin_unlock_irqrestore(&hp->lock, flags);
456         if (irq)
457                 free_irq(irq, hp);
458         while(temp_open_count) {
459                 --temp_open_count;
460                 kobject_put(kobjp);
461         }
462 }
463
464 /*
465  * Push buffered characters whether they were just recently buffered or waiting
466  * on a blocked hypervisor.  Call this function with hp->lock held.
467  */
468 static void hvc_push(struct hvc_struct *hp)
469 {
470         int n;
471
472         n = hp->ops->put_chars(hp->vtermno, hp->outbuf, hp->n_outbuf);
473         if (n <= 0) {
474                 if (n == 0) {
475                         hp->do_wakeup = 1;
476                         return;
477                 }
478                 /* throw away output on error; this happens when
479                    there is no session connected to the vterm. */
480                 hp->n_outbuf = 0;
481         } else
482                 hp->n_outbuf -= n;
483         if (hp->n_outbuf > 0)
484                 memmove(hp->outbuf, hp->outbuf + n, hp->n_outbuf);
485         else
486                 hp->do_wakeup = 1;
487 }
488
489 static int hvc_write(struct tty_struct *tty, const unsigned char *buf, int count)
490 {
491         struct hvc_struct *hp = tty->driver_data;
492         unsigned long flags;
493         int rsize, written = 0;
494
495         /* This write was probably executed during a tty close. */
496         if (!hp)
497                 return -EPIPE;
498
499         if (hp->count <= 0)
500                 return -EIO;
501
502         spin_lock_irqsave(&hp->lock, flags);
503
504         /* Push pending writes */
505         if (hp->n_outbuf > 0)
506                 hvc_push(hp);
507
508         while (count > 0 && (rsize = hp->outbuf_size - hp->n_outbuf) > 0) {
509                 if (rsize > count)
510                         rsize = count;
511                 memcpy(hp->outbuf + hp->n_outbuf, buf, rsize);
512                 count -= rsize;
513                 buf += rsize;
514                 hp->n_outbuf += rsize;
515                 written += rsize;
516                 hvc_push(hp);
517         }
518         spin_unlock_irqrestore(&hp->lock, flags);
519
520         /*
521          * Racy, but harmless, kick thread if there is still pending data.
522          */
523         if (hp->n_outbuf)
524                 hvc_kick();
525
526         return written;
527 }
528
529 /*
530  * This is actually a contract between the driver and the tty layer outlining
531  * how much write room the driver can guarantee will be sent OR BUFFERED.  This
532  * driver MUST honor the return value.
533  */
534 static int hvc_write_room(struct tty_struct *tty)
535 {
536         struct hvc_struct *hp = tty->driver_data;
537
538         if (!hp)
539                 return -1;
540
541         return hp->outbuf_size - hp->n_outbuf;
542 }
543
544 static int hvc_chars_in_buffer(struct tty_struct *tty)
545 {
546         struct hvc_struct *hp = tty->driver_data;
547
548         if (!hp)
549                 return -1;
550         return hp->n_outbuf;
551 }
552
553 /*
554  * timeout will vary between the MIN and MAX values defined here.  By default
555  * and during console activity we will use a default MIN_TIMEOUT of 10.  When
556  * the console is idle, we increase the timeout value on each pass through
557  * msleep until we reach the max.  This may be noticeable as a brief (average
558  * one second) delay on the console before the console responds to input when
559  * there has been no input for some time.
560  */
561 #define MIN_TIMEOUT             (10)
562 #define MAX_TIMEOUT             (2000)
563 static u32 timeout = MIN_TIMEOUT;
564
565 #define HVC_POLL_READ   0x00000001
566 #define HVC_POLL_WRITE  0x00000002
567
568 static int hvc_poll(struct hvc_struct *hp)
569 {
570         struct tty_struct *tty;
571         int i, n, poll_mask = 0;
572         char buf[N_INBUF] __ALIGNED__;
573         unsigned long flags;
574         int read_total = 0;
575
576         spin_lock_irqsave(&hp->lock, flags);
577
578         /* Push pending writes */
579         if (hp->n_outbuf > 0)
580                 hvc_push(hp);
581
582         /* Reschedule us if still some write pending */
583         if (hp->n_outbuf > 0)
584                 poll_mask |= HVC_POLL_WRITE;
585
586         /* No tty attached, just skip */
587         tty = hp->tty;
588         if (tty == NULL)
589                 goto bail;
590
591         /* Now check if we can get data (are we throttled ?) */
592         if (test_bit(TTY_THROTTLED, &tty->flags))
593                 goto throttled;
594
595         /* If we aren't interrupt driven and aren't throttled, we always
596          * request a reschedule
597          */
598         if (hp->irq == 0)
599                 poll_mask |= HVC_POLL_READ;
600
601         /* Read data if any */
602         for (;;) {
603                 int count = tty_buffer_request_room(tty, N_INBUF);
604
605                 /* If flip is full, just reschedule a later read */
606                 if (count == 0) {
607                         poll_mask |= HVC_POLL_READ;
608                         break;
609                 }
610
611                 n = hp->ops->get_chars(hp->vtermno, buf, count);
612                 if (n <= 0) {
613                         /* Hangup the tty when disconnected from host */
614                         if (n == -EPIPE) {
615                                 spin_unlock_irqrestore(&hp->lock, flags);
616                                 tty_hangup(tty);
617                                 spin_lock_irqsave(&hp->lock, flags);
618                         } else if ( n == -EAGAIN ) {
619                                 /*
620                                  * Some back-ends can only ensure a certain min
621                                  * num of bytes read, which may be > 'count'.
622                                  * Let the tty clear the flip buff to make room.
623                                  */
624                                 poll_mask |= HVC_POLL_READ;
625                         }
626                         break;
627                 }
628                 for (i = 0; i < n; ++i) {
629 #ifdef CONFIG_MAGIC_SYSRQ
630                         if (hp->index == hvc_con_driver.index) {
631                                 /* Handle the SysRq Hack */
632                                 /* XXX should support a sequence */
633                                 if (buf[i] == '\x0f') { /* ^O */
634                                         sysrq_pressed = 1;
635                                         continue;
636                                 } else if (sysrq_pressed) {
637                                         handle_sysrq(buf[i], tty);
638                                         sysrq_pressed = 0;
639                                         continue;
640                                 }
641                         }
642 #endif /* CONFIG_MAGIC_SYSRQ */
643                         tty_insert_flip_char(tty, buf[i], 0);
644                 }
645
646                 read_total += n;
647         }
648  throttled:
649         /* Wakeup write queue if necessary */
650         if (hp->do_wakeup) {
651                 hp->do_wakeup = 0;
652                 tty_wakeup(tty);
653         }
654  bail:
655         spin_unlock_irqrestore(&hp->lock, flags);
656
657         if (read_total) {
658                 /* Activity is occurring, so reset the polling backoff value to
659                    a minimum for performance. */
660                 timeout = MIN_TIMEOUT;
661
662                 tty_flip_buffer_push(tty);
663         }
664
665         return poll_mask;
666 }
667
668 #if defined(CONFIG_XMON) && defined(CONFIG_SMP)
669 extern cpumask_t cpus_in_xmon;
670 #else
671 static const cpumask_t cpus_in_xmon = CPU_MASK_NONE;
672 #endif
673
674 /*
675  * This kthread is either polling or interrupt driven.  This is determined by
676  * calling hvc_poll() who determines whether a console adapter support
677  * interrupts.
678  */
679 static int khvcd(void *unused)
680 {
681         int poll_mask;
682         struct hvc_struct *hp;
683
684         set_freezable();
685         __set_current_state(TASK_RUNNING);
686         do {
687                 poll_mask = 0;
688                 hvc_kicked = 0;
689                 try_to_freeze();
690                 wmb();
691                 if (cpus_empty(cpus_in_xmon)) {
692                         spin_lock(&hvc_structs_lock);
693                         list_for_each_entry(hp, &hvc_structs, next) {
694                                 poll_mask |= hvc_poll(hp);
695                         }
696                         spin_unlock(&hvc_structs_lock);
697                 } else
698                         poll_mask |= HVC_POLL_READ;
699                 if (hvc_kicked)
700                         continue;
701                 if (poll_mask & HVC_POLL_WRITE) {
702                         yield();
703                         continue;
704                 }
705                 set_current_state(TASK_INTERRUPTIBLE);
706                 if (!hvc_kicked) {
707                         if (poll_mask == 0)
708                                 schedule();
709                         else {
710                                 if (timeout < MAX_TIMEOUT)
711                                         timeout += (timeout >> 6) + 1;
712
713                                 msleep_interruptible(timeout);
714                         }
715                 }
716                 __set_current_state(TASK_RUNNING);
717         } while (!kthread_should_stop());
718
719         return 0;
720 }
721
722 static const struct tty_operations hvc_ops = {
723         .open = hvc_open,
724         .close = hvc_close,
725         .write = hvc_write,
726         .hangup = hvc_hangup,
727         .unthrottle = hvc_unthrottle,
728         .write_room = hvc_write_room,
729         .chars_in_buffer = hvc_chars_in_buffer,
730 };
731
732 /* callback when the kboject ref count reaches zero. */
733 static void destroy_hvc_struct(struct kobject *kobj)
734 {
735         struct hvc_struct *hp = container_of(kobj, struct hvc_struct, kobj);
736         unsigned long flags;
737
738         spin_lock(&hvc_structs_lock);
739
740         spin_lock_irqsave(&hp->lock, flags);
741         list_del(&(hp->next));
742         spin_unlock_irqrestore(&hp->lock, flags);
743
744         spin_unlock(&hvc_structs_lock);
745
746         kfree(hp);
747 }
748
749 static struct kobj_type hvc_kobj_type = {
750         .release = destroy_hvc_struct,
751 };
752
753 struct hvc_struct __devinit *hvc_alloc(uint32_t vtermno, int irq,
754                                         struct hv_ops *ops, int outbuf_size)
755 {
756         struct hvc_struct *hp;
757         int i;
758
759         /* We wait until a driver actually comes along */
760         if (!hvc_driver) {
761                 int err = hvc_init();
762                 if (err)
763                         return ERR_PTR(err);
764         }
765
766         hp = kmalloc(ALIGN(sizeof(*hp), sizeof(long)) + outbuf_size,
767                         GFP_KERNEL);
768         if (!hp)
769                 return ERR_PTR(-ENOMEM);
770
771         memset(hp, 0x00, sizeof(*hp));
772
773         hp->vtermno = vtermno;
774         hp->irq = irq;
775         hp->ops = ops;
776         hp->outbuf_size = outbuf_size;
777         hp->outbuf = &((char *)hp)[ALIGN(sizeof(*hp), sizeof(long))];
778
779         kobject_init(&hp->kobj);
780         hp->kobj.ktype = &hvc_kobj_type;
781
782         spin_lock_init(&hp->lock);
783         spin_lock(&hvc_structs_lock);
784
785         /*
786          * find index to use:
787          * see if this vterm id matches one registered for console.
788          */
789         for (i=0; i < MAX_NR_HVC_CONSOLES; i++)
790                 if (vtermnos[i] == hp->vtermno &&
791                     cons_ops[i] == hp->ops)
792                         break;
793
794         /* no matching slot, just use a counter */
795         if (i >= MAX_NR_HVC_CONSOLES)
796                 i = ++last_hvc;
797
798         hp->index = i;
799
800         list_add_tail(&(hp->next), &hvc_structs);
801         spin_unlock(&hvc_structs_lock);
802
803         return hp;
804 }
805
806 int __devexit hvc_remove(struct hvc_struct *hp)
807 {
808         unsigned long flags;
809         struct kobject *kobjp;
810         struct tty_struct *tty;
811
812         spin_lock_irqsave(&hp->lock, flags);
813         tty = hp->tty;
814         kobjp = &hp->kobj;
815
816         if (hp->index < MAX_NR_HVC_CONSOLES)
817                 vtermnos[hp->index] = -1;
818
819         /* Don't whack hp->irq because tty_hangup() will need to free the irq. */
820
821         spin_unlock_irqrestore(&hp->lock, flags);
822
823         /*
824          * We 'put' the instance that was grabbed when the kobject instance
825          * was initialized using kobject_init().  Let the last holder of this
826          * kobject cause it to be removed, which will probably be the tty_hangup
827          * below.
828          */
829         kobject_put(kobjp);
830
831         /*
832          * This function call will auto chain call hvc_hangup.  The tty should
833          * always be valid at this time unless a simultaneous tty close already
834          * cleaned up the hvc_struct.
835          */
836         if (tty)
837                 tty_hangup(tty);
838         return 0;
839 }
840
841 /* Driver initialization: called as soon as someone uses hvc_alloc(). */
842 static int hvc_init(void)
843 {
844         struct tty_driver *drv;
845         int err;
846
847         /* We need more than hvc_count adapters due to hotplug additions. */
848         drv = alloc_tty_driver(HVC_ALLOC_TTY_ADAPTERS);
849         if (!drv) {
850                 err = -ENOMEM;
851                 goto out;
852         }
853
854         drv->owner = THIS_MODULE;
855         drv->driver_name = "hvc";
856         drv->name = "hvc";
857         drv->major = HVC_MAJOR;
858         drv->minor_start = HVC_MINOR;
859         drv->type = TTY_DRIVER_TYPE_SYSTEM;
860         drv->init_termios = tty_std_termios;
861         drv->flags = TTY_DRIVER_REAL_RAW;
862         tty_set_operations(drv, &hvc_ops);
863
864         /* Always start the kthread because there can be hotplug vty adapters
865          * added later. */
866         hvc_task = kthread_run(khvcd, NULL, "khvcd");
867         if (IS_ERR(hvc_task)) {
868                 printk(KERN_ERR "Couldn't create kthread for console.\n");
869                 err = PTR_ERR(hvc_task);
870                 goto put_tty;
871         }
872
873         err = tty_register_driver(drv);
874         if (err) {
875                 printk(KERN_ERR "Couldn't register hvc console driver\n");
876                 goto stop_thread;
877         }
878
879         /* FIXME: This mb() seems completely random.  Remove it. */
880         mb();
881         hvc_driver = drv;
882         return 0;
883
884 put_tty:
885         put_tty_driver(hvc_driver);
886 stop_thread:
887         kthread_stop(hvc_task);
888         hvc_task = NULL;
889 out:
890         return err;
891 }
892
893 /* This isn't particularly necessary due to this being a console driver
894  * but it is nice to be thorough.
895  */
896 static void __exit hvc_exit(void)
897 {
898         if (hvc_driver) {
899                 kthread_stop(hvc_task);
900
901                 tty_unregister_driver(hvc_driver);
902                 /* return tty_struct instances allocated in hvc_init(). */
903                 put_tty_driver(hvc_driver);
904                 unregister_console(&hvc_con_driver);
905         }
906 }
907 module_exit(hvc_exit);