xref: /openbmc/linux/drivers/tty/hvc/hvcs.c (revision bbb774d9)
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 int hvcs_get_pi(struct hvcs_struct *hvcsd);
294 static int hvcs_rescan_devices_list(void);
295 
296 static void hvcs_partner_free(struct hvcs_struct *hvcsd);
297 
298 static int hvcs_initialize(void);
299 
300 #define HVCS_SCHED_READ	0x00000001
301 #define HVCS_QUICK_READ	0x00000002
302 #define HVCS_TRY_WRITE	0x00000004
303 #define HVCS_READ_MASK	(HVCS_SCHED_READ | HVCS_QUICK_READ)
304 
305 static inline struct hvcs_struct *from_vio_dev(struct vio_dev *viod)
306 {
307 	return dev_get_drvdata(&viod->dev);
308 }
309 /* The sysfs interface for the driver and devices */
310 
311 static ssize_t hvcs_partner_vtys_show(struct device *dev, struct device_attribute *attr, char *buf)
312 {
313 	struct vio_dev *viod = to_vio_dev(dev);
314 	struct hvcs_struct *hvcsd = from_vio_dev(viod);
315 	unsigned long flags;
316 	int retval;
317 
318 	spin_lock_irqsave(&hvcsd->lock, flags);
319 	retval = sprintf(buf, "%X\n", hvcsd->p_unit_address);
320 	spin_unlock_irqrestore(&hvcsd->lock, flags);
321 	return retval;
322 }
323 static DEVICE_ATTR(partner_vtys, S_IRUGO, hvcs_partner_vtys_show, NULL);
324 
325 static ssize_t hvcs_partner_clcs_show(struct device *dev, struct device_attribute *attr, char *buf)
326 {
327 	struct vio_dev *viod = to_vio_dev(dev);
328 	struct hvcs_struct *hvcsd = from_vio_dev(viod);
329 	unsigned long flags;
330 	int retval;
331 
332 	spin_lock_irqsave(&hvcsd->lock, flags);
333 	retval = sprintf(buf, "%s\n", &hvcsd->p_location_code[0]);
334 	spin_unlock_irqrestore(&hvcsd->lock, flags);
335 	return retval;
336 }
337 static DEVICE_ATTR(partner_clcs, S_IRUGO, hvcs_partner_clcs_show, NULL);
338 
339 static ssize_t hvcs_current_vty_store(struct device *dev, struct device_attribute *attr, const char * buf,
340 		size_t count)
341 {
342 	/*
343 	 * Don't need this feature at the present time because firmware doesn't
344 	 * yet support multiple partners.
345 	 */
346 	printk(KERN_INFO "HVCS: Denied current_vty change: -EPERM.\n");
347 	return -EPERM;
348 }
349 
350 static ssize_t hvcs_current_vty_show(struct device *dev, struct device_attribute *attr, char *buf)
351 {
352 	struct vio_dev *viod = to_vio_dev(dev);
353 	struct hvcs_struct *hvcsd = from_vio_dev(viod);
354 	unsigned long flags;
355 	int retval;
356 
357 	spin_lock_irqsave(&hvcsd->lock, flags);
358 	retval = sprintf(buf, "%s\n", &hvcsd->p_location_code[0]);
359 	spin_unlock_irqrestore(&hvcsd->lock, flags);
360 	return retval;
361 }
362 
363 static DEVICE_ATTR(current_vty,
364 	S_IRUGO | S_IWUSR, hvcs_current_vty_show, hvcs_current_vty_store);
365 
366 static ssize_t hvcs_vterm_state_store(struct device *dev, struct device_attribute *attr, const char *buf,
367 		size_t count)
368 {
369 	struct vio_dev *viod = to_vio_dev(dev);
370 	struct hvcs_struct *hvcsd = from_vio_dev(viod);
371 	unsigned long flags;
372 
373 	/* writing a '0' to this sysfs entry will result in the disconnect. */
374 	if (simple_strtol(buf, NULL, 0) != 0)
375 		return -EINVAL;
376 
377 	spin_lock_irqsave(&hvcsd->lock, flags);
378 
379 	if (hvcsd->port.count > 0) {
380 		spin_unlock_irqrestore(&hvcsd->lock, flags);
381 		printk(KERN_INFO "HVCS: vterm state unchanged.  "
382 				"The hvcs device node is still in use.\n");
383 		return -EPERM;
384 	}
385 
386 	if (hvcsd->connected == 0) {
387 		spin_unlock_irqrestore(&hvcsd->lock, flags);
388 		printk(KERN_INFO "HVCS: vterm state unchanged. The"
389 				" vty-server is not connected to a vty.\n");
390 		return -EPERM;
391 	}
392 
393 	hvcs_partner_free(hvcsd);
394 	printk(KERN_INFO "HVCS: Closed vty-server@%X and"
395 			" partner vty@%X:%d connection.\n",
396 			hvcsd->vdev->unit_address,
397 			hvcsd->p_unit_address,
398 			(uint32_t)hvcsd->p_partition_ID);
399 
400 	spin_unlock_irqrestore(&hvcsd->lock, flags);
401 	return count;
402 }
403 
404 static ssize_t hvcs_vterm_state_show(struct device *dev, struct device_attribute *attr, char *buf)
405 {
406 	struct vio_dev *viod = to_vio_dev(dev);
407 	struct hvcs_struct *hvcsd = from_vio_dev(viod);
408 	unsigned long flags;
409 	int retval;
410 
411 	spin_lock_irqsave(&hvcsd->lock, flags);
412 	retval = sprintf(buf, "%d\n", hvcsd->connected);
413 	spin_unlock_irqrestore(&hvcsd->lock, flags);
414 	return retval;
415 }
416 static DEVICE_ATTR(vterm_state, S_IRUGO | S_IWUSR,
417 		hvcs_vterm_state_show, hvcs_vterm_state_store);
418 
419 static ssize_t hvcs_index_show(struct device *dev, struct device_attribute *attr, char *buf)
420 {
421 	struct vio_dev *viod = to_vio_dev(dev);
422 	struct hvcs_struct *hvcsd = from_vio_dev(viod);
423 	unsigned long flags;
424 	int retval;
425 
426 	spin_lock_irqsave(&hvcsd->lock, flags);
427 	retval = sprintf(buf, "%d\n", hvcsd->index);
428 	spin_unlock_irqrestore(&hvcsd->lock, flags);
429 	return retval;
430 }
431 
432 static DEVICE_ATTR(index, S_IRUGO, hvcs_index_show, NULL);
433 
434 static struct attribute *hvcs_attrs[] = {
435 	&dev_attr_partner_vtys.attr,
436 	&dev_attr_partner_clcs.attr,
437 	&dev_attr_current_vty.attr,
438 	&dev_attr_vterm_state.attr,
439 	&dev_attr_index.attr,
440 	NULL,
441 };
442 
443 static struct attribute_group hvcs_attr_group = {
444 	.attrs = hvcs_attrs,
445 };
446 
447 static ssize_t rescan_show(struct device_driver *ddp, char *buf)
448 {
449 	/* A 1 means it is updating, a 0 means it is done updating */
450 	return snprintf(buf, PAGE_SIZE, "%d\n", hvcs_rescan_status);
451 }
452 
453 static ssize_t rescan_store(struct device_driver *ddp, const char * buf,
454 		size_t count)
455 {
456 	if ((simple_strtol(buf, NULL, 0) != 1)
457 		&& (hvcs_rescan_status != 0))
458 		return -EINVAL;
459 
460 	hvcs_rescan_status = 1;
461 	printk(KERN_INFO "HVCS: rescanning partner info for all"
462 		" vty-servers.\n");
463 	hvcs_rescan_devices_list();
464 	hvcs_rescan_status = 0;
465 	return count;
466 }
467 
468 static DRIVER_ATTR_RW(rescan);
469 
470 static void hvcs_kick(void)
471 {
472 	hvcs_kicked = 1;
473 	wmb();
474 	wake_up_process(hvcs_task);
475 }
476 
477 static void hvcs_unthrottle(struct tty_struct *tty)
478 {
479 	struct hvcs_struct *hvcsd = tty->driver_data;
480 	unsigned long flags;
481 
482 	spin_lock_irqsave(&hvcsd->lock, flags);
483 	hvcsd->todo_mask |= HVCS_SCHED_READ;
484 	spin_unlock_irqrestore(&hvcsd->lock, flags);
485 	hvcs_kick();
486 }
487 
488 static void hvcs_throttle(struct tty_struct *tty)
489 {
490 	struct hvcs_struct *hvcsd = tty->driver_data;
491 	unsigned long flags;
492 
493 	spin_lock_irqsave(&hvcsd->lock, flags);
494 	vio_disable_interrupts(hvcsd->vdev);
495 	spin_unlock_irqrestore(&hvcsd->lock, flags);
496 }
497 
498 /*
499  * If the device is being removed we don't have to worry about this interrupt
500  * handler taking any further interrupts because they are disabled which means
501  * the hvcs_struct will always be valid in this handler.
502  */
503 static irqreturn_t hvcs_handle_interrupt(int irq, void *dev_instance)
504 {
505 	struct hvcs_struct *hvcsd = dev_instance;
506 
507 	spin_lock(&hvcsd->lock);
508 	vio_disable_interrupts(hvcsd->vdev);
509 	hvcsd->todo_mask |= HVCS_SCHED_READ;
510 	spin_unlock(&hvcsd->lock);
511 	hvcs_kick();
512 
513 	return IRQ_HANDLED;
514 }
515 
516 /* This function must be called with the hvcsd->lock held */
517 static void hvcs_try_write(struct hvcs_struct *hvcsd)
518 {
519 	uint32_t unit_address = hvcsd->vdev->unit_address;
520 	struct tty_struct *tty = hvcsd->port.tty;
521 	int sent;
522 
523 	if (hvcsd->todo_mask & HVCS_TRY_WRITE) {
524 		/* won't send partial writes */
525 		sent = hvc_put_chars(unit_address,
526 				&hvcsd->buffer[0],
527 				hvcsd->chars_in_buffer );
528 		if (sent > 0) {
529 			hvcsd->chars_in_buffer = 0;
530 			/* wmb(); */
531 			hvcsd->todo_mask &= ~(HVCS_TRY_WRITE);
532 			/* wmb(); */
533 
534 			/*
535 			 * We are still obligated to deliver the data to the
536 			 * hypervisor even if the tty has been closed because
537 			 * we committed to delivering it.  But don't try to wake
538 			 * a non-existent tty.
539 			 */
540 			if (tty) {
541 				tty_wakeup(tty);
542 			}
543 		}
544 	}
545 }
546 
547 static int hvcs_io(struct hvcs_struct *hvcsd)
548 {
549 	uint32_t unit_address;
550 	struct tty_struct *tty;
551 	char buf[HVCS_BUFF_LEN] __ALIGNED__;
552 	unsigned long flags;
553 	int got = 0;
554 
555 	spin_lock_irqsave(&hvcsd->lock, flags);
556 
557 	unit_address = hvcsd->vdev->unit_address;
558 	tty = hvcsd->port.tty;
559 
560 	hvcs_try_write(hvcsd);
561 
562 	if (!tty || tty_throttled(tty)) {
563 		hvcsd->todo_mask &= ~(HVCS_READ_MASK);
564 		goto bail;
565 	} else if (!(hvcsd->todo_mask & (HVCS_READ_MASK)))
566 		goto bail;
567 
568 	/* remove the read masks */
569 	hvcsd->todo_mask &= ~(HVCS_READ_MASK);
570 
571 	if (tty_buffer_request_room(&hvcsd->port, HVCS_BUFF_LEN) >= HVCS_BUFF_LEN) {
572 		got = hvc_get_chars(unit_address,
573 				&buf[0],
574 				HVCS_BUFF_LEN);
575 		tty_insert_flip_string(&hvcsd->port, buf, got);
576 	}
577 
578 	/* Give the TTY time to process the data we just sent. */
579 	if (got)
580 		hvcsd->todo_mask |= HVCS_QUICK_READ;
581 
582 	spin_unlock_irqrestore(&hvcsd->lock, flags);
583 	/* This is synch -- FIXME :js: it is not! */
584 	if (got)
585 		tty_flip_buffer_push(&hvcsd->port);
586 	else {
587 		/* Do this _after_ the flip_buffer_push */
588 		spin_lock_irqsave(&hvcsd->lock, flags);
589 		vio_enable_interrupts(hvcsd->vdev);
590 		spin_unlock_irqrestore(&hvcsd->lock, flags);
591 	}
592 
593 	return hvcsd->todo_mask;
594 
595  bail:
596 	spin_unlock_irqrestore(&hvcsd->lock, flags);
597 	return hvcsd->todo_mask;
598 }
599 
600 static int khvcsd(void *unused)
601 {
602 	struct hvcs_struct *hvcsd;
603 	int hvcs_todo_mask;
604 
605 	__set_current_state(TASK_RUNNING);
606 
607 	do {
608 		hvcs_todo_mask = 0;
609 		hvcs_kicked = 0;
610 		wmb();
611 
612 		spin_lock(&hvcs_structs_lock);
613 		list_for_each_entry(hvcsd, &hvcs_structs, next) {
614 			hvcs_todo_mask |= hvcs_io(hvcsd);
615 		}
616 		spin_unlock(&hvcs_structs_lock);
617 
618 		/*
619 		 * If any of the hvcs adapters want to try a write or quick read
620 		 * don't schedule(), yield a smidgen then execute the hvcs_io
621 		 * thread again for those that want the write.
622 		 */
623 		 if (hvcs_todo_mask & (HVCS_TRY_WRITE | HVCS_QUICK_READ)) {
624 			yield();
625 			continue;
626 		}
627 
628 		set_current_state(TASK_INTERRUPTIBLE);
629 		if (!hvcs_kicked)
630 			schedule();
631 		__set_current_state(TASK_RUNNING);
632 	} while (!kthread_should_stop());
633 
634 	return 0;
635 }
636 
637 static const struct vio_device_id hvcs_driver_table[] = {
638 	{"serial-server", "hvterm2"},
639 	{ "", "" }
640 };
641 MODULE_DEVICE_TABLE(vio, hvcs_driver_table);
642 
643 static void hvcs_return_index(int index)
644 {
645 	/* Paranoia check */
646 	if (!hvcs_index_list)
647 		return;
648 	if (index < 0 || index >= hvcs_index_count)
649 		return;
650 	if (hvcs_index_list[index] == -1)
651 		return;
652 	else
653 		hvcs_index_list[index] = -1;
654 }
655 
656 static void hvcs_destruct_port(struct tty_port *p)
657 {
658 	struct hvcs_struct *hvcsd = container_of(p, struct hvcs_struct, port);
659 	struct vio_dev *vdev;
660 	unsigned long flags;
661 
662 	spin_lock(&hvcs_structs_lock);
663 	spin_lock_irqsave(&hvcsd->lock, flags);
664 
665 	/* the list_del poisons the pointers */
666 	list_del(&(hvcsd->next));
667 
668 	if (hvcsd->connected == 1) {
669 		hvcs_partner_free(hvcsd);
670 		printk(KERN_INFO "HVCS: Closed vty-server@%X and"
671 				" partner vty@%X:%d connection.\n",
672 				hvcsd->vdev->unit_address,
673 				hvcsd->p_unit_address,
674 				(uint32_t)hvcsd->p_partition_ID);
675 	}
676 	printk(KERN_INFO "HVCS: Destroyed hvcs_struct for vty-server@%X.\n",
677 			hvcsd->vdev->unit_address);
678 
679 	vdev = hvcsd->vdev;
680 	hvcsd->vdev = NULL;
681 
682 	hvcsd->p_unit_address = 0;
683 	hvcsd->p_partition_ID = 0;
684 	hvcs_return_index(hvcsd->index);
685 	memset(&hvcsd->p_location_code[0], 0x00, HVCS_CLC_LENGTH + 1);
686 
687 	spin_unlock_irqrestore(&hvcsd->lock, flags);
688 	spin_unlock(&hvcs_structs_lock);
689 
690 	sysfs_remove_group(&vdev->dev.kobj, &hvcs_attr_group);
691 
692 	kfree(hvcsd);
693 }
694 
695 static const struct tty_port_operations hvcs_port_ops = {
696 	.destruct = hvcs_destruct_port,
697 };
698 
699 static int hvcs_get_index(void)
700 {
701 	int i;
702 	/* Paranoia check */
703 	if (!hvcs_index_list) {
704 		printk(KERN_ERR "HVCS: hvcs_index_list NOT valid!.\n");
705 		return -EFAULT;
706 	}
707 	/* Find the numerically lowest first free index. */
708 	for(i = 0; i < hvcs_index_count; i++) {
709 		if (hvcs_index_list[i] == -1) {
710 			hvcs_index_list[i] = 0;
711 			return i;
712 		}
713 	}
714 	return -1;
715 }
716 
717 static int hvcs_probe(
718 	struct vio_dev *dev,
719 	const struct vio_device_id *id)
720 {
721 	struct hvcs_struct *hvcsd;
722 	int index, rc;
723 	int retval;
724 
725 	if (!dev || !id) {
726 		printk(KERN_ERR "HVCS: probed with invalid parameter.\n");
727 		return -EPERM;
728 	}
729 
730 	/* Make sure we are properly initialized */
731 	rc = hvcs_initialize();
732 	if (rc) {
733 		pr_err("HVCS: Failed to initialize core driver.\n");
734 		return rc;
735 	}
736 
737 	/* early to avoid cleanup on failure */
738 	index = hvcs_get_index();
739 	if (index < 0) {
740 		return -EFAULT;
741 	}
742 
743 	hvcsd = kzalloc(sizeof(*hvcsd), GFP_KERNEL);
744 	if (!hvcsd)
745 		return -ENODEV;
746 
747 	tty_port_init(&hvcsd->port);
748 	hvcsd->port.ops = &hvcs_port_ops;
749 	spin_lock_init(&hvcsd->lock);
750 
751 	hvcsd->vdev = dev;
752 	dev_set_drvdata(&dev->dev, hvcsd);
753 
754 	hvcsd->index = index;
755 
756 	/* hvcsd->index = ++hvcs_struct_count; */
757 	hvcsd->chars_in_buffer = 0;
758 	hvcsd->todo_mask = 0;
759 	hvcsd->connected = 0;
760 
761 	/*
762 	 * This will populate the hvcs_struct's partner info fields for the
763 	 * first time.
764 	 */
765 	if (hvcs_get_pi(hvcsd)) {
766 		printk(KERN_ERR "HVCS: Failed to fetch partner"
767 			" info for vty-server@%X on device probe.\n",
768 			hvcsd->vdev->unit_address);
769 	}
770 
771 	/*
772 	 * If a user app opens a tty that corresponds to this vty-server before
773 	 * the hvcs_struct has been added to the devices list then the user app
774 	 * will get -ENODEV.
775 	 */
776 	spin_lock(&hvcs_structs_lock);
777 	list_add_tail(&(hvcsd->next), &hvcs_structs);
778 	spin_unlock(&hvcs_structs_lock);
779 
780 	retval = sysfs_create_group(&dev->dev.kobj, &hvcs_attr_group);
781 	if (retval) {
782 		printk(KERN_ERR "HVCS: Can't create sysfs attrs for vty-server@%X\n",
783 		       hvcsd->vdev->unit_address);
784 		return retval;
785 	}
786 
787 	printk(KERN_INFO "HVCS: vty-server@%X added to the vio bus.\n", dev->unit_address);
788 
789 	/*
790 	 * DON'T enable interrupts here because there is no user to receive the
791 	 * data.
792 	 */
793 	return 0;
794 }
795 
796 static void hvcs_remove(struct vio_dev *dev)
797 {
798 	struct hvcs_struct *hvcsd = dev_get_drvdata(&dev->dev);
799 	unsigned long flags;
800 	struct tty_struct *tty;
801 
802 	/* By this time the vty-server won't be getting any more interrupts */
803 
804 	spin_lock_irqsave(&hvcsd->lock, flags);
805 
806 	tty = hvcsd->port.tty;
807 
808 	spin_unlock_irqrestore(&hvcsd->lock, flags);
809 
810 	/*
811 	 * Let the last holder of this object cause it to be removed, which
812 	 * would probably be tty_hangup below.
813 	 */
814 	tty_port_put(&hvcsd->port);
815 
816 	/*
817 	 * The hangup is a scheduled function which will auto chain call
818 	 * hvcs_hangup.  The tty should always be valid at this time unless a
819 	 * simultaneous tty close already cleaned up the hvcs_struct.
820 	 */
821 	if (tty)
822 		tty_hangup(tty);
823 
824 	printk(KERN_INFO "HVCS: vty-server@%X removed from the"
825 			" vio bus.\n", dev->unit_address);
826 };
827 
828 static struct vio_driver hvcs_vio_driver = {
829 	.id_table	= hvcs_driver_table,
830 	.probe		= hvcs_probe,
831 	.remove		= hvcs_remove,
832 	.name		= hvcs_driver_name,
833 };
834 
835 /* Only called from hvcs_get_pi please */
836 static void hvcs_set_pi(struct hvcs_partner_info *pi, struct hvcs_struct *hvcsd)
837 {
838 	hvcsd->p_unit_address = pi->unit_address;
839 	hvcsd->p_partition_ID  = pi->partition_ID;
840 
841 	/* copy the null-term char too */
842 	strlcpy(hvcsd->p_location_code, pi->location_code,
843 		sizeof(hvcsd->p_location_code));
844 }
845 
846 /*
847  * Traverse the list and add the partner info that is found to the hvcs_struct
848  * struct entry. NOTE: At this time I know that partner info will return a
849  * single entry but in the future there may be multiple partner info entries per
850  * vty-server and you'll want to zero out that list and reset it.  If for some
851  * reason you have an old version of this driver but there IS more than one
852  * partner info then hvcsd->p_* will hold the last partner info data from the
853  * firmware query.  A good way to update this code would be to replace the three
854  * partner info fields in hvcs_struct with a list of hvcs_partner_info
855  * instances.
856  *
857  * This function must be called with the hvcsd->lock held.
858  */
859 static int hvcs_get_pi(struct hvcs_struct *hvcsd)
860 {
861 	struct hvcs_partner_info *pi;
862 	uint32_t unit_address = hvcsd->vdev->unit_address;
863 	struct list_head head;
864 	int retval;
865 
866 	spin_lock(&hvcs_pi_lock);
867 	if (!hvcs_pi_buff) {
868 		spin_unlock(&hvcs_pi_lock);
869 		return -EFAULT;
870 	}
871 	retval = hvcs_get_partner_info(unit_address, &head, hvcs_pi_buff);
872 	spin_unlock(&hvcs_pi_lock);
873 	if (retval) {
874 		printk(KERN_ERR "HVCS: Failed to fetch partner"
875 			" info for vty-server@%x.\n", unit_address);
876 		return retval;
877 	}
878 
879 	/* nixes the values if the partner vty went away */
880 	hvcsd->p_unit_address = 0;
881 	hvcsd->p_partition_ID = 0;
882 
883 	list_for_each_entry(pi, &head, node)
884 		hvcs_set_pi(pi, hvcsd);
885 
886 	hvcs_free_partner_info(&head);
887 	return 0;
888 }
889 
890 /*
891  * This function is executed by the driver "rescan" sysfs entry.  It shouldn't
892  * be executed elsewhere, in order to prevent deadlock issues.
893  */
894 static int hvcs_rescan_devices_list(void)
895 {
896 	struct hvcs_struct *hvcsd;
897 	unsigned long flags;
898 
899 	spin_lock(&hvcs_structs_lock);
900 
901 	list_for_each_entry(hvcsd, &hvcs_structs, next) {
902 		spin_lock_irqsave(&hvcsd->lock, flags);
903 		hvcs_get_pi(hvcsd);
904 		spin_unlock_irqrestore(&hvcsd->lock, flags);
905 	}
906 
907 	spin_unlock(&hvcs_structs_lock);
908 
909 	return 0;
910 }
911 
912 /*
913  * Farm this off into its own function because it could be more complex once
914  * multiple partners support is added. This function should be called with
915  * the hvcsd->lock held.
916  */
917 static int hvcs_has_pi(struct hvcs_struct *hvcsd)
918 {
919 	if ((!hvcsd->p_unit_address) || (!hvcsd->p_partition_ID))
920 		return 0;
921 	return 1;
922 }
923 
924 /*
925  * NOTE: It is possible that the super admin removed a partner vty and then
926  * added a different vty as the new partner.
927  *
928  * This function must be called with the hvcsd->lock held.
929  */
930 static int hvcs_partner_connect(struct hvcs_struct *hvcsd)
931 {
932 	int retval;
933 	unsigned int unit_address = hvcsd->vdev->unit_address;
934 
935 	/*
936 	 * If there wasn't any pi when the device was added it doesn't meant
937 	 * there isn't any now.  This driver isn't notified when a new partner
938 	 * vty is added to a vty-server so we discover changes on our own.
939 	 * Please see comments in hvcs_register_connection() for justification
940 	 * of this bizarre code.
941 	 */
942 	retval = hvcs_register_connection(unit_address,
943 			hvcsd->p_partition_ID,
944 			hvcsd->p_unit_address);
945 	if (!retval) {
946 		hvcsd->connected = 1;
947 		return 0;
948 	} else if (retval != -EINVAL)
949 		return retval;
950 
951 	/*
952 	 * As per the spec re-get the pi and try again if -EINVAL after the
953 	 * first connection attempt.
954 	 */
955 	if (hvcs_get_pi(hvcsd))
956 		return -ENOMEM;
957 
958 	if (!hvcs_has_pi(hvcsd))
959 		return -ENODEV;
960 
961 	retval = hvcs_register_connection(unit_address,
962 			hvcsd->p_partition_ID,
963 			hvcsd->p_unit_address);
964 	if (retval != -EINVAL) {
965 		hvcsd->connected = 1;
966 		return retval;
967 	}
968 
969 	/*
970 	 * EBUSY is the most likely scenario though the vty could have been
971 	 * removed or there really could be an hcall error due to the parameter
972 	 * data but thanks to ambiguous firmware return codes we can't really
973 	 * tell.
974 	 */
975 	printk(KERN_INFO "HVCS: vty-server or partner"
976 			" vty is busy.  Try again later.\n");
977 	return -EBUSY;
978 }
979 
980 /* This function must be called with the hvcsd->lock held */
981 static void hvcs_partner_free(struct hvcs_struct *hvcsd)
982 {
983 	int retval;
984 	do {
985 		retval = hvcs_free_connection(hvcsd->vdev->unit_address);
986 	} while (retval == -EBUSY);
987 	hvcsd->connected = 0;
988 }
989 
990 /* This helper function must be called WITHOUT the hvcsd->lock held */
991 static int hvcs_enable_device(struct hvcs_struct *hvcsd, uint32_t unit_address,
992 		unsigned int irq, struct vio_dev *vdev)
993 {
994 	unsigned long flags;
995 	int rc;
996 
997 	/*
998 	 * It is possible that the vty-server was removed between the time that
999 	 * the conn was registered and now.
1000 	 */
1001 	rc = request_irq(irq, &hvcs_handle_interrupt, 0, "ibmhvcs", hvcsd);
1002 	if (!rc) {
1003 		/*
1004 		 * It is possible the vty-server was removed after the irq was
1005 		 * requested but before we have time to enable interrupts.
1006 		 */
1007 		if (vio_enable_interrupts(vdev) == H_SUCCESS)
1008 			return 0;
1009 		else {
1010 			printk(KERN_ERR "HVCS: int enable failed for"
1011 					" vty-server@%X.\n", unit_address);
1012 			free_irq(irq, hvcsd);
1013 		}
1014 	} else
1015 		printk(KERN_ERR "HVCS: irq req failed for"
1016 				" vty-server@%X.\n", unit_address);
1017 
1018 	spin_lock_irqsave(&hvcsd->lock, flags);
1019 	hvcs_partner_free(hvcsd);
1020 	spin_unlock_irqrestore(&hvcsd->lock, flags);
1021 
1022 	return rc;
1023 
1024 }
1025 
1026 /*
1027  * This always increments the kref ref count if the call is successful.
1028  * Please remember to dec when you are done with the instance.
1029  *
1030  * NOTICE: Do NOT hold either the hvcs_struct.lock or hvcs_structs_lock when
1031  * calling this function or you will get deadlock.
1032  */
1033 static struct hvcs_struct *hvcs_get_by_index(int index)
1034 {
1035 	struct hvcs_struct *hvcsd;
1036 	unsigned long flags;
1037 
1038 	spin_lock(&hvcs_structs_lock);
1039 	list_for_each_entry(hvcsd, &hvcs_structs, next) {
1040 		spin_lock_irqsave(&hvcsd->lock, flags);
1041 		if (hvcsd->index == index) {
1042 			tty_port_get(&hvcsd->port);
1043 			spin_unlock_irqrestore(&hvcsd->lock, flags);
1044 			spin_unlock(&hvcs_structs_lock);
1045 			return hvcsd;
1046 		}
1047 		spin_unlock_irqrestore(&hvcsd->lock, flags);
1048 	}
1049 	spin_unlock(&hvcs_structs_lock);
1050 
1051 	return NULL;
1052 }
1053 
1054 static int hvcs_install(struct tty_driver *driver, struct tty_struct *tty)
1055 {
1056 	struct hvcs_struct *hvcsd;
1057 	struct vio_dev *vdev;
1058 	unsigned long unit_address, flags;
1059 	unsigned int irq;
1060 	int retval;
1061 
1062 	/*
1063 	 * Is there a vty-server that shares the same index?
1064 	 * This function increments the kref index.
1065 	 */
1066 	hvcsd = hvcs_get_by_index(tty->index);
1067 	if (!hvcsd) {
1068 		printk(KERN_WARNING "HVCS: open failed, no device associated"
1069 				" with tty->index %d.\n", tty->index);
1070 		return -ENODEV;
1071 	}
1072 
1073 	spin_lock_irqsave(&hvcsd->lock, flags);
1074 
1075 	if (hvcsd->connected == 0) {
1076 		retval = hvcs_partner_connect(hvcsd);
1077 		if (retval) {
1078 			spin_unlock_irqrestore(&hvcsd->lock, flags);
1079 			printk(KERN_WARNING "HVCS: partner connect failed.\n");
1080 			goto err_put;
1081 		}
1082 	}
1083 
1084 	hvcsd->port.count = 0;
1085 	hvcsd->port.tty = tty;
1086 	tty->driver_data = hvcsd;
1087 
1088 	memset(&hvcsd->buffer[0], 0x00, HVCS_BUFF_LEN);
1089 
1090 	/*
1091 	 * Save these in the spinlock for the enable operations that need them
1092 	 * outside of the spinlock.
1093 	 */
1094 	irq = hvcsd->vdev->irq;
1095 	vdev = hvcsd->vdev;
1096 	unit_address = hvcsd->vdev->unit_address;
1097 
1098 	hvcsd->todo_mask |= HVCS_SCHED_READ;
1099 	spin_unlock_irqrestore(&hvcsd->lock, flags);
1100 
1101 	/*
1102 	 * This must be done outside of the spinlock because it requests irqs
1103 	 * and will grab the spinlock and free the connection if it fails.
1104 	 */
1105 	retval = hvcs_enable_device(hvcsd, unit_address, irq, vdev);
1106 	if (retval) {
1107 		printk(KERN_WARNING "HVCS: enable device failed.\n");
1108 		goto err_put;
1109 	}
1110 
1111 	retval = tty_port_install(&hvcsd->port, driver, tty);
1112 	if (retval)
1113 		goto err_irq;
1114 
1115 	return 0;
1116 err_irq:
1117 	spin_lock_irqsave(&hvcsd->lock, flags);
1118 	vio_disable_interrupts(hvcsd->vdev);
1119 	spin_unlock_irqrestore(&hvcsd->lock, flags);
1120 	free_irq(irq, hvcsd);
1121 err_put:
1122 	tty_port_put(&hvcsd->port);
1123 
1124 	return retval;
1125 }
1126 
1127 /*
1128  * This is invoked via the tty_open interface when a user app connects to the
1129  * /dev node.
1130  */
1131 static int hvcs_open(struct tty_struct *tty, struct file *filp)
1132 {
1133 	struct hvcs_struct *hvcsd = tty->driver_data;
1134 	unsigned long flags;
1135 
1136 	spin_lock_irqsave(&hvcsd->lock, flags);
1137 	hvcsd->port.count++;
1138 	hvcsd->todo_mask |= HVCS_SCHED_READ;
1139 	spin_unlock_irqrestore(&hvcsd->lock, flags);
1140 
1141 	hvcs_kick();
1142 
1143 	printk(KERN_INFO "HVCS: vty-server@%X connection opened.\n",
1144 		hvcsd->vdev->unit_address );
1145 
1146 	return 0;
1147 }
1148 
1149 static void hvcs_close(struct tty_struct *tty, struct file *filp)
1150 {
1151 	struct hvcs_struct *hvcsd;
1152 	unsigned long flags;
1153 	int irq;
1154 
1155 	/*
1156 	 * Is someone trying to close the file associated with this device after
1157 	 * we have hung up?  If so tty->driver_data wouldn't be valid.
1158 	 */
1159 	if (tty_hung_up_p(filp))
1160 		return;
1161 
1162 	/*
1163 	 * No driver_data means that this close was probably issued after a
1164 	 * failed hvcs_open by the tty layer's release_dev() api and we can just
1165 	 * exit cleanly.
1166 	 */
1167 	if (!tty->driver_data)
1168 		return;
1169 
1170 	hvcsd = tty->driver_data;
1171 
1172 	spin_lock_irqsave(&hvcsd->lock, flags);
1173 	if (--hvcsd->port.count == 0) {
1174 
1175 		vio_disable_interrupts(hvcsd->vdev);
1176 
1177 		/*
1178 		 * NULL this early so that the kernel_thread doesn't try to
1179 		 * execute any operations on the TTY even though it is obligated
1180 		 * to deliver any pending I/O to the hypervisor.
1181 		 */
1182 		hvcsd->port.tty = NULL;
1183 
1184 		irq = hvcsd->vdev->irq;
1185 		spin_unlock_irqrestore(&hvcsd->lock, flags);
1186 
1187 		tty_wait_until_sent(tty, HVCS_CLOSE_WAIT);
1188 
1189 		free_irq(irq, hvcsd);
1190 		return;
1191 	} else if (hvcsd->port.count < 0) {
1192 		printk(KERN_ERR "HVCS: vty-server@%X open_count: %d is mismanaged.\n",
1193 		hvcsd->vdev->unit_address, hvcsd->port.count);
1194 	}
1195 
1196 	spin_unlock_irqrestore(&hvcsd->lock, flags);
1197 }
1198 
1199 static void hvcs_cleanup(struct tty_struct * tty)
1200 {
1201 	struct hvcs_struct *hvcsd = tty->driver_data;
1202 
1203 	/*
1204 	 * This line is important because it tells hvcs_open that this
1205 	 * device needs to be re-configured the next time hvcs_open is
1206 	 * called.
1207 	 */
1208 	tty->driver_data = NULL;
1209 
1210 	tty_port_put(&hvcsd->port);
1211 }
1212 
1213 static void hvcs_hangup(struct tty_struct * tty)
1214 {
1215 	struct hvcs_struct *hvcsd = tty->driver_data;
1216 	unsigned long flags;
1217 	int temp_open_count;
1218 	int irq;
1219 
1220 	spin_lock_irqsave(&hvcsd->lock, flags);
1221 	/* Preserve this so that we know how many kref refs to put */
1222 	temp_open_count = hvcsd->port.count;
1223 
1224 	/*
1225 	 * Don't kref put inside the spinlock because the destruction
1226 	 * callback may use the spinlock and it may get called before the
1227 	 * spinlock has been released.
1228 	 */
1229 	vio_disable_interrupts(hvcsd->vdev);
1230 
1231 	hvcsd->todo_mask = 0;
1232 
1233 	/* I don't think the tty needs the hvcs_struct pointer after a hangup */
1234 	tty->driver_data = NULL;
1235 	hvcsd->port.tty = NULL;
1236 
1237 	hvcsd->port.count = 0;
1238 
1239 	/* This will drop any buffered data on the floor which is OK in a hangup
1240 	 * scenario. */
1241 	memset(&hvcsd->buffer[0], 0x00, HVCS_BUFF_LEN);
1242 	hvcsd->chars_in_buffer = 0;
1243 
1244 	irq = hvcsd->vdev->irq;
1245 
1246 	spin_unlock_irqrestore(&hvcsd->lock, flags);
1247 
1248 	free_irq(irq, hvcsd);
1249 
1250 	/*
1251 	 * We need to kref_put() for every open_count we have since the
1252 	 * tty_hangup() function doesn't invoke a close per open connection on a
1253 	 * non-console device.
1254 	 */
1255 	while(temp_open_count) {
1256 		--temp_open_count;
1257 		/*
1258 		 * The final put will trigger destruction of the hvcs_struct.
1259 		 * NOTE:  If this hangup was signaled from user space then the
1260 		 * final put will never happen.
1261 		 */
1262 		tty_port_put(&hvcsd->port);
1263 	}
1264 }
1265 
1266 /*
1267  * NOTE: This is almost always from_user since user level apps interact with the
1268  * /dev nodes. I'm trusting that if hvcs_write gets called and interrupted by
1269  * hvcs_remove (which removes the target device and executes tty_hangup()) that
1270  * tty_hangup will allow hvcs_write time to complete execution before it
1271  * terminates our device.
1272  */
1273 static int hvcs_write(struct tty_struct *tty,
1274 		const unsigned char *buf, int count)
1275 {
1276 	struct hvcs_struct *hvcsd = tty->driver_data;
1277 	unsigned int unit_address;
1278 	const unsigned char *charbuf;
1279 	unsigned long flags;
1280 	int total_sent = 0;
1281 	int tosend = 0;
1282 	int result = 0;
1283 
1284 	/*
1285 	 * If they don't check the return code off of their open they may
1286 	 * attempt this even if there is no connected device.
1287 	 */
1288 	if (!hvcsd)
1289 		return -ENODEV;
1290 
1291 	/* Reasonable size to prevent user level flooding */
1292 	if (count > HVCS_MAX_FROM_USER) {
1293 		printk(KERN_WARNING "HVCS write: count being truncated to"
1294 				" HVCS_MAX_FROM_USER.\n");
1295 		count = HVCS_MAX_FROM_USER;
1296 	}
1297 
1298 	charbuf = buf;
1299 
1300 	spin_lock_irqsave(&hvcsd->lock, flags);
1301 
1302 	/*
1303 	 * Somehow an open succeeded but the device was removed or the
1304 	 * connection terminated between the vty-server and partner vty during
1305 	 * the middle of a write operation?  This is a crummy place to do this
1306 	 * but we want to keep it all in the spinlock.
1307 	 */
1308 	if (hvcsd->port.count <= 0) {
1309 		spin_unlock_irqrestore(&hvcsd->lock, flags);
1310 		return -ENODEV;
1311 	}
1312 
1313 	unit_address = hvcsd->vdev->unit_address;
1314 
1315 	while (count > 0) {
1316 		tosend = min(count, (HVCS_BUFF_LEN - hvcsd->chars_in_buffer));
1317 		/*
1318 		 * No more space, this probably means that the last call to
1319 		 * hvcs_write() didn't succeed and the buffer was filled up.
1320 		 */
1321 		if (!tosend)
1322 			break;
1323 
1324 		memcpy(&hvcsd->buffer[hvcsd->chars_in_buffer],
1325 				&charbuf[total_sent],
1326 				tosend);
1327 
1328 		hvcsd->chars_in_buffer += tosend;
1329 
1330 		result = 0;
1331 
1332 		/*
1333 		 * If this is true then we don't want to try writing to the
1334 		 * hypervisor because that is the kernel_threads job now.  We'll
1335 		 * just add to the buffer.
1336 		 */
1337 		if (!(hvcsd->todo_mask & HVCS_TRY_WRITE))
1338 			/* won't send partial writes */
1339 			result = hvc_put_chars(unit_address,
1340 					&hvcsd->buffer[0],
1341 					hvcsd->chars_in_buffer);
1342 
1343 		/*
1344 		 * Since we know we have enough room in hvcsd->buffer for
1345 		 * tosend we record that it was sent regardless of whether the
1346 		 * hypervisor actually took it because we have it buffered.
1347 		 */
1348 		total_sent+=tosend;
1349 		count-=tosend;
1350 		if (result == 0) {
1351 			hvcsd->todo_mask |= HVCS_TRY_WRITE;
1352 			hvcs_kick();
1353 			break;
1354 		}
1355 
1356 		hvcsd->chars_in_buffer = 0;
1357 		/*
1358 		 * Test after the chars_in_buffer reset otherwise this could
1359 		 * deadlock our writes if hvc_put_chars fails.
1360 		 */
1361 		if (result < 0)
1362 			break;
1363 	}
1364 
1365 	spin_unlock_irqrestore(&hvcsd->lock, flags);
1366 
1367 	if (result == -1)
1368 		return -EIO;
1369 	else
1370 		return total_sent;
1371 }
1372 
1373 /*
1374  * This is really asking how much can we guarantee that we can send or that we
1375  * absolutely WILL BUFFER if we can't send it.  This driver MUST honor the
1376  * return value, hence the reason for hvcs_struct buffering.
1377  */
1378 static unsigned int hvcs_write_room(struct tty_struct *tty)
1379 {
1380 	struct hvcs_struct *hvcsd = tty->driver_data;
1381 
1382 	if (!hvcsd || hvcsd->port.count <= 0)
1383 		return 0;
1384 
1385 	return HVCS_BUFF_LEN - hvcsd->chars_in_buffer;
1386 }
1387 
1388 static unsigned int hvcs_chars_in_buffer(struct tty_struct *tty)
1389 {
1390 	struct hvcs_struct *hvcsd = tty->driver_data;
1391 
1392 	return hvcsd->chars_in_buffer;
1393 }
1394 
1395 static const struct tty_operations hvcs_ops = {
1396 	.install = hvcs_install,
1397 	.open = hvcs_open,
1398 	.close = hvcs_close,
1399 	.cleanup = hvcs_cleanup,
1400 	.hangup = hvcs_hangup,
1401 	.write = hvcs_write,
1402 	.write_room = hvcs_write_room,
1403 	.chars_in_buffer = hvcs_chars_in_buffer,
1404 	.unthrottle = hvcs_unthrottle,
1405 	.throttle = hvcs_throttle,
1406 };
1407 
1408 static int hvcs_alloc_index_list(int n)
1409 {
1410 	int i;
1411 
1412 	hvcs_index_list = kmalloc_array(n, sizeof(hvcs_index_count),
1413 					GFP_KERNEL);
1414 	if (!hvcs_index_list)
1415 		return -ENOMEM;
1416 	hvcs_index_count = n;
1417 	for (i = 0; i < hvcs_index_count; i++)
1418 		hvcs_index_list[i] = -1;
1419 	return 0;
1420 }
1421 
1422 static void hvcs_free_index_list(void)
1423 {
1424 	/* Paranoia check to be thorough. */
1425 	kfree(hvcs_index_list);
1426 	hvcs_index_list = NULL;
1427 	hvcs_index_count = 0;
1428 }
1429 
1430 static int hvcs_initialize(void)
1431 {
1432 	int rc, num_ttys_to_alloc;
1433 
1434 	mutex_lock(&hvcs_init_mutex);
1435 	if (hvcs_task) {
1436 		mutex_unlock(&hvcs_init_mutex);
1437 		return 0;
1438 	}
1439 
1440 	/* Has the user specified an overload with an insmod param? */
1441 	if (hvcs_parm_num_devs <= 0 ||
1442 		(hvcs_parm_num_devs > HVCS_MAX_SERVER_ADAPTERS)) {
1443 		num_ttys_to_alloc = HVCS_DEFAULT_SERVER_ADAPTERS;
1444 	} else
1445 		num_ttys_to_alloc = hvcs_parm_num_devs;
1446 
1447 	hvcs_tty_driver = tty_alloc_driver(num_ttys_to_alloc,
1448 			TTY_DRIVER_REAL_RAW);
1449 	if (IS_ERR(hvcs_tty_driver)) {
1450 		mutex_unlock(&hvcs_init_mutex);
1451 		return PTR_ERR(hvcs_tty_driver);
1452 	}
1453 
1454 	if (hvcs_alloc_index_list(num_ttys_to_alloc)) {
1455 		rc = -ENOMEM;
1456 		goto index_fail;
1457 	}
1458 
1459 	hvcs_tty_driver->driver_name = hvcs_driver_name;
1460 	hvcs_tty_driver->name = hvcs_device_node;
1461 
1462 	/*
1463 	 * We'll let the system assign us a major number, indicated by leaving
1464 	 * it blank.
1465 	 */
1466 
1467 	hvcs_tty_driver->minor_start = HVCS_MINOR_START;
1468 	hvcs_tty_driver->type = TTY_DRIVER_TYPE_SYSTEM;
1469 
1470 	/*
1471 	 * We role our own so that we DONT ECHO.  We can't echo because the
1472 	 * device we are connecting to already echoes by default and this would
1473 	 * throw us into a horrible recursive echo-echo-echo loop.
1474 	 */
1475 	hvcs_tty_driver->init_termios = hvcs_tty_termios;
1476 
1477 	tty_set_operations(hvcs_tty_driver, &hvcs_ops);
1478 
1479 	/*
1480 	 * The following call will result in sysfs entries that denote the
1481 	 * dynamically assigned major and minor numbers for our devices.
1482 	 */
1483 	if (tty_register_driver(hvcs_tty_driver)) {
1484 		printk(KERN_ERR "HVCS: registration as a tty driver failed.\n");
1485 		rc = -EIO;
1486 		goto register_fail;
1487 	}
1488 
1489 	hvcs_pi_buff = (unsigned long *) __get_free_page(GFP_KERNEL);
1490 	if (!hvcs_pi_buff) {
1491 		rc = -ENOMEM;
1492 		goto buff_alloc_fail;
1493 	}
1494 
1495 	hvcs_task = kthread_run(khvcsd, NULL, "khvcsd");
1496 	if (IS_ERR(hvcs_task)) {
1497 		printk(KERN_ERR "HVCS: khvcsd creation failed.\n");
1498 		rc = -EIO;
1499 		goto kthread_fail;
1500 	}
1501 	mutex_unlock(&hvcs_init_mutex);
1502 	return 0;
1503 
1504 kthread_fail:
1505 	free_page((unsigned long)hvcs_pi_buff);
1506 buff_alloc_fail:
1507 	tty_unregister_driver(hvcs_tty_driver);
1508 register_fail:
1509 	hvcs_free_index_list();
1510 index_fail:
1511 	tty_driver_kref_put(hvcs_tty_driver);
1512 	hvcs_tty_driver = NULL;
1513 	mutex_unlock(&hvcs_init_mutex);
1514 	return rc;
1515 }
1516 
1517 static int __init hvcs_module_init(void)
1518 {
1519 	int rc = vio_register_driver(&hvcs_vio_driver);
1520 	if (rc) {
1521 		printk(KERN_ERR "HVCS: can't register vio driver\n");
1522 		return rc;
1523 	}
1524 
1525 	pr_info("HVCS: Driver registered.\n");
1526 
1527 	/* This needs to be done AFTER the vio_register_driver() call or else
1528 	 * the kobjects won't be initialized properly.
1529 	 */
1530 	rc = driver_create_file(&(hvcs_vio_driver.driver), &driver_attr_rescan);
1531 	if (rc)
1532 		pr_warn("HVCS: Failed to create rescan file (err %d)\n", rc);
1533 
1534 	return 0;
1535 }
1536 
1537 static void __exit hvcs_module_exit(void)
1538 {
1539 	/*
1540 	 * This driver receives hvcs_remove callbacks for each device upon
1541 	 * module removal.
1542 	 */
1543 	vio_unregister_driver(&hvcs_vio_driver);
1544 	if (!hvcs_task)
1545 		return;
1546 
1547 	/*
1548 	 * This synchronous operation  will wake the khvcsd kthread if it is
1549 	 * asleep and will return when khvcsd has terminated.
1550 	 */
1551 	kthread_stop(hvcs_task);
1552 
1553 	spin_lock(&hvcs_pi_lock);
1554 	free_page((unsigned long)hvcs_pi_buff);
1555 	hvcs_pi_buff = NULL;
1556 	spin_unlock(&hvcs_pi_lock);
1557 
1558 	driver_remove_file(&hvcs_vio_driver.driver, &driver_attr_rescan);
1559 
1560 	tty_unregister_driver(hvcs_tty_driver);
1561 
1562 	hvcs_free_index_list();
1563 
1564 	tty_driver_kref_put(hvcs_tty_driver);
1565 
1566 	printk(KERN_INFO "HVCS: driver module removed.\n");
1567 }
1568 
1569 module_init(hvcs_module_init);
1570 module_exit(hvcs_module_exit);
1571