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