update to 2.6.9-rc1
[linux-flexiantxendom0-3.2.10.git] / drivers / char / hvcs.c
1 /*
2  * IBM eServer Hypervisor Virtual Console Server Device Driver
3  * Copyright (C) 2003, 2004 IBM Corp.
4  *  Ryan S. Arnold (rsa@us.ibm.com)
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19  *
20  * Author(s) :  Ryan S. Arnold <rsa@us.ibm.com>
21  *
22  * This is the device driver for the IBM Hypervisor Virtual Console Server,
23  * "hvcs".  The IBM hvcs provides a tty driver interface to allow Linux
24  * user space applications access to the system consoles of logically
25  * partitioned operating systems, e.g. Linux, running on the same partitioned
26  * Power5 ppc64 system.  Physical hardware consoles per partition are not
27  * practical on this hardware so system consoles are accessed by this driver
28  * using inter-partition firmware interfaces to virtual terminal devices.
29  *
30  * A vty is known to the HMC as a "virtual serial server adapter".  It is a
31  * virtual terminal device that is created by firmware upon partition creation
32  * to act as a partitioned OS's console device.
33  *
34  * Firmware dynamically (via hotplug) exposes vty-servers to a running ppc64
35  * Linux system upon their creation by the HMC or their exposure during boot.
36  * The non-user interactive backend of this driver is implemented as a vio
37  * device driver so that it can receive notification of vty-server lifetimes
38  * after it registers with the vio bus to handle vty-server probe and remove
39  * callbacks.
40  *
41  * Many vty-servers can be configured to connect to one vty, but a vty can
42  * only be actively connected to by a single vty-server, in any manner, at one
43  * time.  If the HMC is currently hosting the console for a target Linux
44  * partition; attempts to open the tty device to the partition's console using
45  * the hvcs on any partition will return -EBUSY with every open attempt until
46  * the HMC frees the connection between its vty-server and the desired
47  * partition's vty device.  Conversely, a vty-server may only be connected to
48  * a single vty at one time even though it may have several configured vty
49  * partner possibilities.
50  *
51  * Firmware does not provide notification of vty partner changes to this
52  * driver.  This means that an HMC Super Admin may add or remove partner vtys
53  * from a vty-server's partner list but the changes will not be signaled to
54  * the vty-server.  Firmware only notifies the driver when a vty-server is
55  * added or removed from the system.  To compensate for this deficiency, this
56  * driver implements a sysfs update attribute which provides a method for
57  * rescanning partner information upon a user's request.
58  *
59  * Each vty-server, prior to being exposed to this driver is reference counted
60  * using the 2.6 Linux kernel kobject construct.  This kobject is also used by
61  * the vio bus to provide a vio device sysfs entry that this driver attaches
62  * device specific attributes to, including partner information.  The vio bus
63  * framework also provides a sysfs entry for each vio driver.  The hvcs driver
64  * provides driver attributes in this entry.
65  *
66  * For direction on installation and usage of this driver please reference
67  * Documentation/powerpc/hvcs.txt.
68  */
69
70 #include <linux/device.h>
71 #include <linux/init.h>
72 #include <linux/interrupt.h>
73 #include <linux/kernel.h>
74 #include <linux/kobject.h>
75 #include <linux/kthread.h>
76 #include <linux/list.h>
77 #include <linux/major.h>
78 #include <linux/module.h>
79 #include <linux/moduleparam.h>
80 #include <linux/sched.h>
81 #include <linux/spinlock.h>
82 #include <linux/stat.h>
83 #include <linux/tty.h>
84 #include <linux/tty_flip.h>
85 #include <asm/hvconsole.h>
86 #include <asm/hvcserver.h>
87 #include <asm/uaccess.h>
88 #include <asm/vio.h>
89
90 /*
91  * 1.0.0 -> 1.1.0 Added kernel_thread scheduling methodology to driver to
92  * replace wait_task constructs.
93  *
94  * 1.1.0 -> 1.2.0 Moved pi_buff initialization out of arch code into driver code
95  * and added locking to share this buffer between hvcs_struct instances.  This
96  * is because the page_size kmalloc can't be done with a spin_lock held.
97  *
98  * Also added sysfs attribute to manually disconnect the vty-server from the vty
99  * due to stupid firmware behavior when opening the connection then sending data
100  * then then quickly closing the connection would cause data loss on the
101  * receiving side.  This required some reordering of the termination code.
102  *
103  * Fixed the hangup scenario and fixed memory leaks on module_exit.
104  *
105  * 1.2.0 -> 1.3.0 Moved from manual kernel thread creation & execution to
106  * kthread construct which replaced in-kernel IPC for thread termination with
107  * kthread_stop and kthread_should_stop.  Explicit wait_queue handling was
108  * removed because kthread handles this.  Minor bug fix to postpone partner_info
109  * clearing on hvcs_close until adapter removal to preserve context data for
110  * printk on partner connection free.  Added lock to protect hvcs_structs so
111  * that hvcs_struct instances aren't added or removed during list traversal.
112  * Cleaned up comment style, added spaces after commas, and broke function
113  * declaration lines to be under 80 columns.
114  *
115  * 1.3.0 -> 1.3.1 In hvcs_open memset(..,0x00,..) instead of memset(..,0x3F,00).
116  * Removed braces around single statements following conditionals.  Removed '=
117  * 0' after static int declarations since these default to zero.  Removed
118  * list_for_each_safe() and replaced with list_for_each_entry() in
119  * hvcs_get_by_index().  The 'safe' version is un-needed now that the driver is
120  * using spinlocks.  Changed spin_lock_irqsave() to spin_lock() when locking
121  * hvcs_structs_lock and hvcs_pi_lock since these are not touched in an int
122  * handler.  Initialized hvcs_structs_lock and hvcs_pi_lock to
123  * SPIN_LOCK_UNLOCKED at declaration time rather than in hvcs_module_init().
124  * Added spin_lock around list_del() in destroy_hvcs_struct() to protect the
125  * list traversals from a deletion.  Removed '= NULL' from pointer declaration
126  * statements since they are initialized NULL by default.  In hvcs_probe()
127  * changed kmalloc(sizeof(*hvcsd),...) to kmalloc(sizeof(struct
128  * hvcs_struct),...) because otherwise allocation would only be the size of a
129  * pointer.  Removed wmb() instances from hvcs_try_write().  They probably
130  * aren't needed with locking in place.  Added check and cleanup for
131  * hvcs_pi_buff = kmalloc() in hvcs_module_init().  Exposed hvcs_struct.index
132  * via a sysfs attribute so that the coupling between /dev/hvcs* and a
133  * vty-server can be automatically determined.  Moved kobject_put() in hvcs_open
134  * outside of the spin_unlock_irqrestore().
135  */
136 #define HVCS_DRIVER_VERSION "1.3.1"
137
138 MODULE_AUTHOR("Ryan S. Arnold <rsa@us.ibm.com>");
139 MODULE_DESCRIPTION("IBM hvcs (Hypervisor Virtual Console Server) Driver");
140 MODULE_LICENSE("GPL");
141 MODULE_VERSION(HVCS_DRIVER_VERSION);
142
143 /*
144  * Since the Linux TTY code does not currently (2-04-2004) support dynamic
145  * addition of tty derived devices and we shouldn't allocate thousands of
146  * tty_device pointers when the number of vty-server & vty partner connections
147  * will most often be much lower than this, we'll arbitrarily allocate
148  * HVCS_DEFAULT_SERVER_ADAPTERS tty_structs and cdev's by default when we
149  * register the tty_driver. This can be overridden using an insmod parameter.
150  */
151 #define HVCS_DEFAULT_SERVER_ADAPTERS    64
152
153 /*
154  * The user can't insmod with more than HVCS_MAX_SERVER_ADAPTERS hvcs device
155  * nodes as a sanity check.  Theoretically there can be over 1 Billion
156  * vty-server & vty partner connections.
157  */
158 #define HVCS_MAX_SERVER_ADAPTERS        1024
159
160 /*
161  * We let Linux assign us a major number and we start the minors at zero.  There
162  * is no intuitive mapping between minor number and the target partition.  The
163  * mapping of minor number is related to the order the vty-servers are exposed
164  * to this driver via the hvcs_probe function.
165  */
166 #define HVCS_MINOR_START        0
167
168 /*
169  * The hcall interface involves putting 8 chars into each of two registers.
170  * We load up those 2 registers (in arch/ppc64/hvconsole.c) by casting char[16]
171  * to long[2].  It would work without __ALIGNED__, but a little (tiny) bit
172  * slower because an unaligned load is slower than aligned load.
173  */
174 #define __ALIGNED__     __attribute__((__aligned__(8)))
175
176 /* Converged location code string length + 1 null terminator */
177 #define CLC_LENGTH              80
178
179 /*
180  * How much data can firmware send with each hvc_put_chars()?  Maybe this
181  * should be moved into an architecture specific area.
182  */
183 #define HVCS_BUFF_LEN   16
184
185 /*
186  * This is the maximum amount of data we'll let the user send us (hvcs_write) at
187  * once in a chunk as a sanity check.
188  */
189 #define HVCS_MAX_FROM_USER      4096
190
191 /*
192  * Be careful when adding flags to this line discipline.  Don't add anything
193  * that will cause echoing or we'll go into recursive loop echoing chars back
194  * and forth with the console drivers.
195  */
196 static struct termios hvcs_tty_termios = {
197         .c_iflag = IGNBRK | IGNPAR,
198         .c_oflag = OPOST,
199         .c_cflag = B38400 | CS8 | CREAD | HUPCL,
200         .c_cc = INIT_C_CC
201 };
202
203 /*
204  * This value is used to take the place of a command line parameter when the
205  * module is inserted.  It starts as -1 and stays as such if the user doesn't
206  * specify a module insmod parameter.  If they DO specify one then it is set to
207  * the value of the integer passed in.
208  */
209 static int hvcs_parm_num_devs = -1;
210 module_param(hvcs_parm_num_devs, int, 0);
211
212 char hvcs_driver_name[] = "hvcs";
213 char hvcs_device_node[] = "hvcs";
214 char hvcs_driver_string[]
215         = "IBM hvcs (Hypervisor Virtual Console Server) Driver";
216
217 /* Status of partner info rescan triggered via sysfs. */
218 static int hvcs_rescan_status;
219
220 static struct tty_driver *hvcs_tty_driver;
221
222 /*
223  * This is used to associate a vty-server, as it is exposed to this driver, with
224  * a preallocated tty_struct.index.  The dev node and hvcs index numbers are not
225  * re-used after device removal otherwise removing and adding a new one would
226  * link a /dev/hvcs* entry to a different vty-server than it did before the
227  * removal.  Incidentally, a newly exposed vty-server will always map to an
228  * incrementally higher /dev/hvcs* entry than the last exposed vty-server.
229  */
230 static int hvcs_struct_count = -1;
231
232 /*
233  * Used by the khvcsd to pick up I/O operations when the kernel_thread is
234  * already awake but potentially shifted to TASK_INTERRUPTIBLE state.
235  */
236 static int hvcs_kicked;
237
238 /* Used the the kthread construct for task operations */
239 static struct task_struct *hvcs_task;
240
241 /*
242  * We allocate this for the use of all of the hvcs_structs when they fetch
243  * partner info.
244  */
245 static unsigned long *hvcs_pi_buff;
246
247 static spinlock_t hvcs_pi_lock = SPIN_LOCK_UNLOCKED;
248
249 /* One vty-server per hvcs_struct */
250 struct hvcs_struct {
251         spinlock_t lock;
252
253         /*
254          * This index identifies this hvcs device as the complement to a
255          * specific tty index.
256          */
257         unsigned int index;
258
259         struct tty_struct *tty;
260         unsigned int open_count;
261
262         /*
263          * Used to tell the driver kernel_thread what operations need to take
264          * place upon this hvcs_struct instance.
265          */
266         int todo_mask;
267
268         /*
269          * This buffer is required so that when hvcs_write_room() reports that
270          * it can send HVCS_BUFF_LEN characters that it will buffer the full
271          * HVCS_BUFF_LEN characters if need be.  This is essential for opost
272          * writes since they do not do high level buffering and expect to be
273          * able to send what the driver commits to sending buffering
274          * [e.g. tab to space conversions in n_tty.c opost()].
275          */
276         char buffer[HVCS_BUFF_LEN];
277         int chars_in_buffer;
278
279         /*
280          * Any variable below the kobject is valid before a tty is connected and
281          * stays valid after the tty is disconnected.  These shouldn't be
282          * whacked until the koject refcount reaches zero though some entries
283          * may be changed via sysfs initiatives.
284          */
285         struct kobject kobj; /* ref count & hvcs_struct lifetime */
286         int connected; /* is the vty-server currently connected to a vty? */
287         uint32_t p_unit_address; /* partner unit address */
288         uint32_t p_partition_ID; /* partner partition ID */
289         char p_location_code[CLC_LENGTH];
290         struct list_head next; /* list management */
291         struct vio_dev *vdev;
292 };
293
294 /* Required to back map a kobject to its containing object */
295 #define from_kobj(kobj) container_of(kobj, struct hvcs_struct, kobj)
296
297 static struct list_head hvcs_structs = LIST_HEAD_INIT(hvcs_structs);
298 static spinlock_t hvcs_structs_lock = SPIN_LOCK_UNLOCKED;
299
300 static void hvcs_unthrottle(struct tty_struct *tty);
301 static void hvcs_throttle(struct tty_struct *tty);
302 static irqreturn_t hvcs_handle_interrupt(int irq, void *dev_instance,
303                 struct pt_regs *regs);
304
305 static int hvcs_write(struct tty_struct *tty, int from_user,
306                 const unsigned char *buf, int count);
307 static int hvcs_write_room(struct tty_struct *tty);
308 static int hvcs_chars_in_buffer(struct tty_struct *tty);
309
310 static int hvcs_has_pi(struct hvcs_struct *hvcsd);
311 static void hvcs_set_pi(struct hvcs_partner_info *pi,
312                 struct hvcs_struct *hvcsd);
313 static int hvcs_get_pi(struct hvcs_struct *hvcsd);
314 static int hvcs_rescan_devices_list(void);
315
316 static int hvcs_partner_connect(struct hvcs_struct *hvcsd);
317 static void hvcs_partner_free(struct hvcs_struct *hvcsd);
318
319 static int hvcs_enable_device(struct hvcs_struct *hvcsd,
320                 uint32_t unit_address, unsigned int irq, struct vio_dev *dev);
321 static void hvcs_final_close(struct hvcs_struct *hvcsd);
322
323 static void destroy_hvcs_struct(struct kobject *kobj);
324 static int hvcs_open(struct tty_struct *tty, struct file *filp);
325 static void hvcs_close(struct tty_struct *tty, struct file *filp);
326 static void hvcs_hangup(struct tty_struct * tty);
327
328 static void hvcs_create_device_attrs(struct hvcs_struct *hvcsd);
329 static void hvcs_remove_device_attrs(struct vio_dev *vdev);
330 static void hvcs_create_driver_attrs(void);
331 static void hvcs_remove_driver_attrs(void);
332
333 static int __devinit hvcs_probe(struct vio_dev *dev,
334                 const struct vio_device_id *id);
335 static int __devexit hvcs_remove(struct vio_dev *dev);
336 static int __init hvcs_module_init(void);
337 static void __exit hvcs_module_exit(void);
338
339 #define HVCS_SCHED_READ 0x00000001
340 #define HVCS_QUICK_READ 0x00000002
341 #define HVCS_TRY_WRITE  0x00000004
342 #define HVCS_READ_MASK  (HVCS_SCHED_READ | HVCS_QUICK_READ)
343
344 static void hvcs_kick(void)
345 {
346         hvcs_kicked = 1;
347         wmb();
348         wake_up_process(hvcs_task);
349 }
350
351 static void hvcs_unthrottle(struct tty_struct *tty)
352 {
353         struct hvcs_struct *hvcsd = tty->driver_data;
354         unsigned long flags;
355
356         spin_lock_irqsave(&hvcsd->lock, flags);
357         hvcsd->todo_mask |= HVCS_SCHED_READ;
358         spin_unlock_irqrestore(&hvcsd->lock, flags);
359         hvcs_kick();
360 }
361
362 static void hvcs_throttle(struct tty_struct *tty)
363 {
364         struct hvcs_struct *hvcsd = tty->driver_data;
365         unsigned long flags;
366
367         spin_lock_irqsave(&hvcsd->lock, flags);
368         vio_disable_interrupts(hvcsd->vdev);
369         spin_unlock_irqrestore(&hvcsd->lock, flags);
370 }
371
372 /*
373  * If the device is being removed we don't have to worry about this interrupt
374  * handler taking any further interrupts because they are disabled which means
375  * the hvcs_struct will always be valid in this handler.
376  */
377 static irqreturn_t hvcs_handle_interrupt(int irq, void *dev_instance,
378                 struct pt_regs *regs)
379 {
380         struct hvcs_struct *hvcsd = dev_instance;
381
382         spin_lock(&hvcsd->lock);
383         vio_disable_interrupts(hvcsd->vdev);
384         hvcsd->todo_mask |= HVCS_SCHED_READ;
385         spin_unlock(&hvcsd->lock);
386         hvcs_kick();
387
388         return IRQ_HANDLED;
389 }
390
391 /* This function must be called with the hvcsd->lock held */
392 static void hvcs_try_write(struct hvcs_struct *hvcsd)
393 {
394         uint32_t unit_address = hvcsd->vdev->unit_address;
395         struct tty_struct *tty = hvcsd->tty;
396         int sent;
397
398         if (hvcsd->todo_mask & HVCS_TRY_WRITE) {
399                 /* won't send partial writes */
400                 sent = hvc_put_chars(unit_address,
401                                 &hvcsd->buffer[0],
402                                 hvcsd->chars_in_buffer );
403                 if (sent > 0) {
404                         hvcsd->chars_in_buffer = 0;
405                         /* wmb(); */
406                         hvcsd->todo_mask &= ~(HVCS_TRY_WRITE);
407                         /* wmb(); */
408
409                         /*
410                          * We are still obligated to deliver the data to the
411                          * hypervisor even if the tty has been closed because
412                          * we commited to delivering it.  But don't try to wake
413                          * a non-existent tty.
414                          */
415                         if (tty) {
416                                 if ((tty->flags & (1 << TTY_DO_WRITE_WAKEUP))
417                                                 && tty->ldisc.write_wakeup)
418                                         (tty->ldisc.write_wakeup) (tty);
419                                 wake_up_interruptible(&tty->write_wait);
420                         }
421                 }
422         }
423 }
424
425 static int hvcs_io(struct hvcs_struct *hvcsd)
426 {
427         uint32_t unit_address;
428         struct tty_struct *tty;
429         char buf[HVCS_BUFF_LEN] __ALIGNED__;
430         unsigned long flags;
431         int got;
432         int i;
433
434         spin_lock_irqsave(&hvcsd->lock, flags);
435
436         unit_address = hvcsd->vdev->unit_address;
437         tty = hvcsd->tty;
438
439         hvcs_try_write(hvcsd);
440
441         if (!tty || test_bit(TTY_THROTTLED, &tty->flags)) {
442                 hvcsd->todo_mask &= ~(HVCS_READ_MASK);
443                 goto bail;
444         } else if (!(hvcsd->todo_mask & (HVCS_READ_MASK)))
445                 goto bail;
446
447         /* remove the read masks */
448         hvcsd->todo_mask &= ~(HVCS_READ_MASK);
449
450         if ((tty->flip.count + HVCS_BUFF_LEN) < TTY_FLIPBUF_SIZE) {
451                 got = hvc_get_chars(unit_address,
452                                 &buf[0],
453                                 HVCS_BUFF_LEN);
454                 for (i=0;got && i<got;i++)
455                         tty_insert_flip_char(tty, buf[i], TTY_NORMAL);
456         }
457
458         /* Give the TTY time to process the data we just sent. */
459         if (got)
460                 hvcsd->todo_mask |= HVCS_QUICK_READ;
461
462         spin_unlock_irqrestore(&hvcsd->lock, flags);
463         if (tty->flip.count) {
464                 /* This is synch because tty->low_latency == 1 */
465                 tty_flip_buffer_push(tty);
466         }
467
468         if (!got) {
469                 /* Do this _after_ the flip_buffer_push */
470                 spin_lock_irqsave(&hvcsd->lock, flags);
471                 vio_enable_interrupts(hvcsd->vdev);
472                 spin_unlock_irqrestore(&hvcsd->lock, flags);
473         }
474
475         return hvcsd->todo_mask;
476
477  bail:
478         spin_unlock_irqrestore(&hvcsd->lock, flags);
479         return hvcsd->todo_mask;
480 }
481
482 static int khvcsd(void *unused)
483 {
484         struct hvcs_struct *hvcsd;
485         int hvcs_todo_mask;
486
487         __set_current_state(TASK_RUNNING);
488
489         do {
490                 hvcs_todo_mask = 0;
491                 hvcs_kicked = 0;
492                 wmb();
493
494                 spin_lock(&hvcs_structs_lock);
495                 list_for_each_entry(hvcsd, &hvcs_structs, next) {
496                         hvcs_todo_mask |= hvcs_io(hvcsd);
497                 }
498                 spin_unlock(&hvcs_structs_lock);
499
500                 /*
501                  * If any of the hvcs adapters want to try a write or quick read
502                  * don't schedule(), yield a smidgen then execute the hvcs_io
503                  * thread again for those that want the write.
504                  */
505                  if (hvcs_todo_mask & (HVCS_TRY_WRITE | HVCS_QUICK_READ)) {
506                         yield();
507                         continue;
508                 }
509
510                 set_current_state(TASK_INTERRUPTIBLE);
511                 if (!hvcs_kicked)
512                         schedule();
513                 __set_current_state(TASK_RUNNING);
514         } while (!kthread_should_stop());
515
516         return 0;
517 }
518
519 static struct vio_device_id hvcs_driver_table[] __devinitdata= {
520         {"serial-server", "hvterm2"},
521         { 0, }
522 };
523 MODULE_DEVICE_TABLE(vio, hvcs_driver_table);
524
525 /* callback when the kboject ref count reaches zero */
526 static void destroy_hvcs_struct(struct kobject *kobj)
527 {
528         struct hvcs_struct *hvcsd = from_kobj(kobj);
529         struct vio_dev *vdev;
530         unsigned long flags;
531
532         spin_lock(&hvcs_structs_lock);
533         spin_lock_irqsave(&hvcsd->lock, flags);
534
535         /* the list_del poisons the pointers */
536         list_del(&(hvcsd->next));
537
538         if (hvcsd->connected == 1) {
539                 hvcs_partner_free(hvcsd);
540                 printk(KERN_INFO "HVCS: Closed vty-server@%X and"
541                                 " partner vty@%X:%d connection.\n",
542                                 hvcsd->vdev->unit_address,
543                                 hvcsd->p_unit_address,
544                                 (uint32_t)hvcsd->p_partition_ID);
545         }
546         printk(KERN_INFO "HVCS: Destroyed hvcs_struct for vty-server@%X.\n",
547                         hvcsd->vdev->unit_address);
548
549         vdev = hvcsd->vdev;
550         hvcsd->vdev = NULL;
551
552         hvcsd->p_unit_address = 0;
553         hvcsd->p_partition_ID = 0;
554         memset(&hvcsd->p_location_code[0], 0x00, CLC_LENGTH);
555
556         spin_unlock_irqrestore(&hvcsd->lock, flags);
557         spin_unlock(&hvcs_structs_lock);
558
559         hvcs_remove_device_attrs(vdev);
560
561         kfree(hvcsd);
562 }
563
564 /* This function must be called with hvcsd->lock held. */
565 static void hvcs_final_close(struct hvcs_struct *hvcsd)
566 {
567         vio_disable_interrupts(hvcsd->vdev);
568         free_irq(hvcsd->vdev->irq, hvcsd);
569
570         hvcsd->todo_mask = 0;
571
572         /* These two may be redundant if the operation was a close. */
573         if (hvcsd->tty) {
574                 hvcsd->tty->driver_data = NULL;
575                 hvcsd->tty = NULL;
576         }
577
578         hvcsd->open_count = 0;
579
580         memset(&hvcsd->buffer[0], 0x00, HVCS_BUFF_LEN);
581         hvcsd->chars_in_buffer = 0;
582 }
583
584 static struct kobj_type hvcs_kobj_type = {
585         .release = destroy_hvcs_struct,
586 };
587
588 static int __devinit hvcs_probe(
589         struct vio_dev *dev,
590         const struct vio_device_id *id)
591 {
592         struct hvcs_struct *hvcsd;
593
594         if (!dev || !id) {
595                 printk(KERN_ERR "HVCS: probed with invalid parameter.\n");
596                 return -EPERM;
597         }
598
599         hvcsd = kmalloc(sizeof(struct hvcs_struct), GFP_KERNEL);
600         if (!hvcsd)
601                 return -ENODEV;
602
603         /* hvcsd->tty is zeroed out with the memset */
604         memset(hvcsd, 0x00, sizeof(*hvcsd));
605
606         hvcsd->lock = SPIN_LOCK_UNLOCKED;
607         /* Automatically incs the refcount the first time */
608         kobject_init(&hvcsd->kobj);
609         /* Set up the callback for terminating the hvcs_struct's life */
610         hvcsd->kobj.ktype = &hvcs_kobj_type;
611
612         hvcsd->vdev = dev;
613         dev->dev.driver_data = hvcsd;
614
615         hvcsd->index = ++hvcs_struct_count;
616         hvcsd->chars_in_buffer = 0;
617         hvcsd->todo_mask = 0;
618         hvcsd->connected = 0;
619
620         /*
621          * This will populate the hvcs_struct's partner info fields for the
622          * first time.
623          */
624         if (hvcs_get_pi(hvcsd)) {
625                 printk(KERN_ERR "HVCS: Failed to fetch partner"
626                         " info for vty-server@%X on device probe.\n",
627                         hvcsd->vdev->unit_address);
628         }
629
630         /*
631          * If a user app opens a tty that corresponds to this vty-server before
632          * the hvcs_struct has been added to the devices list then the user app
633          * will get -ENODEV.
634          */
635
636         spin_lock(&hvcs_structs_lock);
637
638         list_add_tail(&(hvcsd->next), &hvcs_structs);
639
640         spin_unlock(&hvcs_structs_lock);
641
642         hvcs_create_device_attrs(hvcsd);
643
644         printk(KERN_INFO "HVCS: Added vty-server@%X.\n", dev->unit_address);
645
646         /*
647          * DON'T enable interrupts here because there is no user to receive the
648          * data.
649          */
650         return 0;
651 }
652
653 static int __devexit hvcs_remove(struct vio_dev *dev)
654 {
655         struct hvcs_struct *hvcsd = dev->dev.driver_data;
656         unsigned long flags;
657         struct kobject *kobjp;
658         struct tty_struct *tty;
659
660         if (!hvcsd)
661                 return -ENODEV;
662
663         /* By this time the vty-server won't be getting any more interrups */
664
665         spin_lock_irqsave(&hvcsd->lock, flags);
666
667         tty = hvcsd->tty;
668
669         kobjp = &hvcsd->kobj;
670
671         spin_unlock_irqrestore(&hvcsd->lock, flags);
672
673         /*
674          * Let the last holder of this object cause it to be removed, which
675          * would probably be tty_hangup below.
676          */
677         kobject_put (kobjp);
678
679         /*
680          * The hangup is a scheduled function which will auto chain call
681          * hvcs_hangup.  The tty should always be valid at this time unless a
682          * simultaneous tty close already cleaned up the hvcs_struct.
683          */
684         if (tty)
685                 tty_hangup(tty);
686
687         printk(KERN_INFO "HVCS: vty-server@%X removed from the"
688                         " vio bus.\n", dev->unit_address);
689         return 0;
690 };
691
692 static struct vio_driver hvcs_vio_driver = {
693         .name           = hvcs_driver_name,
694         .id_table       = hvcs_driver_table,
695         .probe          = hvcs_probe,
696         .remove         = hvcs_remove,
697 };
698
699 /* Only called from hvcs_get_pi please */
700 static void hvcs_set_pi(struct hvcs_partner_info *pi, struct hvcs_struct *hvcsd)
701 {
702         int clclength;
703
704         hvcsd->p_unit_address = pi->unit_address;
705         hvcsd->p_partition_ID  = pi->partition_ID;
706         clclength = strlen(&pi->location_code[0]);
707         if (clclength > CLC_LENGTH - 1)
708                 clclength = CLC_LENGTH - 1;
709
710         /* copy the null-term char too */
711         strncpy(&hvcsd->p_location_code[0],
712                         &pi->location_code[0], clclength + 1);
713 }
714
715 /*
716  * Traverse the list and add the partner info that is found to the hvcs_struct
717  * struct entry. NOTE: At this time I know that partner info will return a
718  * single entry but in the future there may be multiple partner info entries per
719  * vty-server and you'll want to zero out that list and reset it.  If for some
720  * reason you have an old version of this driver but there IS more than one
721  * partner info then hvcsd->p_* will hold the last partner info data from the
722  * firmware query.  A good way to update this code would be to replace the three
723  * partner info fields in hvcs_struct with a list of hvcs_partner_info
724  * instances.
725  *
726  * This function must be called with the hvcsd->lock held.
727  */
728 static int hvcs_get_pi(struct hvcs_struct *hvcsd)
729 {
730         struct hvcs_partner_info *pi;
731         uint32_t unit_address = hvcsd->vdev->unit_address;
732         struct list_head head;
733         int retval;
734
735         spin_lock(&hvcs_pi_lock);
736         if (!hvcs_pi_buff) {
737                 spin_unlock(&hvcs_pi_lock);
738                 return -EFAULT;
739         }
740         retval = hvcs_get_partner_info(unit_address, &head, hvcs_pi_buff);
741         spin_unlock(&hvcs_pi_lock);
742         if (retval) {
743                 printk(KERN_ERR "HVCS: Failed to fetch partner"
744                         " info for vty-server@%x.\n", unit_address);
745                 return retval;
746         }
747
748         /* nixes the values if the partner vty went away */
749         hvcsd->p_unit_address = 0;
750         hvcsd->p_partition_ID = 0;
751
752         list_for_each_entry(pi, &head, node)
753                 hvcs_set_pi(pi, hvcsd);
754
755         hvcs_free_partner_info(&head);
756         return 0;
757 }
758
759 /*
760  * This function is executed by the driver "rescan" sysfs entry.  It shouldn't
761  * be executed elsewhere, in order to prevent deadlock issues.
762  */
763 static int hvcs_rescan_devices_list(void)
764 {
765         struct hvcs_struct *hvcsd;
766         unsigned long flags;
767
768         spin_lock(&hvcs_structs_lock);
769
770         list_for_each_entry(hvcsd, &hvcs_structs, next) {
771                 spin_lock_irqsave(&hvcsd->lock, flags);
772                 hvcs_get_pi(hvcsd);
773                 spin_unlock_irqrestore(&hvcsd->lock, flags);
774         }
775
776         spin_unlock(&hvcs_structs_lock);
777
778         return 0;
779 }
780
781 /*
782  * Farm this off into its own function because it could be more complex once
783  * multiple partners support is added. This function should be called with
784  * the hvcsd->lock held.
785  */
786 static int hvcs_has_pi(struct hvcs_struct *hvcsd)
787 {
788         if ((!hvcsd->p_unit_address) || (!hvcsd->p_partition_ID))
789                 return 0;
790         return 1;
791 }
792
793 /*
794  * NOTE: It is possible that the super admin removed a partner vty and then
795  * added a different vty as the new partner.
796  *
797  * This function must be called with the hvcsd->lock held.
798  */
799 static int hvcs_partner_connect(struct hvcs_struct *hvcsd)
800 {
801         int retval;
802         unsigned int unit_address = hvcsd->vdev->unit_address;
803
804         /*
805          * If there wasn't any pi when the device was added it doesn't meant
806          * there isn't any now.  This driver isn't notified when a new partner
807          * vty is added to a vty-server so we discover changes on our own.
808          * Please see comments in hvcs_register_connection() for justification
809          * of this bizarre code.
810          */
811         retval = hvcs_register_connection(unit_address,
812                         hvcsd->p_partition_ID,
813                         hvcsd->p_unit_address);
814         if (!retval) {
815                 hvcsd->connected = 1;
816                 return 0;
817         } else if (retval != -EINVAL)
818                 return retval;
819
820         /*
821          * As per the spec re-get the pi and try again if -EINVAL after the
822          * first connection attempt.
823          */
824         if (hvcs_get_pi(hvcsd))
825                 return -ENOMEM;
826
827         if (!hvcs_has_pi(hvcsd))
828                 return -ENODEV;
829
830         retval = hvcs_register_connection(unit_address,
831                         hvcsd->p_partition_ID,
832                         hvcsd->p_unit_address);
833         if (retval != -EINVAL) {
834                 hvcsd->connected = 1;
835                 return retval;
836         }
837
838         /*
839          * EBUSY is the most likely scenario though the vty could have been
840          * removed or there really could be an hcall error due to the parameter
841          * data but thanks to ambiguous firmware return codes we can't really
842          * tell.
843          */
844         printk(KERN_INFO "HVCS: vty-server or partner"
845                         " vty is busy.  Try again later.\n");
846         return -EBUSY;
847 }
848
849 /* This function must be called with the hvcsd->lock held */
850 static void hvcs_partner_free(struct hvcs_struct *hvcsd)
851 {
852         int retval;
853         do {
854                 retval = hvcs_free_connection(hvcsd->vdev->unit_address);
855         } while (retval == -EBUSY);
856         hvcsd->connected = 0;
857 }
858
859 /* This helper function must be called WITHOUT the hvcsd->lock held */
860 static int hvcs_enable_device(struct hvcs_struct *hvcsd, uint32_t unit_address,
861                 unsigned int irq, struct vio_dev *vdev)
862 {
863         unsigned long flags;
864         int rc;
865
866         /*
867          * It is possible that the vty-server was removed between the time that
868          * the conn was registered and now.
869          */
870         if (!(rc = request_irq(irq, &hvcs_handle_interrupt,
871                                 SA_INTERRUPT, "ibmhvcs", hvcsd))) {
872                 /*
873                  * It is possible the vty-server was removed after the irq was
874                  * requested but before we have time to enable interrupts.
875                  */
876                 if (vio_enable_interrupts(vdev) == H_Success)
877                         return 0;
878                 else {
879                         printk(KERN_ERR "HVCS: int enable failed for"
880                                         " vty-server@%X.\n", unit_address);
881                         free_irq(irq, hvcsd);
882                 }
883         } else
884                 printk(KERN_ERR "HVCS: irq req failed for"
885                                 " vty-server@%X.\n", unit_address);
886
887         spin_lock_irqsave(&hvcsd->lock, flags);
888         hvcs_partner_free(hvcsd);
889         spin_unlock_irqrestore(&hvcsd->lock, flags);
890
891         return rc;
892
893 }
894
895 /*
896  * This always increments the kobject ref count if the call is successful.
897  * Please remember to dec when you are done with the instance.
898  *
899  * NOTICE: Do NOT hold either the hvcs_struct.lock or hvcs_structs_lock when
900  * calling this function or you will get deadlock.
901  */
902 struct hvcs_struct *hvcs_get_by_index(int index)
903 {
904         struct hvcs_struct *hvcsd;
905         unsigned long flags;
906
907         spin_lock(&hvcs_structs_lock);
908         /* We can immediately discard OOB requests */
909         if (index >= 0 && index < HVCS_MAX_SERVER_ADAPTERS) {
910                 list_for_each_entry(hvcsd, &hvcs_structs, next) {
911                         spin_lock_irqsave(&hvcsd->lock, flags);
912                         if (hvcsd->index == index) {
913                                 kobject_get(&hvcsd->kobj);
914                                 spin_unlock_irqrestore(&hvcsd->lock, flags);
915                                 spin_unlock(&hvcs_structs_lock);
916                                 return hvcsd;
917                         }
918                         spin_unlock_irqrestore(&hvcsd->lock, flags);
919                 }
920                 hvcsd = NULL;
921         }
922
923         spin_unlock(&hvcs_structs_lock);
924         return hvcsd;
925 }
926
927 /*
928  * This is invoked via the tty_open interface when a user app connects to the
929  * /dev node.
930  */
931 static int hvcs_open(struct tty_struct *tty, struct file *filp)
932 {
933         struct hvcs_struct *hvcsd;
934         int rc, retval = 0;
935         unsigned long flags;
936         unsigned int irq;
937         struct vio_dev *vdev;
938         unsigned long unit_address;
939         struct kobject *kobjp;
940
941         if (tty->driver_data)
942                 goto fast_open;
943
944         /*
945          * Is there a vty-server that shares the same index?
946          * This function increments the kobject index.
947          */
948         if (!(hvcsd = hvcs_get_by_index(tty->index))) {
949                 printk(KERN_WARNING "HVCS: open failed, no index.\n");
950                 return -ENODEV;
951         }
952
953         spin_lock_irqsave(&hvcsd->lock, flags);
954
955         if (hvcsd->connected == 0)
956                 if ((retval = hvcs_partner_connect(hvcsd)))
957                         goto error_release;
958
959         hvcsd->open_count = 1;
960         hvcsd->tty = tty;
961         tty->driver_data = hvcsd;
962
963         /*
964          * Set this driver to low latency so that we actually have a chance at
965          * catching a throttled TTY after we flip_buffer_push.  Otherwise the
966          * flush_to_async may not execute until after the kernel_thread has
967          * yielded and resumed the next flip_buffer_push resulting in data
968          * loss.
969          */
970         tty->low_latency = 1;
971
972         memset(&hvcsd->buffer[0], 0x00, HVCS_BUFF_LEN);
973
974         /*
975          * Save these in the spinlock for the enable operations that need them
976          * outside of the spinlock.
977          */
978         irq = hvcsd->vdev->irq;
979         vdev = hvcsd->vdev;
980         unit_address = hvcsd->vdev->unit_address;
981
982         hvcsd->todo_mask |= HVCS_SCHED_READ;
983         spin_unlock_irqrestore(&hvcsd->lock, flags);
984
985         /*
986          * This must be done outside of the spinlock because it requests irqs
987          * and will grab the spinlcok and free the connection if it fails.
988          */
989         if (((rc = hvcs_enable_device(hvcsd, unit_address, irq, vdev)))) {
990                 kobject_put(&hvcsd->kobj);
991                 printk(KERN_WARNING "HVCS: enable device failed.\n");
992                 return rc;
993         }
994
995         goto open_success;
996
997 fast_open:
998         hvcsd = tty->driver_data;
999
1000         spin_lock_irqsave(&hvcsd->lock, flags);
1001         if (!kobject_get(&hvcsd->kobj)) {
1002                 spin_unlock_irqrestore(&hvcsd->lock, flags);
1003                 printk(KERN_ERR "HVCS: Kobject of open"
1004                         " hvcs doesn't exist.\n");
1005                 return -EFAULT; /* Is this the right return value? */
1006         }
1007
1008         hvcsd->open_count++;
1009
1010         hvcsd->todo_mask |= HVCS_SCHED_READ;
1011         spin_unlock_irqrestore(&hvcsd->lock, flags);
1012 open_success:
1013         hvcs_kick();
1014
1015         printk(KERN_INFO "HVCS: vty-server@%X opened.\n",
1016                 hvcsd->vdev->unit_address );
1017
1018         return 0;
1019
1020 error_release:
1021         kobjp = &hvcsd->kobj;
1022         spin_unlock_irqrestore(&hvcsd->lock, flags);
1023         kobject_put(&hvcsd->kobj);
1024
1025         printk(KERN_WARNING "HVCS: HVCS partner connect failed.\n");
1026         return retval;
1027 }
1028
1029 static void hvcs_close(struct tty_struct *tty, struct file *filp)
1030 {
1031         struct hvcs_struct *hvcsd;
1032         unsigned long flags;
1033         struct kobject *kobjp;
1034
1035         /*
1036          * Is someone trying to close the file associated with this device after
1037          * we have hung up?  If so tty->driver_data wouldn't be valid.
1038          */
1039         if (tty_hung_up_p(filp))
1040                 return;
1041
1042         /*
1043          * No driver_data means that this close was probably issued after a
1044          * failed hvcs_open by the tty layer's release_dev() api and we can just
1045          * exit cleanly.
1046          */
1047         if (!tty->driver_data)
1048                 return;
1049
1050         hvcsd = tty->driver_data;
1051
1052         spin_lock_irqsave(&hvcsd->lock, flags);
1053         if (--hvcsd->open_count == 0) {
1054
1055                 /*
1056                  * This line is important because it tells hvcs_open that this
1057                  * device needs to be re-configured the next time hvcs_open is
1058                  * called.
1059                  */
1060                 hvcsd->tty->driver_data = NULL;
1061
1062                 /*
1063                  * NULL this early so that the kernel_thread doesn't try to
1064                  * execute any operations on the TTY even though it is obligated
1065                  * to deliver any pending I/O to the hypervisor.
1066                  */
1067                 hvcsd->tty = NULL;
1068
1069                 /*
1070                  * Block the close until all the buffered data has been
1071                  * delivered.
1072                  */
1073                 while(hvcsd->chars_in_buffer) {
1074                         spin_unlock_irqrestore(&hvcsd->lock, flags);
1075
1076                         /*
1077                          * Give the kernel thread the hvcs_struct so that it can
1078                          * try to deliver the remaining data but block the close
1079                          * operation by spinning in this function so that other
1080                          * tty operations have to wait.
1081                          */
1082                         yield();
1083                         spin_lock_irqsave(&hvcsd->lock, flags);
1084                 }
1085
1086                 hvcs_final_close(hvcsd);
1087
1088         } else if (hvcsd->open_count < 0) {
1089                 printk(KERN_ERR "HVCS: vty-server@%X open_count: %d"
1090                                 " is missmanaged.\n",
1091                         hvcsd->vdev->unit_address, hvcsd->open_count);
1092         }
1093         kobjp = &hvcsd->kobj;
1094
1095         spin_unlock_irqrestore(&hvcsd->lock, flags);
1096
1097         kobject_put(kobjp);
1098 }
1099
1100 static void hvcs_hangup(struct tty_struct * tty)
1101 {
1102         struct hvcs_struct *hvcsd = tty->driver_data;
1103         unsigned long flags;
1104         int temp_open_count;
1105         struct kobject *kobjp;
1106
1107         spin_lock_irqsave(&hvcsd->lock, flags);
1108         /* Preserve this so that we know how many kobject refs to put */
1109         temp_open_count = hvcsd->open_count;
1110
1111         /*
1112          * Don't kobject put inside the spinlock because the destruction
1113          * callback may use the spinlock and it may get called before the
1114          * spinlock has been released.  Get a pointer to the kobject and
1115          * kobject_put on that instead.
1116          */
1117         kobjp = &hvcsd->kobj;
1118
1119         /* Calling this will drop any buffered data on the floor. */
1120         hvcs_final_close(hvcsd);
1121
1122         spin_unlock_irqrestore(&hvcsd->lock, flags);
1123
1124         /*
1125          * We need to kobject_put() for every open_count we have since the
1126          * tty_hangup() function doesn't invoke a close per open connection on a
1127          * non-console device.
1128          */
1129         while(temp_open_count) {
1130                 --temp_open_count;
1131                 /*
1132                  * The final put will trigger destruction of the hvcs_struct.
1133                  * NOTE:  If this hangup was signaled from user space then the
1134                  * final put will never happen.
1135                  */
1136                 kobject_put(kobjp);
1137         }
1138 }
1139
1140 /*
1141  * NOTE: This is almost always from_user since user level apps interact with the
1142  * /dev nodes. I'm trusting that if hvcs_write gets called and interrupted by
1143  * hvcs_remove (which removes the target device and executes tty_hangup()) that
1144  * tty_hangup will allow hvcs_write time to complete execution before it
1145  * terminates our device.
1146  */
1147 static int hvcs_write(struct tty_struct *tty, int from_user,
1148                 const unsigned char *buf, int count)
1149 {
1150         struct hvcs_struct *hvcsd = tty->driver_data;
1151         unsigned int unit_address;
1152         unsigned char *charbuf;
1153         unsigned long flags;
1154         int total_sent = 0;
1155         int tosend = 0;
1156         int result = 0;
1157
1158         /*
1159          * If they don't check the return code off of their open they may
1160          * attempt this even if there is no connected device.
1161          */
1162         if (!hvcsd)
1163                 return -ENODEV;
1164
1165         /* Reasonable size to prevent user level flooding */
1166         if (count > HVCS_MAX_FROM_USER) {
1167                 printk(KERN_WARNING "HVCS write: count being truncated to"
1168                                 " HVCS_MAX_FROM_USER.\n");
1169                 count = HVCS_MAX_FROM_USER;
1170         }
1171
1172         if (!from_user)
1173                 charbuf = (unsigned char *)buf;
1174         else {
1175                 charbuf = kmalloc(count, GFP_KERNEL);
1176                 if (!charbuf) {
1177                         printk(KERN_WARNING "HVCS: write -ENOMEM.\n");
1178                         return -ENOMEM;
1179                 }
1180
1181                 if (copy_from_user(charbuf, buf, count)) {
1182                         kfree(charbuf);
1183                         printk(KERN_WARNING "HVCS: write -EFAULT.\n");
1184                         return -EFAULT;
1185                 }
1186         }
1187
1188         spin_lock_irqsave(&hvcsd->lock, flags);
1189
1190         /*
1191          * Somehow an open succedded but the device was removed or the
1192          * connection terminated between the vty-server and partner vty during
1193          * the middle of a write operation?  This is a crummy place to do this
1194          * but we want to keep it all in the spinlock.
1195          */
1196         if (hvcsd->open_count <= 0) {
1197                 spin_unlock_irqrestore(&hvcsd->lock, flags);
1198                 if (from_user)
1199                         kfree(charbuf);
1200                 return -ENODEV;
1201         }
1202
1203         unit_address = hvcsd->vdev->unit_address;
1204
1205         while (count > 0) {
1206                 tosend = min(count, (HVCS_BUFF_LEN - hvcsd->chars_in_buffer));
1207                 /*
1208                  * No more space, this probably means that the last call to
1209                  * hvcs_write() didn't succeed and the buffer was filled up.
1210                  */
1211                 if (!tosend)
1212                         break;
1213
1214                 memcpy(&hvcsd->buffer[hvcsd->chars_in_buffer],
1215                                 &charbuf[total_sent],
1216                                 tosend);
1217
1218                 hvcsd->chars_in_buffer += tosend;
1219
1220                 result = 0;
1221
1222                 /*
1223                  * If this is true then we don't want to try writing to the
1224                  * hypervisor because that is the kernel_threads job now.  We'll
1225                  * just add to the buffer.
1226                  */
1227                 if (!(hvcsd->todo_mask & HVCS_TRY_WRITE))
1228                         /* won't send partial writes */
1229                         result = hvc_put_chars(unit_address,
1230                                         &hvcsd->buffer[0],
1231                                         hvcsd->chars_in_buffer);
1232
1233                 /*
1234                  * Since we know we have enough room in hvcsd->buffer for
1235                  * tosend we record that it was sent regardless of whether the
1236                  * hypervisor actually took it because we have it buffered.
1237                  */
1238                 total_sent+=tosend;
1239                 count-=tosend;
1240                 if (result == 0) {
1241                         hvcsd->todo_mask |= HVCS_TRY_WRITE;
1242                         hvcs_kick();
1243                         break;
1244                 }
1245
1246                 hvcsd->chars_in_buffer = 0;
1247                 /*
1248                  * Test after the chars_in_buffer reset otherwise this could
1249                  * deadlock our writes if hvc_put_chars fails.
1250                  */
1251                 if (result < 0)
1252                         break;
1253         }
1254
1255         spin_unlock_irqrestore(&hvcsd->lock, flags);
1256         if (from_user)
1257                 kfree(charbuf);
1258
1259         if (result == -1)
1260                 return -EIO;
1261         else
1262                 return total_sent;
1263 }
1264
1265 /*
1266  * This is really asking how much can we guarentee that we can send or that we
1267  * absolutely WILL BUFFER if we can't send it.  This driver MUST honor the
1268  * return value, hence the reason for hvcs_struct buffering.
1269  */
1270 static int hvcs_write_room(struct tty_struct *tty)
1271 {
1272         struct hvcs_struct *hvcsd = tty->driver_data;
1273         unsigned long flags;
1274         int retval;
1275
1276         if (!hvcsd || hvcsd->open_count <= 0)
1277                 return 0;
1278
1279         spin_lock_irqsave(&hvcsd->lock, flags);
1280         retval = HVCS_BUFF_LEN - hvcsd->chars_in_buffer;
1281         spin_unlock_irqrestore(&hvcsd->lock, flags);
1282         return retval;
1283 }
1284
1285 static int hvcs_chars_in_buffer(struct tty_struct *tty)
1286 {
1287         struct hvcs_struct *hvcsd = tty->driver_data;
1288         unsigned long flags;
1289         int retval;
1290
1291         spin_lock_irqsave(&hvcsd->lock, flags);
1292         retval = hvcsd->chars_in_buffer;
1293         spin_unlock_irqrestore(&hvcsd->lock, flags);
1294         return retval;
1295 }
1296
1297 static struct tty_operations hvcs_ops = {
1298         .open = hvcs_open,
1299         .close = hvcs_close,
1300         .hangup = hvcs_hangup,
1301         .write = hvcs_write,
1302         .write_room = hvcs_write_room,
1303         .chars_in_buffer = hvcs_chars_in_buffer,
1304         .unthrottle = hvcs_unthrottle,
1305         .throttle = hvcs_throttle,
1306 };
1307
1308 static int __init hvcs_module_init(void)
1309 {
1310         int rc;
1311         int num_ttys_to_alloc;
1312
1313         printk(KERN_INFO "Initializing %s\n", hvcs_driver_string);
1314
1315         /* Has the user specified an overload with an insmod param? */
1316         if (hvcs_parm_num_devs <= 0 ||
1317                 (hvcs_parm_num_devs > HVCS_MAX_SERVER_ADAPTERS)) {
1318                 num_ttys_to_alloc = HVCS_DEFAULT_SERVER_ADAPTERS;
1319         } else
1320                 num_ttys_to_alloc = hvcs_parm_num_devs;
1321
1322         hvcs_tty_driver = alloc_tty_driver(num_ttys_to_alloc);
1323         if (!hvcs_tty_driver)
1324                 return -ENOMEM;
1325
1326         hvcs_tty_driver->owner = THIS_MODULE;
1327
1328         hvcs_tty_driver->driver_name = hvcs_driver_name;
1329         hvcs_tty_driver->name = hvcs_device_node;
1330
1331         /*
1332          * We'll let the system assign us a major number, indicated by leaving
1333          * it blank.
1334          */
1335
1336         hvcs_tty_driver->minor_start = HVCS_MINOR_START;
1337         hvcs_tty_driver->type = TTY_DRIVER_TYPE_SYSTEM;
1338
1339         /*
1340          * We role our own so that we DONT ECHO.  We can't echo because the
1341          * device we are connecting to already echoes by default and this would
1342          * throw us into a horrible recursive echo-echo-echo loop.
1343          */
1344         hvcs_tty_driver->init_termios = hvcs_tty_termios;
1345         hvcs_tty_driver->flags = TTY_DRIVER_REAL_RAW;
1346
1347         tty_set_operations(hvcs_tty_driver, &hvcs_ops);
1348
1349         /*
1350          * The following call will result in sysfs entries that denote the
1351          * dynamically assigned major and minor numbers for our devices.
1352          */
1353         if (tty_register_driver(hvcs_tty_driver)) {
1354                 printk(KERN_ERR "HVCS: registration "
1355                         " as a tty driver failed.\n");
1356                 put_tty_driver(hvcs_tty_driver);
1357                 return rc;
1358         }
1359
1360         hvcs_pi_buff = kmalloc(PAGE_SIZE, GFP_KERNEL);
1361         if (!hvcs_pi_buff) {
1362                 tty_unregister_driver(hvcs_tty_driver);
1363                 put_tty_driver(hvcs_tty_driver);
1364                 return -ENOMEM;
1365         }
1366
1367         hvcs_task = kthread_run(khvcsd, NULL, "khvcsd");
1368         if (IS_ERR(hvcs_task)) {
1369                 printk("khvcsd creation failed.  Driver not loaded.\n");
1370                 kfree(hvcs_pi_buff);
1371                 put_tty_driver(hvcs_tty_driver);
1372                 return -EIO;
1373         }
1374
1375         rc = vio_register_driver(&hvcs_vio_driver);
1376
1377         /*
1378          * This needs to be done AFTER the vio_register_driver() call or else
1379          * the kobjects won't be initialized properly.
1380          */
1381         hvcs_create_driver_attrs();
1382
1383         printk(KERN_INFO "HVCS: driver module inserted.\n");
1384
1385         return rc;
1386 }
1387
1388 static void __exit hvcs_module_exit(void)
1389 {
1390         /*
1391          * This driver receives hvcs_remove callbacks for each device upon
1392          * module removal.
1393          */
1394
1395         /*
1396          * This synchronous operation  will wake the khvcsd kthread if it is
1397          * asleep and will return when khvcsd has terminated.
1398          */
1399         kthread_stop(hvcs_task);
1400
1401         spin_lock(&hvcs_pi_lock);
1402         kfree(hvcs_pi_buff);
1403         hvcs_pi_buff = NULL;
1404         spin_unlock(&hvcs_pi_lock);
1405
1406         hvcs_remove_driver_attrs();
1407
1408         vio_unregister_driver(&hvcs_vio_driver);
1409
1410         tty_unregister_driver(hvcs_tty_driver);
1411
1412         put_tty_driver(hvcs_tty_driver);
1413
1414         printk(KERN_INFO "HVCS: driver module removed.\n");
1415 }
1416
1417 module_init(hvcs_module_init);
1418 module_exit(hvcs_module_exit);
1419
1420 static inline struct hvcs_struct *from_vio_dev(struct vio_dev *viod)
1421 {
1422         return viod->dev.driver_data;
1423 }
1424 /* The sysfs interface for the driver and devices */
1425
1426 static ssize_t hvcs_partner_vtys_show(struct device *dev, char *buf)
1427 {
1428         struct vio_dev *viod = to_vio_dev(dev);
1429         struct hvcs_struct *hvcsd = from_vio_dev(viod);
1430         unsigned long flags;
1431         int retval;
1432
1433         spin_lock_irqsave(&hvcsd->lock, flags);
1434         retval = sprintf(buf, "%X\n", hvcsd->p_unit_address);
1435         spin_unlock_irqrestore(&hvcsd->lock, flags);
1436         return retval;
1437 }
1438 static DEVICE_ATTR(partner_vtys, S_IRUGO, hvcs_partner_vtys_show, NULL);
1439
1440 static ssize_t hvcs_partner_clcs_show(struct device *dev, char *buf)
1441 {
1442         struct vio_dev *viod = to_vio_dev(dev);
1443         struct hvcs_struct *hvcsd = from_vio_dev(viod);
1444         unsigned long flags;
1445         int retval;
1446
1447         spin_lock_irqsave(&hvcsd->lock, flags);
1448         retval = sprintf(buf, "%s\n", &hvcsd->p_location_code[0]);
1449         spin_unlock_irqrestore(&hvcsd->lock, flags);
1450         return retval;
1451 }
1452 static DEVICE_ATTR(partner_clcs, S_IRUGO, hvcs_partner_clcs_show, NULL);
1453
1454 static ssize_t hvcs_current_vty_store(struct device *dev, const char * buf,
1455                 size_t count)
1456 {
1457         /*
1458          * Don't need this feature at the present time because firmware doesn't
1459          * yet support multiple partners.
1460          */
1461         printk(KERN_INFO "HVCS: Denied current_vty change: -EPERM.\n");
1462         return -EPERM;
1463 }
1464
1465 static ssize_t hvcs_current_vty_show(struct device *dev, char *buf)
1466 {
1467         struct vio_dev *viod = to_vio_dev(dev);
1468         struct hvcs_struct *hvcsd = from_vio_dev(viod);
1469         unsigned long flags;
1470         int retval;
1471
1472         spin_lock_irqsave(&hvcsd->lock, flags);
1473         retval = sprintf(buf, "%s\n", &hvcsd->p_location_code[0]);
1474         spin_unlock_irqrestore(&hvcsd->lock, flags);
1475         return retval;
1476 }
1477
1478 static DEVICE_ATTR(current_vty,
1479         S_IRUGO | S_IWUSR, hvcs_current_vty_show, hvcs_current_vty_store);
1480
1481 static ssize_t hvcs_vterm_state_store(struct device *dev, const char *buf,
1482                 size_t count)
1483 {
1484         struct vio_dev *viod = to_vio_dev(dev);
1485         struct hvcs_struct *hvcsd = from_vio_dev(viod);
1486         unsigned long flags;
1487
1488         /* writing a '0' to this sysfs entry will result in the disconnect. */
1489         if (simple_strtol(buf, NULL, 0) != 0)
1490                 return -EINVAL;
1491
1492         spin_lock_irqsave(&hvcsd->lock, flags);
1493
1494         if (hvcsd->open_count > 0) {
1495                 spin_unlock_irqrestore(&hvcsd->lock, flags);
1496                 printk(KERN_INFO "HVCS: vterm state unchanged.  "
1497                                 "The hvcs device node is still in use.\n");
1498                 return -EPERM;
1499         }
1500
1501         if (hvcsd->connected == 0) {
1502                 spin_unlock_irqrestore(&hvcsd->lock, flags);
1503                 printk(KERN_INFO "HVCS: vterm state unchanged. The"
1504                                 " vty-server is not connected to a vty.\n");
1505                 return -EPERM;
1506         }
1507
1508         hvcs_partner_free(hvcsd);
1509         printk(KERN_INFO "HVCS: Closed vty-server@%X and"
1510                         " partner vty@%X:%d connection.\n",
1511                         hvcsd->vdev->unit_address,
1512                         hvcsd->p_unit_address,
1513                         (uint32_t)hvcsd->p_partition_ID);
1514
1515         spin_unlock_irqrestore(&hvcsd->lock, flags);
1516         return count;
1517 }
1518
1519 static ssize_t hvcs_vterm_state_show(struct device *dev, char *buf)
1520 {
1521         struct vio_dev *viod = to_vio_dev(dev);
1522         struct hvcs_struct *hvcsd = from_vio_dev(viod);
1523         unsigned long flags;
1524         int retval;
1525
1526         spin_lock_irqsave(&hvcsd->lock, flags);
1527         retval = sprintf(buf, "%d\n", hvcsd->connected);
1528         spin_unlock_irqrestore(&hvcsd->lock, flags);
1529         return retval;
1530 }
1531 static DEVICE_ATTR(vterm_state, S_IRUGO | S_IWUSR,
1532                 hvcs_vterm_state_show, hvcs_vterm_state_store);
1533
1534 static ssize_t hvcs_index_show(struct device *dev, char *buf)
1535 {
1536         struct vio_dev *viod = to_vio_dev(dev);
1537         struct hvcs_struct *hvcsd = from_vio_dev(viod);
1538         unsigned long flags;
1539         int retval;
1540
1541         spin_lock_irqsave(&hvcsd->lock, flags);
1542         retval = sprintf(buf, "%d\n", hvcsd->index);
1543         spin_unlock_irqrestore(&hvcsd->lock, flags);
1544         return retval;
1545 }
1546
1547 static DEVICE_ATTR(index, S_IRUGO, hvcs_index_show, NULL);
1548
1549 static struct attribute *hvcs_attrs[] = {
1550         &dev_attr_partner_vtys.attr,
1551         &dev_attr_partner_clcs.attr,
1552         &dev_attr_current_vty.attr,
1553         &dev_attr_vterm_state.attr,
1554         &dev_attr_index.attr,
1555         NULL,
1556 };
1557
1558 static struct attribute_group hvcs_attr_group = {
1559         .attrs = hvcs_attrs,
1560 };
1561
1562 static void hvcs_create_device_attrs(struct hvcs_struct *hvcsd)
1563 {
1564         struct vio_dev *vdev = hvcsd->vdev;
1565         sysfs_create_group(&vdev->dev.kobj, &hvcs_attr_group);
1566 }
1567
1568 static void hvcs_remove_device_attrs(struct vio_dev *vdev)
1569 {
1570         sysfs_remove_group(&vdev->dev.kobj, &hvcs_attr_group);
1571 }
1572
1573 static ssize_t hvcs_rescan_show(struct device_driver *ddp, char *buf)
1574 {
1575         /* A 1 means it is updating, a 0 means it is done updating */
1576         return snprintf(buf, PAGE_SIZE, "%d\n", hvcs_rescan_status);
1577 }
1578
1579 static ssize_t hvcs_rescan_store(struct device_driver *ddp, const char * buf,
1580                 size_t count)
1581 {
1582         if ((simple_strtol(buf, NULL, 0) != 1)
1583                 && (hvcs_rescan_status != 0))
1584                 return -EINVAL;
1585
1586         hvcs_rescan_status = 1;
1587         printk(KERN_INFO "HVCS: rescanning partner info for all"
1588                 " vty-servers.\n");
1589         hvcs_rescan_devices_list();
1590         hvcs_rescan_status = 0;
1591         return count;
1592 }
1593 static DRIVER_ATTR(rescan,
1594         S_IRUGO | S_IWUSR, hvcs_rescan_show, hvcs_rescan_store);
1595
1596 static void hvcs_create_driver_attrs(void)
1597 {
1598         struct device_driver *driverfs = &(hvcs_vio_driver.driver);
1599         driver_create_file(driverfs, &driver_attr_rescan);
1600 }
1601
1602 static void hvcs_remove_driver_attrs(void)
1603 {
1604         struct device_driver *driverfs = &(hvcs_vio_driver.driver);
1605         driver_remove_file(driverfs, &driver_attr_rescan);
1606 }