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