xref: /linux/drivers/char/virtio_console.c (revision d229807f669ba3dea9f64467ee965051c4366aed)
1 /*
2  * Copyright (C) 2006, 2007, 2009 Rusty Russell, IBM Corporation
3  * Copyright (C) 2009, 2010, 2011 Red Hat, Inc.
4  * Copyright (C) 2009, 2010, 2011 Amit Shah <amit.shah@redhat.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20 #include <linux/cdev.h>
21 #include <linux/debugfs.h>
22 #include <linux/device.h>
23 #include <linux/err.h>
24 #include <linux/fs.h>
25 #include <linux/init.h>
26 #include <linux/list.h>
27 #include <linux/poll.h>
28 #include <linux/sched.h>
29 #include <linux/slab.h>
30 #include <linux/spinlock.h>
31 #include <linux/virtio.h>
32 #include <linux/virtio_console.h>
33 #include <linux/wait.h>
34 #include <linux/workqueue.h>
35 #include <linux/module.h>
36 #include "../tty/hvc/hvc_console.h"
37 
38 /*
39  * This is a global struct for storing common data for all the devices
40  * this driver handles.
41  *
42  * Mainly, it has a linked list for all the consoles in one place so
43  * that callbacks from hvc for get_chars(), put_chars() work properly
44  * across multiple devices and multiple ports per device.
45  */
46 struct ports_driver_data {
47 	/* Used for registering chardevs */
48 	struct class *class;
49 
50 	/* Used for exporting per-port information to debugfs */
51 	struct dentry *debugfs_dir;
52 
53 	/* List of all the devices we're handling */
54 	struct list_head portdevs;
55 
56 	/* Number of devices this driver is handling */
57 	unsigned int index;
58 
59 	/*
60 	 * This is used to keep track of the number of hvc consoles
61 	 * spawned by this driver.  This number is given as the first
62 	 * argument to hvc_alloc().  To correctly map an initial
63 	 * console spawned via hvc_instantiate to the console being
64 	 * hooked up via hvc_alloc, we need to pass the same vtermno.
65 	 *
66 	 * We also just assume the first console being initialised was
67 	 * the first one that got used as the initial console.
68 	 */
69 	unsigned int next_vtermno;
70 
71 	/* All the console devices handled by this driver */
72 	struct list_head consoles;
73 };
74 static struct ports_driver_data pdrvdata;
75 
76 DEFINE_SPINLOCK(pdrvdata_lock);
77 
78 /* This struct holds information that's relevant only for console ports */
79 struct console {
80 	/* We'll place all consoles in a list in the pdrvdata struct */
81 	struct list_head list;
82 
83 	/* The hvc device associated with this console port */
84 	struct hvc_struct *hvc;
85 
86 	/* The size of the console */
87 	struct winsize ws;
88 
89 	/*
90 	 * This number identifies the number that we used to register
91 	 * with hvc in hvc_instantiate() and hvc_alloc(); this is the
92 	 * number passed on by the hvc callbacks to us to
93 	 * differentiate between the other console ports handled by
94 	 * this driver
95 	 */
96 	u32 vtermno;
97 };
98 
99 struct port_buffer {
100 	char *buf;
101 
102 	/* size of the buffer in *buf above */
103 	size_t size;
104 
105 	/* used length of the buffer */
106 	size_t len;
107 	/* offset in the buf from which to consume data */
108 	size_t offset;
109 };
110 
111 /*
112  * This is a per-device struct that stores data common to all the
113  * ports for that device (vdev->priv).
114  */
115 struct ports_device {
116 	/* Next portdev in the list, head is in the pdrvdata struct */
117 	struct list_head list;
118 
119 	/*
120 	 * Workqueue handlers where we process deferred work after
121 	 * notification
122 	 */
123 	struct work_struct control_work;
124 
125 	struct list_head ports;
126 
127 	/* To protect the list of ports */
128 	spinlock_t ports_lock;
129 
130 	/* To protect the vq operations for the control channel */
131 	spinlock_t cvq_lock;
132 
133 	/* The current config space is stored here */
134 	struct virtio_console_config config;
135 
136 	/* The virtio device we're associated with */
137 	struct virtio_device *vdev;
138 
139 	/*
140 	 * A couple of virtqueues for the control channel: one for
141 	 * guest->host transfers, one for host->guest transfers
142 	 */
143 	struct virtqueue *c_ivq, *c_ovq;
144 
145 	/* Array of per-port IO virtqueues */
146 	struct virtqueue **in_vqs, **out_vqs;
147 
148 	/* Used for numbering devices for sysfs and debugfs */
149 	unsigned int drv_index;
150 
151 	/* Major number for this device.  Ports will be created as minors. */
152 	int chr_major;
153 };
154 
155 /* This struct holds the per-port data */
156 struct port {
157 	/* Next port in the list, head is in the ports_device */
158 	struct list_head list;
159 
160 	/* Pointer to the parent virtio_console device */
161 	struct ports_device *portdev;
162 
163 	/* The current buffer from which data has to be fed to readers */
164 	struct port_buffer *inbuf;
165 
166 	/*
167 	 * To protect the operations on the in_vq associated with this
168 	 * port.  Has to be a spinlock because it can be called from
169 	 * interrupt context (get_char()).
170 	 */
171 	spinlock_t inbuf_lock;
172 
173 	/* Protect the operations on the out_vq. */
174 	spinlock_t outvq_lock;
175 
176 	/* The IO vqs for this port */
177 	struct virtqueue *in_vq, *out_vq;
178 
179 	/* File in the debugfs directory that exposes this port's information */
180 	struct dentry *debugfs_file;
181 
182 	/*
183 	 * The entries in this struct will be valid if this port is
184 	 * hooked up to an hvc console
185 	 */
186 	struct console cons;
187 
188 	/* Each port associates with a separate char device */
189 	struct cdev *cdev;
190 	struct device *dev;
191 
192 	/* Reference-counting to handle port hot-unplugs and file operations */
193 	struct kref kref;
194 
195 	/* A waitqueue for poll() or blocking read operations */
196 	wait_queue_head_t waitqueue;
197 
198 	/* The 'name' of the port that we expose via sysfs properties */
199 	char *name;
200 
201 	/* We can notify apps of host connect / disconnect events via SIGIO */
202 	struct fasync_struct *async_queue;
203 
204 	/* The 'id' to identify the port with the Host */
205 	u32 id;
206 
207 	bool outvq_full;
208 
209 	/* Is the host device open */
210 	bool host_connected;
211 
212 	/* We should allow only one process to open a port */
213 	bool guest_connected;
214 };
215 
216 /* This is the very early arch-specified put chars function. */
217 static int (*early_put_chars)(u32, const char *, int);
218 
219 static struct port *find_port_by_vtermno(u32 vtermno)
220 {
221 	struct port *port;
222 	struct console *cons;
223 	unsigned long flags;
224 
225 	spin_lock_irqsave(&pdrvdata_lock, flags);
226 	list_for_each_entry(cons, &pdrvdata.consoles, list) {
227 		if (cons->vtermno == vtermno) {
228 			port = container_of(cons, struct port, cons);
229 			goto out;
230 		}
231 	}
232 	port = NULL;
233 out:
234 	spin_unlock_irqrestore(&pdrvdata_lock, flags);
235 	return port;
236 }
237 
238 static struct port *find_port_by_devt_in_portdev(struct ports_device *portdev,
239 						 dev_t dev)
240 {
241 	struct port *port;
242 	unsigned long flags;
243 
244 	spin_lock_irqsave(&portdev->ports_lock, flags);
245 	list_for_each_entry(port, &portdev->ports, list)
246 		if (port->cdev->dev == dev)
247 			goto out;
248 	port = NULL;
249 out:
250 	spin_unlock_irqrestore(&portdev->ports_lock, flags);
251 
252 	return port;
253 }
254 
255 static struct port *find_port_by_devt(dev_t dev)
256 {
257 	struct ports_device *portdev;
258 	struct port *port;
259 	unsigned long flags;
260 
261 	spin_lock_irqsave(&pdrvdata_lock, flags);
262 	list_for_each_entry(portdev, &pdrvdata.portdevs, list) {
263 		port = find_port_by_devt_in_portdev(portdev, dev);
264 		if (port)
265 			goto out;
266 	}
267 	port = NULL;
268 out:
269 	spin_unlock_irqrestore(&pdrvdata_lock, flags);
270 	return port;
271 }
272 
273 static struct port *find_port_by_id(struct ports_device *portdev, u32 id)
274 {
275 	struct port *port;
276 	unsigned long flags;
277 
278 	spin_lock_irqsave(&portdev->ports_lock, flags);
279 	list_for_each_entry(port, &portdev->ports, list)
280 		if (port->id == id)
281 			goto out;
282 	port = NULL;
283 out:
284 	spin_unlock_irqrestore(&portdev->ports_lock, flags);
285 
286 	return port;
287 }
288 
289 static struct port *find_port_by_vq(struct ports_device *portdev,
290 				    struct virtqueue *vq)
291 {
292 	struct port *port;
293 	unsigned long flags;
294 
295 	spin_lock_irqsave(&portdev->ports_lock, flags);
296 	list_for_each_entry(port, &portdev->ports, list)
297 		if (port->in_vq == vq || port->out_vq == vq)
298 			goto out;
299 	port = NULL;
300 out:
301 	spin_unlock_irqrestore(&portdev->ports_lock, flags);
302 	return port;
303 }
304 
305 static bool is_console_port(struct port *port)
306 {
307 	if (port->cons.hvc)
308 		return true;
309 	return false;
310 }
311 
312 static inline bool use_multiport(struct ports_device *portdev)
313 {
314 	/*
315 	 * This condition can be true when put_chars is called from
316 	 * early_init
317 	 */
318 	if (!portdev->vdev)
319 		return 0;
320 	return portdev->vdev->features[0] & (1 << VIRTIO_CONSOLE_F_MULTIPORT);
321 }
322 
323 static void free_buf(struct port_buffer *buf)
324 {
325 	kfree(buf->buf);
326 	kfree(buf);
327 }
328 
329 static struct port_buffer *alloc_buf(size_t buf_size)
330 {
331 	struct port_buffer *buf;
332 
333 	buf = kmalloc(sizeof(*buf), GFP_KERNEL);
334 	if (!buf)
335 		goto fail;
336 	buf->buf = kzalloc(buf_size, GFP_KERNEL);
337 	if (!buf->buf)
338 		goto free_buf;
339 	buf->len = 0;
340 	buf->offset = 0;
341 	buf->size = buf_size;
342 	return buf;
343 
344 free_buf:
345 	kfree(buf);
346 fail:
347 	return NULL;
348 }
349 
350 /* Callers should take appropriate locks */
351 static void *get_inbuf(struct port *port)
352 {
353 	struct port_buffer *buf;
354 	struct virtqueue *vq;
355 	unsigned int len;
356 
357 	vq = port->in_vq;
358 	buf = virtqueue_get_buf(vq, &len);
359 	if (buf) {
360 		buf->len = len;
361 		buf->offset = 0;
362 	}
363 	return buf;
364 }
365 
366 /*
367  * Create a scatter-gather list representing our input buffer and put
368  * it in the queue.
369  *
370  * Callers should take appropriate locks.
371  */
372 static int add_inbuf(struct virtqueue *vq, struct port_buffer *buf)
373 {
374 	struct scatterlist sg[1];
375 	int ret;
376 
377 	sg_init_one(sg, buf->buf, buf->size);
378 
379 	ret = virtqueue_add_buf(vq, sg, 0, 1, buf);
380 	virtqueue_kick(vq);
381 	return ret;
382 }
383 
384 /* Discard any unread data this port has. Callers lockers. */
385 static void discard_port_data(struct port *port)
386 {
387 	struct port_buffer *buf;
388 	struct virtqueue *vq;
389 	unsigned int len;
390 	int ret;
391 
392 	if (!port->portdev) {
393 		/* Device has been unplugged.  vqs are already gone. */
394 		return;
395 	}
396 	vq = port->in_vq;
397 	if (port->inbuf)
398 		buf = port->inbuf;
399 	else
400 		buf = virtqueue_get_buf(vq, &len);
401 
402 	ret = 0;
403 	while (buf) {
404 		if (add_inbuf(vq, buf) < 0) {
405 			ret++;
406 			free_buf(buf);
407 		}
408 		buf = virtqueue_get_buf(vq, &len);
409 	}
410 	port->inbuf = NULL;
411 	if (ret)
412 		dev_warn(port->dev, "Errors adding %d buffers back to vq\n",
413 			 ret);
414 }
415 
416 static bool port_has_data(struct port *port)
417 {
418 	unsigned long flags;
419 	bool ret;
420 
421 	spin_lock_irqsave(&port->inbuf_lock, flags);
422 	if (port->inbuf) {
423 		ret = true;
424 		goto out;
425 	}
426 	port->inbuf = get_inbuf(port);
427 	if (port->inbuf) {
428 		ret = true;
429 		goto out;
430 	}
431 	ret = false;
432 out:
433 	spin_unlock_irqrestore(&port->inbuf_lock, flags);
434 	return ret;
435 }
436 
437 static ssize_t __send_control_msg(struct ports_device *portdev, u32 port_id,
438 				  unsigned int event, unsigned int value)
439 {
440 	struct scatterlist sg[1];
441 	struct virtio_console_control cpkt;
442 	struct virtqueue *vq;
443 	unsigned int len;
444 
445 	if (!use_multiport(portdev))
446 		return 0;
447 
448 	cpkt.id = port_id;
449 	cpkt.event = event;
450 	cpkt.value = value;
451 
452 	vq = portdev->c_ovq;
453 
454 	sg_init_one(sg, &cpkt, sizeof(cpkt));
455 	if (virtqueue_add_buf(vq, sg, 1, 0, &cpkt) >= 0) {
456 		virtqueue_kick(vq);
457 		while (!virtqueue_get_buf(vq, &len))
458 			cpu_relax();
459 	}
460 	return 0;
461 }
462 
463 static ssize_t send_control_msg(struct port *port, unsigned int event,
464 				unsigned int value)
465 {
466 	/* Did the port get unplugged before userspace closed it? */
467 	if (port->portdev)
468 		return __send_control_msg(port->portdev, port->id, event, value);
469 	return 0;
470 }
471 
472 /* Callers must take the port->outvq_lock */
473 static void reclaim_consumed_buffers(struct port *port)
474 {
475 	void *buf;
476 	unsigned int len;
477 
478 	if (!port->portdev) {
479 		/* Device has been unplugged.  vqs are already gone. */
480 		return;
481 	}
482 	while ((buf = virtqueue_get_buf(port->out_vq, &len))) {
483 		kfree(buf);
484 		port->outvq_full = false;
485 	}
486 }
487 
488 static ssize_t send_buf(struct port *port, void *in_buf, size_t in_count,
489 			bool nonblock)
490 {
491 	struct scatterlist sg[1];
492 	struct virtqueue *out_vq;
493 	ssize_t ret;
494 	unsigned long flags;
495 	unsigned int len;
496 
497 	out_vq = port->out_vq;
498 
499 	spin_lock_irqsave(&port->outvq_lock, flags);
500 
501 	reclaim_consumed_buffers(port);
502 
503 	sg_init_one(sg, in_buf, in_count);
504 	ret = virtqueue_add_buf(out_vq, sg, 1, 0, in_buf);
505 
506 	/* Tell Host to go! */
507 	virtqueue_kick(out_vq);
508 
509 	if (ret < 0) {
510 		in_count = 0;
511 		goto done;
512 	}
513 
514 	if (ret == 0)
515 		port->outvq_full = true;
516 
517 	if (nonblock)
518 		goto done;
519 
520 	/*
521 	 * Wait till the host acknowledges it pushed out the data we
522 	 * sent.  This is done for data from the hvc_console; the tty
523 	 * operations are performed with spinlocks held so we can't
524 	 * sleep here.  An alternative would be to copy the data to a
525 	 * buffer and relax the spinning requirement.  The downside is
526 	 * we need to kmalloc a GFP_ATOMIC buffer each time the
527 	 * console driver writes something out.
528 	 */
529 	while (!virtqueue_get_buf(out_vq, &len))
530 		cpu_relax();
531 done:
532 	spin_unlock_irqrestore(&port->outvq_lock, flags);
533 	/*
534 	 * We're expected to return the amount of data we wrote -- all
535 	 * of it
536 	 */
537 	return in_count;
538 }
539 
540 /*
541  * Give out the data that's requested from the buffer that we have
542  * queued up.
543  */
544 static ssize_t fill_readbuf(struct port *port, char *out_buf, size_t out_count,
545 			    bool to_user)
546 {
547 	struct port_buffer *buf;
548 	unsigned long flags;
549 
550 	if (!out_count || !port_has_data(port))
551 		return 0;
552 
553 	buf = port->inbuf;
554 	out_count = min(out_count, buf->len - buf->offset);
555 
556 	if (to_user) {
557 		ssize_t ret;
558 
559 		ret = copy_to_user(out_buf, buf->buf + buf->offset, out_count);
560 		if (ret)
561 			return -EFAULT;
562 	} else {
563 		memcpy(out_buf, buf->buf + buf->offset, out_count);
564 	}
565 
566 	buf->offset += out_count;
567 
568 	if (buf->offset == buf->len) {
569 		/*
570 		 * We're done using all the data in this buffer.
571 		 * Re-queue so that the Host can send us more data.
572 		 */
573 		spin_lock_irqsave(&port->inbuf_lock, flags);
574 		port->inbuf = NULL;
575 
576 		if (add_inbuf(port->in_vq, buf) < 0)
577 			dev_warn(port->dev, "failed add_buf\n");
578 
579 		spin_unlock_irqrestore(&port->inbuf_lock, flags);
580 	}
581 	/* Return the number of bytes actually copied */
582 	return out_count;
583 }
584 
585 /* The condition that must be true for polling to end */
586 static bool will_read_block(struct port *port)
587 {
588 	if (!port->guest_connected) {
589 		/* Port got hot-unplugged. Let's exit. */
590 		return false;
591 	}
592 	return !port_has_data(port) && port->host_connected;
593 }
594 
595 static bool will_write_block(struct port *port)
596 {
597 	bool ret;
598 
599 	if (!port->guest_connected) {
600 		/* Port got hot-unplugged. Let's exit. */
601 		return false;
602 	}
603 	if (!port->host_connected)
604 		return true;
605 
606 	spin_lock_irq(&port->outvq_lock);
607 	/*
608 	 * Check if the Host has consumed any buffers since we last
609 	 * sent data (this is only applicable for nonblocking ports).
610 	 */
611 	reclaim_consumed_buffers(port);
612 	ret = port->outvq_full;
613 	spin_unlock_irq(&port->outvq_lock);
614 
615 	return ret;
616 }
617 
618 static ssize_t port_fops_read(struct file *filp, char __user *ubuf,
619 			      size_t count, loff_t *offp)
620 {
621 	struct port *port;
622 	ssize_t ret;
623 
624 	port = filp->private_data;
625 
626 	if (!port_has_data(port)) {
627 		/*
628 		 * If nothing's connected on the host just return 0 in
629 		 * case of list_empty; this tells the userspace app
630 		 * that there's no connection
631 		 */
632 		if (!port->host_connected)
633 			return 0;
634 		if (filp->f_flags & O_NONBLOCK)
635 			return -EAGAIN;
636 
637 		ret = wait_event_interruptible(port->waitqueue,
638 					       !will_read_block(port));
639 		if (ret < 0)
640 			return ret;
641 	}
642 	/* Port got hot-unplugged. */
643 	if (!port->guest_connected)
644 		return -ENODEV;
645 	/*
646 	 * We could've received a disconnection message while we were
647 	 * waiting for more data.
648 	 *
649 	 * This check is not clubbed in the if() statement above as we
650 	 * might receive some data as well as the host could get
651 	 * disconnected after we got woken up from our wait.  So we
652 	 * really want to give off whatever data we have and only then
653 	 * check for host_connected.
654 	 */
655 	if (!port_has_data(port) && !port->host_connected)
656 		return 0;
657 
658 	return fill_readbuf(port, ubuf, count, true);
659 }
660 
661 static ssize_t port_fops_write(struct file *filp, const char __user *ubuf,
662 			       size_t count, loff_t *offp)
663 {
664 	struct port *port;
665 	char *buf;
666 	ssize_t ret;
667 	bool nonblock;
668 
669 	/* Userspace could be out to fool us */
670 	if (!count)
671 		return 0;
672 
673 	port = filp->private_data;
674 
675 	nonblock = filp->f_flags & O_NONBLOCK;
676 
677 	if (will_write_block(port)) {
678 		if (nonblock)
679 			return -EAGAIN;
680 
681 		ret = wait_event_interruptible(port->waitqueue,
682 					       !will_write_block(port));
683 		if (ret < 0)
684 			return ret;
685 	}
686 	/* Port got hot-unplugged. */
687 	if (!port->guest_connected)
688 		return -ENODEV;
689 
690 	count = min((size_t)(32 * 1024), count);
691 
692 	buf = kmalloc(count, GFP_KERNEL);
693 	if (!buf)
694 		return -ENOMEM;
695 
696 	ret = copy_from_user(buf, ubuf, count);
697 	if (ret) {
698 		ret = -EFAULT;
699 		goto free_buf;
700 	}
701 
702 	/*
703 	 * We now ask send_buf() to not spin for generic ports -- we
704 	 * can re-use the same code path that non-blocking file
705 	 * descriptors take for blocking file descriptors since the
706 	 * wait is already done and we're certain the write will go
707 	 * through to the host.
708 	 */
709 	nonblock = true;
710 	ret = send_buf(port, buf, count, nonblock);
711 
712 	if (nonblock && ret > 0)
713 		goto out;
714 
715 free_buf:
716 	kfree(buf);
717 out:
718 	return ret;
719 }
720 
721 static unsigned int port_fops_poll(struct file *filp, poll_table *wait)
722 {
723 	struct port *port;
724 	unsigned int ret;
725 
726 	port = filp->private_data;
727 	poll_wait(filp, &port->waitqueue, wait);
728 
729 	if (!port->guest_connected) {
730 		/* Port got unplugged */
731 		return POLLHUP;
732 	}
733 	ret = 0;
734 	if (!will_read_block(port))
735 		ret |= POLLIN | POLLRDNORM;
736 	if (!will_write_block(port))
737 		ret |= POLLOUT;
738 	if (!port->host_connected)
739 		ret |= POLLHUP;
740 
741 	return ret;
742 }
743 
744 static void remove_port(struct kref *kref);
745 
746 static int port_fops_release(struct inode *inode, struct file *filp)
747 {
748 	struct port *port;
749 
750 	port = filp->private_data;
751 
752 	/* Notify host of port being closed */
753 	send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
754 
755 	spin_lock_irq(&port->inbuf_lock);
756 	port->guest_connected = false;
757 
758 	discard_port_data(port);
759 
760 	spin_unlock_irq(&port->inbuf_lock);
761 
762 	spin_lock_irq(&port->outvq_lock);
763 	reclaim_consumed_buffers(port);
764 	spin_unlock_irq(&port->outvq_lock);
765 
766 	/*
767 	 * Locks aren't necessary here as a port can't be opened after
768 	 * unplug, and if a port isn't unplugged, a kref would already
769 	 * exist for the port.  Plus, taking ports_lock here would
770 	 * create a dependency on other locks taken by functions
771 	 * inside remove_port if we're the last holder of the port,
772 	 * creating many problems.
773 	 */
774 	kref_put(&port->kref, remove_port);
775 
776 	return 0;
777 }
778 
779 static int port_fops_open(struct inode *inode, struct file *filp)
780 {
781 	struct cdev *cdev = inode->i_cdev;
782 	struct port *port;
783 	int ret;
784 
785 	port = find_port_by_devt(cdev->dev);
786 	filp->private_data = port;
787 
788 	/* Prevent against a port getting hot-unplugged at the same time */
789 	spin_lock_irq(&port->portdev->ports_lock);
790 	kref_get(&port->kref);
791 	spin_unlock_irq(&port->portdev->ports_lock);
792 
793 	/*
794 	 * Don't allow opening of console port devices -- that's done
795 	 * via /dev/hvc
796 	 */
797 	if (is_console_port(port)) {
798 		ret = -ENXIO;
799 		goto out;
800 	}
801 
802 	/* Allow only one process to open a particular port at a time */
803 	spin_lock_irq(&port->inbuf_lock);
804 	if (port->guest_connected) {
805 		spin_unlock_irq(&port->inbuf_lock);
806 		ret = -EMFILE;
807 		goto out;
808 	}
809 
810 	port->guest_connected = true;
811 	spin_unlock_irq(&port->inbuf_lock);
812 
813 	spin_lock_irq(&port->outvq_lock);
814 	/*
815 	 * There might be a chance that we missed reclaiming a few
816 	 * buffers in the window of the port getting previously closed
817 	 * and opening now.
818 	 */
819 	reclaim_consumed_buffers(port);
820 	spin_unlock_irq(&port->outvq_lock);
821 
822 	nonseekable_open(inode, filp);
823 
824 	/* Notify host of port being opened */
825 	send_control_msg(filp->private_data, VIRTIO_CONSOLE_PORT_OPEN, 1);
826 
827 	return 0;
828 out:
829 	kref_put(&port->kref, remove_port);
830 	return ret;
831 }
832 
833 static int port_fops_fasync(int fd, struct file *filp, int mode)
834 {
835 	struct port *port;
836 
837 	port = filp->private_data;
838 	return fasync_helper(fd, filp, mode, &port->async_queue);
839 }
840 
841 /*
842  * The file operations that we support: programs in the guest can open
843  * a console device, read from it, write to it, poll for data and
844  * close it.  The devices are at
845  *   /dev/vport<device number>p<port number>
846  */
847 static const struct file_operations port_fops = {
848 	.owner = THIS_MODULE,
849 	.open  = port_fops_open,
850 	.read  = port_fops_read,
851 	.write = port_fops_write,
852 	.poll  = port_fops_poll,
853 	.release = port_fops_release,
854 	.fasync = port_fops_fasync,
855 	.llseek = no_llseek,
856 };
857 
858 /*
859  * The put_chars() callback is pretty straightforward.
860  *
861  * We turn the characters into a scatter-gather list, add it to the
862  * output queue and then kick the Host.  Then we sit here waiting for
863  * it to finish: inefficient in theory, but in practice
864  * implementations will do it immediately (lguest's Launcher does).
865  */
866 static int put_chars(u32 vtermno, const char *buf, int count)
867 {
868 	struct port *port;
869 
870 	if (unlikely(early_put_chars))
871 		return early_put_chars(vtermno, buf, count);
872 
873 	port = find_port_by_vtermno(vtermno);
874 	if (!port)
875 		return -EPIPE;
876 
877 	return send_buf(port, (void *)buf, count, false);
878 }
879 
880 /*
881  * get_chars() is the callback from the hvc_console infrastructure
882  * when an interrupt is received.
883  *
884  * We call out to fill_readbuf that gets us the required data from the
885  * buffers that are queued up.
886  */
887 static int get_chars(u32 vtermno, char *buf, int count)
888 {
889 	struct port *port;
890 
891 	/* If we've not set up the port yet, we have no input to give. */
892 	if (unlikely(early_put_chars))
893 		return 0;
894 
895 	port = find_port_by_vtermno(vtermno);
896 	if (!port)
897 		return -EPIPE;
898 
899 	/* If we don't have an input queue yet, we can't get input. */
900 	BUG_ON(!port->in_vq);
901 
902 	return fill_readbuf(port, buf, count, false);
903 }
904 
905 static void resize_console(struct port *port)
906 {
907 	struct virtio_device *vdev;
908 
909 	/* The port could have been hot-unplugged */
910 	if (!port || !is_console_port(port))
911 		return;
912 
913 	vdev = port->portdev->vdev;
914 	if (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE))
915 		hvc_resize(port->cons.hvc, port->cons.ws);
916 }
917 
918 /* We set the configuration at this point, since we now have a tty */
919 static int notifier_add_vio(struct hvc_struct *hp, int data)
920 {
921 	struct port *port;
922 
923 	port = find_port_by_vtermno(hp->vtermno);
924 	if (!port)
925 		return -EINVAL;
926 
927 	hp->irq_requested = 1;
928 	resize_console(port);
929 
930 	return 0;
931 }
932 
933 static void notifier_del_vio(struct hvc_struct *hp, int data)
934 {
935 	hp->irq_requested = 0;
936 }
937 
938 /* The operations for console ports. */
939 static const struct hv_ops hv_ops = {
940 	.get_chars = get_chars,
941 	.put_chars = put_chars,
942 	.notifier_add = notifier_add_vio,
943 	.notifier_del = notifier_del_vio,
944 	.notifier_hangup = notifier_del_vio,
945 };
946 
947 /*
948  * Console drivers are initialized very early so boot messages can go
949  * out, so we do things slightly differently from the generic virtio
950  * initialization of the net and block drivers.
951  *
952  * At this stage, the console is output-only.  It's too early to set
953  * up a virtqueue, so we let the drivers do some boutique early-output
954  * thing.
955  */
956 int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int))
957 {
958 	early_put_chars = put_chars;
959 	return hvc_instantiate(0, 0, &hv_ops);
960 }
961 
962 int init_port_console(struct port *port)
963 {
964 	int ret;
965 
966 	/*
967 	 * The Host's telling us this port is a console port.  Hook it
968 	 * up with an hvc console.
969 	 *
970 	 * To set up and manage our virtual console, we call
971 	 * hvc_alloc().
972 	 *
973 	 * The first argument of hvc_alloc() is the virtual console
974 	 * number.  The second argument is the parameter for the
975 	 * notification mechanism (like irq number).  We currently
976 	 * leave this as zero, virtqueues have implicit notifications.
977 	 *
978 	 * The third argument is a "struct hv_ops" containing the
979 	 * put_chars() get_chars(), notifier_add() and notifier_del()
980 	 * pointers.  The final argument is the output buffer size: we
981 	 * can do any size, so we put PAGE_SIZE here.
982 	 */
983 	port->cons.vtermno = pdrvdata.next_vtermno;
984 
985 	port->cons.hvc = hvc_alloc(port->cons.vtermno, 0, &hv_ops, PAGE_SIZE);
986 	if (IS_ERR(port->cons.hvc)) {
987 		ret = PTR_ERR(port->cons.hvc);
988 		dev_err(port->dev,
989 			"error %d allocating hvc for port\n", ret);
990 		port->cons.hvc = NULL;
991 		return ret;
992 	}
993 	spin_lock_irq(&pdrvdata_lock);
994 	pdrvdata.next_vtermno++;
995 	list_add_tail(&port->cons.list, &pdrvdata.consoles);
996 	spin_unlock_irq(&pdrvdata_lock);
997 	port->guest_connected = true;
998 
999 	/*
1000 	 * Start using the new console output if this is the first
1001 	 * console to come up.
1002 	 */
1003 	if (early_put_chars)
1004 		early_put_chars = NULL;
1005 
1006 	/* Notify host of port being opened */
1007 	send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
1008 
1009 	return 0;
1010 }
1011 
1012 static ssize_t show_port_name(struct device *dev,
1013 			      struct device_attribute *attr, char *buffer)
1014 {
1015 	struct port *port;
1016 
1017 	port = dev_get_drvdata(dev);
1018 
1019 	return sprintf(buffer, "%s\n", port->name);
1020 }
1021 
1022 static DEVICE_ATTR(name, S_IRUGO, show_port_name, NULL);
1023 
1024 static struct attribute *port_sysfs_entries[] = {
1025 	&dev_attr_name.attr,
1026 	NULL
1027 };
1028 
1029 static struct attribute_group port_attribute_group = {
1030 	.name = NULL,		/* put in device directory */
1031 	.attrs = port_sysfs_entries,
1032 };
1033 
1034 static int debugfs_open(struct inode *inode, struct file *filp)
1035 {
1036 	filp->private_data = inode->i_private;
1037 	return 0;
1038 }
1039 
1040 static ssize_t debugfs_read(struct file *filp, char __user *ubuf,
1041 			    size_t count, loff_t *offp)
1042 {
1043 	struct port *port;
1044 	char *buf;
1045 	ssize_t ret, out_offset, out_count;
1046 
1047 	out_count = 1024;
1048 	buf = kmalloc(out_count, GFP_KERNEL);
1049 	if (!buf)
1050 		return -ENOMEM;
1051 
1052 	port = filp->private_data;
1053 	out_offset = 0;
1054 	out_offset += snprintf(buf + out_offset, out_count,
1055 			       "name: %s\n", port->name ? port->name : "");
1056 	out_offset += snprintf(buf + out_offset, out_count - out_offset,
1057 			       "guest_connected: %d\n", port->guest_connected);
1058 	out_offset += snprintf(buf + out_offset, out_count - out_offset,
1059 			       "host_connected: %d\n", port->host_connected);
1060 	out_offset += snprintf(buf + out_offset, out_count - out_offset,
1061 			       "outvq_full: %d\n", port->outvq_full);
1062 	out_offset += snprintf(buf + out_offset, out_count - out_offset,
1063 			       "is_console: %s\n",
1064 			       is_console_port(port) ? "yes" : "no");
1065 	out_offset += snprintf(buf + out_offset, out_count - out_offset,
1066 			       "console_vtermno: %u\n", port->cons.vtermno);
1067 
1068 	ret = simple_read_from_buffer(ubuf, count, offp, buf, out_offset);
1069 	kfree(buf);
1070 	return ret;
1071 }
1072 
1073 static const struct file_operations port_debugfs_ops = {
1074 	.owner = THIS_MODULE,
1075 	.open  = debugfs_open,
1076 	.read  = debugfs_read,
1077 };
1078 
1079 static void set_console_size(struct port *port, u16 rows, u16 cols)
1080 {
1081 	if (!port || !is_console_port(port))
1082 		return;
1083 
1084 	port->cons.ws.ws_row = rows;
1085 	port->cons.ws.ws_col = cols;
1086 }
1087 
1088 static unsigned int fill_queue(struct virtqueue *vq, spinlock_t *lock)
1089 {
1090 	struct port_buffer *buf;
1091 	unsigned int nr_added_bufs;
1092 	int ret;
1093 
1094 	nr_added_bufs = 0;
1095 	do {
1096 		buf = alloc_buf(PAGE_SIZE);
1097 		if (!buf)
1098 			break;
1099 
1100 		spin_lock_irq(lock);
1101 		ret = add_inbuf(vq, buf);
1102 		if (ret < 0) {
1103 			spin_unlock_irq(lock);
1104 			free_buf(buf);
1105 			break;
1106 		}
1107 		nr_added_bufs++;
1108 		spin_unlock_irq(lock);
1109 	} while (ret > 0);
1110 
1111 	return nr_added_bufs;
1112 }
1113 
1114 static void send_sigio_to_port(struct port *port)
1115 {
1116 	if (port->async_queue && port->guest_connected)
1117 		kill_fasync(&port->async_queue, SIGIO, POLL_OUT);
1118 }
1119 
1120 static int add_port(struct ports_device *portdev, u32 id)
1121 {
1122 	char debugfs_name[16];
1123 	struct port *port;
1124 	struct port_buffer *buf;
1125 	dev_t devt;
1126 	unsigned int nr_added_bufs;
1127 	int err;
1128 
1129 	port = kmalloc(sizeof(*port), GFP_KERNEL);
1130 	if (!port) {
1131 		err = -ENOMEM;
1132 		goto fail;
1133 	}
1134 	kref_init(&port->kref);
1135 
1136 	port->portdev = portdev;
1137 	port->id = id;
1138 
1139 	port->name = NULL;
1140 	port->inbuf = NULL;
1141 	port->cons.hvc = NULL;
1142 	port->async_queue = NULL;
1143 
1144 	port->cons.ws.ws_row = port->cons.ws.ws_col = 0;
1145 
1146 	port->host_connected = port->guest_connected = false;
1147 
1148 	port->outvq_full = false;
1149 
1150 	port->in_vq = portdev->in_vqs[port->id];
1151 	port->out_vq = portdev->out_vqs[port->id];
1152 
1153 	port->cdev = cdev_alloc();
1154 	if (!port->cdev) {
1155 		dev_err(&port->portdev->vdev->dev, "Error allocating cdev\n");
1156 		err = -ENOMEM;
1157 		goto free_port;
1158 	}
1159 	port->cdev->ops = &port_fops;
1160 
1161 	devt = MKDEV(portdev->chr_major, id);
1162 	err = cdev_add(port->cdev, devt, 1);
1163 	if (err < 0) {
1164 		dev_err(&port->portdev->vdev->dev,
1165 			"Error %d adding cdev for port %u\n", err, id);
1166 		goto free_cdev;
1167 	}
1168 	port->dev = device_create(pdrvdata.class, &port->portdev->vdev->dev,
1169 				  devt, port, "vport%up%u",
1170 				  port->portdev->drv_index, id);
1171 	if (IS_ERR(port->dev)) {
1172 		err = PTR_ERR(port->dev);
1173 		dev_err(&port->portdev->vdev->dev,
1174 			"Error %d creating device for port %u\n",
1175 			err, id);
1176 		goto free_cdev;
1177 	}
1178 
1179 	spin_lock_init(&port->inbuf_lock);
1180 	spin_lock_init(&port->outvq_lock);
1181 	init_waitqueue_head(&port->waitqueue);
1182 
1183 	/* Fill the in_vq with buffers so the host can send us data. */
1184 	nr_added_bufs = fill_queue(port->in_vq, &port->inbuf_lock);
1185 	if (!nr_added_bufs) {
1186 		dev_err(port->dev, "Error allocating inbufs\n");
1187 		err = -ENOMEM;
1188 		goto free_device;
1189 	}
1190 
1191 	/*
1192 	 * If we're not using multiport support, this has to be a console port
1193 	 */
1194 	if (!use_multiport(port->portdev)) {
1195 		err = init_port_console(port);
1196 		if (err)
1197 			goto free_inbufs;
1198 	}
1199 
1200 	spin_lock_irq(&portdev->ports_lock);
1201 	list_add_tail(&port->list, &port->portdev->ports);
1202 	spin_unlock_irq(&portdev->ports_lock);
1203 
1204 	/*
1205 	 * Tell the Host we're set so that it can send us various
1206 	 * configuration parameters for this port (eg, port name,
1207 	 * caching, whether this is a console port, etc.)
1208 	 */
1209 	send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1210 
1211 	if (pdrvdata.debugfs_dir) {
1212 		/*
1213 		 * Finally, create the debugfs file that we can use to
1214 		 * inspect a port's state at any time
1215 		 */
1216 		sprintf(debugfs_name, "vport%up%u",
1217 			port->portdev->drv_index, id);
1218 		port->debugfs_file = debugfs_create_file(debugfs_name, 0444,
1219 							 pdrvdata.debugfs_dir,
1220 							 port,
1221 							 &port_debugfs_ops);
1222 	}
1223 	return 0;
1224 
1225 free_inbufs:
1226 	while ((buf = virtqueue_detach_unused_buf(port->in_vq)))
1227 		free_buf(buf);
1228 free_device:
1229 	device_destroy(pdrvdata.class, port->dev->devt);
1230 free_cdev:
1231 	cdev_del(port->cdev);
1232 free_port:
1233 	kfree(port);
1234 fail:
1235 	/* The host might want to notify management sw about port add failure */
1236 	__send_control_msg(portdev, id, VIRTIO_CONSOLE_PORT_READY, 0);
1237 	return err;
1238 }
1239 
1240 /* No users remain, remove all port-specific data. */
1241 static void remove_port(struct kref *kref)
1242 {
1243 	struct port *port;
1244 
1245 	port = container_of(kref, struct port, kref);
1246 
1247 	sysfs_remove_group(&port->dev->kobj, &port_attribute_group);
1248 	device_destroy(pdrvdata.class, port->dev->devt);
1249 	cdev_del(port->cdev);
1250 
1251 	kfree(port->name);
1252 
1253 	debugfs_remove(port->debugfs_file);
1254 
1255 	kfree(port);
1256 }
1257 
1258 /*
1259  * Port got unplugged.  Remove port from portdev's list and drop the
1260  * kref reference.  If no userspace has this port opened, it will
1261  * result in immediate removal the port.
1262  */
1263 static void unplug_port(struct port *port)
1264 {
1265 	struct port_buffer *buf;
1266 
1267 	spin_lock_irq(&port->portdev->ports_lock);
1268 	list_del(&port->list);
1269 	spin_unlock_irq(&port->portdev->ports_lock);
1270 
1271 	if (port->guest_connected) {
1272 		port->guest_connected = false;
1273 		port->host_connected = false;
1274 		wake_up_interruptible(&port->waitqueue);
1275 
1276 		/* Let the app know the port is going down. */
1277 		send_sigio_to_port(port);
1278 	}
1279 
1280 	if (is_console_port(port)) {
1281 		spin_lock_irq(&pdrvdata_lock);
1282 		list_del(&port->cons.list);
1283 		spin_unlock_irq(&pdrvdata_lock);
1284 		hvc_remove(port->cons.hvc);
1285 	}
1286 
1287 	/* Remove unused data this port might have received. */
1288 	discard_port_data(port);
1289 
1290 	reclaim_consumed_buffers(port);
1291 
1292 	/* Remove buffers we queued up for the Host to send us data in. */
1293 	while ((buf = virtqueue_detach_unused_buf(port->in_vq)))
1294 		free_buf(buf);
1295 
1296 	/*
1297 	 * We should just assume the device itself has gone off --
1298 	 * else a close on an open port later will try to send out a
1299 	 * control message.
1300 	 */
1301 	port->portdev = NULL;
1302 
1303 	/*
1304 	 * Locks around here are not necessary - a port can't be
1305 	 * opened after we removed the port struct from ports_list
1306 	 * above.
1307 	 */
1308 	kref_put(&port->kref, remove_port);
1309 }
1310 
1311 /* Any private messages that the Host and Guest want to share */
1312 static void handle_control_message(struct ports_device *portdev,
1313 				   struct port_buffer *buf)
1314 {
1315 	struct virtio_console_control *cpkt;
1316 	struct port *port;
1317 	size_t name_size;
1318 	int err;
1319 
1320 	cpkt = (struct virtio_console_control *)(buf->buf + buf->offset);
1321 
1322 	port = find_port_by_id(portdev, cpkt->id);
1323 	if (!port && cpkt->event != VIRTIO_CONSOLE_PORT_ADD) {
1324 		/* No valid header at start of buffer.  Drop it. */
1325 		dev_dbg(&portdev->vdev->dev,
1326 			"Invalid index %u in control packet\n", cpkt->id);
1327 		return;
1328 	}
1329 
1330 	switch (cpkt->event) {
1331 	case VIRTIO_CONSOLE_PORT_ADD:
1332 		if (port) {
1333 			dev_dbg(&portdev->vdev->dev,
1334 				"Port %u already added\n", port->id);
1335 			send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1336 			break;
1337 		}
1338 		if (cpkt->id >= portdev->config.max_nr_ports) {
1339 			dev_warn(&portdev->vdev->dev,
1340 				"Request for adding port with out-of-bound id %u, max. supported id: %u\n",
1341 				cpkt->id, portdev->config.max_nr_ports - 1);
1342 			break;
1343 		}
1344 		add_port(portdev, cpkt->id);
1345 		break;
1346 	case VIRTIO_CONSOLE_PORT_REMOVE:
1347 		unplug_port(port);
1348 		break;
1349 	case VIRTIO_CONSOLE_CONSOLE_PORT:
1350 		if (!cpkt->value)
1351 			break;
1352 		if (is_console_port(port))
1353 			break;
1354 
1355 		init_port_console(port);
1356 		/*
1357 		 * Could remove the port here in case init fails - but
1358 		 * have to notify the host first.
1359 		 */
1360 		break;
1361 	case VIRTIO_CONSOLE_RESIZE: {
1362 		struct {
1363 			__u16 rows;
1364 			__u16 cols;
1365 		} size;
1366 
1367 		if (!is_console_port(port))
1368 			break;
1369 
1370 		memcpy(&size, buf->buf + buf->offset + sizeof(*cpkt),
1371 		       sizeof(size));
1372 		set_console_size(port, size.rows, size.cols);
1373 
1374 		port->cons.hvc->irq_requested = 1;
1375 		resize_console(port);
1376 		break;
1377 	}
1378 	case VIRTIO_CONSOLE_PORT_OPEN:
1379 		port->host_connected = cpkt->value;
1380 		wake_up_interruptible(&port->waitqueue);
1381 		/*
1382 		 * If the host port got closed and the host had any
1383 		 * unconsumed buffers, we'll be able to reclaim them
1384 		 * now.
1385 		 */
1386 		spin_lock_irq(&port->outvq_lock);
1387 		reclaim_consumed_buffers(port);
1388 		spin_unlock_irq(&port->outvq_lock);
1389 
1390 		/*
1391 		 * If the guest is connected, it'll be interested in
1392 		 * knowing the host connection state changed.
1393 		 */
1394 		send_sigio_to_port(port);
1395 		break;
1396 	case VIRTIO_CONSOLE_PORT_NAME:
1397 		/*
1398 		 * Skip the size of the header and the cpkt to get the size
1399 		 * of the name that was sent
1400 		 */
1401 		name_size = buf->len - buf->offset - sizeof(*cpkt) + 1;
1402 
1403 		port->name = kmalloc(name_size, GFP_KERNEL);
1404 		if (!port->name) {
1405 			dev_err(port->dev,
1406 				"Not enough space to store port name\n");
1407 			break;
1408 		}
1409 		strncpy(port->name, buf->buf + buf->offset + sizeof(*cpkt),
1410 			name_size - 1);
1411 		port->name[name_size - 1] = 0;
1412 
1413 		/*
1414 		 * Since we only have one sysfs attribute, 'name',
1415 		 * create it only if we have a name for the port.
1416 		 */
1417 		err = sysfs_create_group(&port->dev->kobj,
1418 					 &port_attribute_group);
1419 		if (err) {
1420 			dev_err(port->dev,
1421 				"Error %d creating sysfs device attributes\n",
1422 				err);
1423 		} else {
1424 			/*
1425 			 * Generate a udev event so that appropriate
1426 			 * symlinks can be created based on udev
1427 			 * rules.
1428 			 */
1429 			kobject_uevent(&port->dev->kobj, KOBJ_CHANGE);
1430 		}
1431 		break;
1432 	}
1433 }
1434 
1435 static void control_work_handler(struct work_struct *work)
1436 {
1437 	struct ports_device *portdev;
1438 	struct virtqueue *vq;
1439 	struct port_buffer *buf;
1440 	unsigned int len;
1441 
1442 	portdev = container_of(work, struct ports_device, control_work);
1443 	vq = portdev->c_ivq;
1444 
1445 	spin_lock(&portdev->cvq_lock);
1446 	while ((buf = virtqueue_get_buf(vq, &len))) {
1447 		spin_unlock(&portdev->cvq_lock);
1448 
1449 		buf->len = len;
1450 		buf->offset = 0;
1451 
1452 		handle_control_message(portdev, buf);
1453 
1454 		spin_lock(&portdev->cvq_lock);
1455 		if (add_inbuf(portdev->c_ivq, buf) < 0) {
1456 			dev_warn(&portdev->vdev->dev,
1457 				 "Error adding buffer to queue\n");
1458 			free_buf(buf);
1459 		}
1460 	}
1461 	spin_unlock(&portdev->cvq_lock);
1462 }
1463 
1464 static void out_intr(struct virtqueue *vq)
1465 {
1466 	struct port *port;
1467 
1468 	port = find_port_by_vq(vq->vdev->priv, vq);
1469 	if (!port)
1470 		return;
1471 
1472 	wake_up_interruptible(&port->waitqueue);
1473 }
1474 
1475 static void in_intr(struct virtqueue *vq)
1476 {
1477 	struct port *port;
1478 	unsigned long flags;
1479 
1480 	port = find_port_by_vq(vq->vdev->priv, vq);
1481 	if (!port)
1482 		return;
1483 
1484 	spin_lock_irqsave(&port->inbuf_lock, flags);
1485 	if (!port->inbuf)
1486 		port->inbuf = get_inbuf(port);
1487 
1488 	/*
1489 	 * Don't queue up data when port is closed.  This condition
1490 	 * can be reached when a console port is not yet connected (no
1491 	 * tty is spawned) and the host sends out data to console
1492 	 * ports.  For generic serial ports, the host won't
1493 	 * (shouldn't) send data till the guest is connected.
1494 	 */
1495 	if (!port->guest_connected)
1496 		discard_port_data(port);
1497 
1498 	spin_unlock_irqrestore(&port->inbuf_lock, flags);
1499 
1500 	wake_up_interruptible(&port->waitqueue);
1501 
1502 	/* Send a SIGIO indicating new data in case the process asked for it */
1503 	send_sigio_to_port(port);
1504 
1505 	if (is_console_port(port) && hvc_poll(port->cons.hvc))
1506 		hvc_kick();
1507 }
1508 
1509 static void control_intr(struct virtqueue *vq)
1510 {
1511 	struct ports_device *portdev;
1512 
1513 	portdev = vq->vdev->priv;
1514 	schedule_work(&portdev->control_work);
1515 }
1516 
1517 static void config_intr(struct virtio_device *vdev)
1518 {
1519 	struct ports_device *portdev;
1520 
1521 	portdev = vdev->priv;
1522 
1523 	if (!use_multiport(portdev)) {
1524 		struct port *port;
1525 		u16 rows, cols;
1526 
1527 		vdev->config->get(vdev,
1528 				  offsetof(struct virtio_console_config, cols),
1529 				  &cols, sizeof(u16));
1530 		vdev->config->get(vdev,
1531 				  offsetof(struct virtio_console_config, rows),
1532 				  &rows, sizeof(u16));
1533 
1534 		port = find_port_by_id(portdev, 0);
1535 		set_console_size(port, rows, cols);
1536 
1537 		/*
1538 		 * We'll use this way of resizing only for legacy
1539 		 * support.  For newer userspace
1540 		 * (VIRTIO_CONSOLE_F_MULTPORT+), use control messages
1541 		 * to indicate console size changes so that it can be
1542 		 * done per-port.
1543 		 */
1544 		resize_console(port);
1545 	}
1546 }
1547 
1548 static int init_vqs(struct ports_device *portdev)
1549 {
1550 	vq_callback_t **io_callbacks;
1551 	char **io_names;
1552 	struct virtqueue **vqs;
1553 	u32 i, j, nr_ports, nr_queues;
1554 	int err;
1555 
1556 	nr_ports = portdev->config.max_nr_ports;
1557 	nr_queues = use_multiport(portdev) ? (nr_ports + 1) * 2 : 2;
1558 
1559 	vqs = kmalloc(nr_queues * sizeof(struct virtqueue *), GFP_KERNEL);
1560 	io_callbacks = kmalloc(nr_queues * sizeof(vq_callback_t *), GFP_KERNEL);
1561 	io_names = kmalloc(nr_queues * sizeof(char *), GFP_KERNEL);
1562 	portdev->in_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
1563 				  GFP_KERNEL);
1564 	portdev->out_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
1565 				   GFP_KERNEL);
1566 	if (!vqs || !io_callbacks || !io_names || !portdev->in_vqs ||
1567 			!portdev->out_vqs) {
1568 		err = -ENOMEM;
1569 		goto free;
1570 	}
1571 
1572 	/*
1573 	 * For backward compat (newer host but older guest), the host
1574 	 * spawns a console port first and also inits the vqs for port
1575 	 * 0 before others.
1576 	 */
1577 	j = 0;
1578 	io_callbacks[j] = in_intr;
1579 	io_callbacks[j + 1] = out_intr;
1580 	io_names[j] = "input";
1581 	io_names[j + 1] = "output";
1582 	j += 2;
1583 
1584 	if (use_multiport(portdev)) {
1585 		io_callbacks[j] = control_intr;
1586 		io_callbacks[j + 1] = NULL;
1587 		io_names[j] = "control-i";
1588 		io_names[j + 1] = "control-o";
1589 
1590 		for (i = 1; i < nr_ports; i++) {
1591 			j += 2;
1592 			io_callbacks[j] = in_intr;
1593 			io_callbacks[j + 1] = out_intr;
1594 			io_names[j] = "input";
1595 			io_names[j + 1] = "output";
1596 		}
1597 	}
1598 	/* Find the queues. */
1599 	err = portdev->vdev->config->find_vqs(portdev->vdev, nr_queues, vqs,
1600 					      io_callbacks,
1601 					      (const char **)io_names);
1602 	if (err)
1603 		goto free;
1604 
1605 	j = 0;
1606 	portdev->in_vqs[0] = vqs[0];
1607 	portdev->out_vqs[0] = vqs[1];
1608 	j += 2;
1609 	if (use_multiport(portdev)) {
1610 		portdev->c_ivq = vqs[j];
1611 		portdev->c_ovq = vqs[j + 1];
1612 
1613 		for (i = 1; i < nr_ports; i++) {
1614 			j += 2;
1615 			portdev->in_vqs[i] = vqs[j];
1616 			portdev->out_vqs[i] = vqs[j + 1];
1617 		}
1618 	}
1619 	kfree(io_names);
1620 	kfree(io_callbacks);
1621 	kfree(vqs);
1622 
1623 	return 0;
1624 
1625 free:
1626 	kfree(portdev->out_vqs);
1627 	kfree(portdev->in_vqs);
1628 	kfree(io_names);
1629 	kfree(io_callbacks);
1630 	kfree(vqs);
1631 
1632 	return err;
1633 }
1634 
1635 static const struct file_operations portdev_fops = {
1636 	.owner = THIS_MODULE,
1637 };
1638 
1639 /*
1640  * Once we're further in boot, we get probed like any other virtio
1641  * device.
1642  *
1643  * If the host also supports multiple console ports, we check the
1644  * config space to see how many ports the host has spawned.  We
1645  * initialize each port found.
1646  */
1647 static int __devinit virtcons_probe(struct virtio_device *vdev)
1648 {
1649 	struct ports_device *portdev;
1650 	int err;
1651 	bool multiport;
1652 
1653 	portdev = kmalloc(sizeof(*portdev), GFP_KERNEL);
1654 	if (!portdev) {
1655 		err = -ENOMEM;
1656 		goto fail;
1657 	}
1658 
1659 	/* Attach this portdev to this virtio_device, and vice-versa. */
1660 	portdev->vdev = vdev;
1661 	vdev->priv = portdev;
1662 
1663 	spin_lock_irq(&pdrvdata_lock);
1664 	portdev->drv_index = pdrvdata.index++;
1665 	spin_unlock_irq(&pdrvdata_lock);
1666 
1667 	portdev->chr_major = register_chrdev(0, "virtio-portsdev",
1668 					     &portdev_fops);
1669 	if (portdev->chr_major < 0) {
1670 		dev_err(&vdev->dev,
1671 			"Error %d registering chrdev for device %u\n",
1672 			portdev->chr_major, portdev->drv_index);
1673 		err = portdev->chr_major;
1674 		goto free;
1675 	}
1676 
1677 	multiport = false;
1678 	portdev->config.max_nr_ports = 1;
1679 	if (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT)) {
1680 		multiport = true;
1681 		vdev->config->get(vdev, offsetof(struct virtio_console_config,
1682 						 max_nr_ports),
1683 				  &portdev->config.max_nr_ports,
1684 				  sizeof(portdev->config.max_nr_ports));
1685 	}
1686 
1687 	err = init_vqs(portdev);
1688 	if (err < 0) {
1689 		dev_err(&vdev->dev, "Error %d initializing vqs\n", err);
1690 		goto free_chrdev;
1691 	}
1692 
1693 	spin_lock_init(&portdev->ports_lock);
1694 	INIT_LIST_HEAD(&portdev->ports);
1695 
1696 	if (multiport) {
1697 		unsigned int nr_added_bufs;
1698 
1699 		spin_lock_init(&portdev->cvq_lock);
1700 		INIT_WORK(&portdev->control_work, &control_work_handler);
1701 
1702 		nr_added_bufs = fill_queue(portdev->c_ivq, &portdev->cvq_lock);
1703 		if (!nr_added_bufs) {
1704 			dev_err(&vdev->dev,
1705 				"Error allocating buffers for control queue\n");
1706 			err = -ENOMEM;
1707 			goto free_vqs;
1708 		}
1709 	} else {
1710 		/*
1711 		 * For backward compatibility: Create a console port
1712 		 * if we're running on older host.
1713 		 */
1714 		add_port(portdev, 0);
1715 	}
1716 
1717 	spin_lock_irq(&pdrvdata_lock);
1718 	list_add_tail(&portdev->list, &pdrvdata.portdevs);
1719 	spin_unlock_irq(&pdrvdata_lock);
1720 
1721 	__send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
1722 			   VIRTIO_CONSOLE_DEVICE_READY, 1);
1723 	return 0;
1724 
1725 free_vqs:
1726 	/* The host might want to notify mgmt sw about device add failure */
1727 	__send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
1728 			   VIRTIO_CONSOLE_DEVICE_READY, 0);
1729 	vdev->config->del_vqs(vdev);
1730 	kfree(portdev->in_vqs);
1731 	kfree(portdev->out_vqs);
1732 free_chrdev:
1733 	unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1734 free:
1735 	kfree(portdev);
1736 fail:
1737 	return err;
1738 }
1739 
1740 static void virtcons_remove(struct virtio_device *vdev)
1741 {
1742 	struct ports_device *portdev;
1743 	struct port *port, *port2;
1744 
1745 	portdev = vdev->priv;
1746 
1747 	spin_lock_irq(&pdrvdata_lock);
1748 	list_del(&portdev->list);
1749 	spin_unlock_irq(&pdrvdata_lock);
1750 
1751 	/* Disable interrupts for vqs */
1752 	vdev->config->reset(vdev);
1753 	/* Finish up work that's lined up */
1754 	cancel_work_sync(&portdev->control_work);
1755 
1756 	list_for_each_entry_safe(port, port2, &portdev->ports, list)
1757 		unplug_port(port);
1758 
1759 	unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1760 
1761 	/*
1762 	 * When yanking out a device, we immediately lose the
1763 	 * (device-side) queues.  So there's no point in keeping the
1764 	 * guest side around till we drop our final reference.  This
1765 	 * also means that any ports which are in an open state will
1766 	 * have to just stop using the port, as the vqs are going
1767 	 * away.
1768 	 */
1769 	if (use_multiport(portdev)) {
1770 		struct port_buffer *buf;
1771 		unsigned int len;
1772 
1773 		while ((buf = virtqueue_get_buf(portdev->c_ivq, &len)))
1774 			free_buf(buf);
1775 
1776 		while ((buf = virtqueue_detach_unused_buf(portdev->c_ivq)))
1777 			free_buf(buf);
1778 	}
1779 
1780 	vdev->config->del_vqs(vdev);
1781 	kfree(portdev->in_vqs);
1782 	kfree(portdev->out_vqs);
1783 
1784 	kfree(portdev);
1785 }
1786 
1787 static struct virtio_device_id id_table[] = {
1788 	{ VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID },
1789 	{ 0 },
1790 };
1791 
1792 static unsigned int features[] = {
1793 	VIRTIO_CONSOLE_F_SIZE,
1794 	VIRTIO_CONSOLE_F_MULTIPORT,
1795 };
1796 
1797 static struct virtio_driver virtio_console = {
1798 	.feature_table = features,
1799 	.feature_table_size = ARRAY_SIZE(features),
1800 	.driver.name =	KBUILD_MODNAME,
1801 	.driver.owner =	THIS_MODULE,
1802 	.id_table =	id_table,
1803 	.probe =	virtcons_probe,
1804 	.remove =	virtcons_remove,
1805 	.config_changed = config_intr,
1806 };
1807 
1808 static int __init init(void)
1809 {
1810 	int err;
1811 
1812 	pdrvdata.class = class_create(THIS_MODULE, "virtio-ports");
1813 	if (IS_ERR(pdrvdata.class)) {
1814 		err = PTR_ERR(pdrvdata.class);
1815 		pr_err("Error %d creating virtio-ports class\n", err);
1816 		return err;
1817 	}
1818 
1819 	pdrvdata.debugfs_dir = debugfs_create_dir("virtio-ports", NULL);
1820 	if (!pdrvdata.debugfs_dir) {
1821 		pr_warning("Error %ld creating debugfs dir for virtio-ports\n",
1822 			   PTR_ERR(pdrvdata.debugfs_dir));
1823 	}
1824 	INIT_LIST_HEAD(&pdrvdata.consoles);
1825 	INIT_LIST_HEAD(&pdrvdata.portdevs);
1826 
1827 	return register_virtio_driver(&virtio_console);
1828 }
1829 
1830 static void __exit fini(void)
1831 {
1832 	unregister_virtio_driver(&virtio_console);
1833 
1834 	class_destroy(pdrvdata.class);
1835 	if (pdrvdata.debugfs_dir)
1836 		debugfs_remove_recursive(pdrvdata.debugfs_dir);
1837 }
1838 module_init(init);
1839 module_exit(fini);
1840 
1841 MODULE_DEVICE_TABLE(virtio, id_table);
1842 MODULE_DESCRIPTION("Virtio console driver");
1843 MODULE_LICENSE("GPL");
1844