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>
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.
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.
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
20 #include <linux/cdev.h>
21 #include <linux/debugfs.h>
22 #include <linux/completion.h>
23 #include <linux/device.h>
24 #include <linux/err.h>
25 #include <linux/freezer.h>
27 #include <linux/init.h>
28 #include <linux/list.h>
29 #include <linux/poll.h>
30 #include <linux/sched.h>
31 #include <linux/slab.h>
32 #include <linux/spinlock.h>
33 #include <linux/virtio.h>
34 #include <linux/virtio_console.h>
35 #include <linux/wait.h>
36 #include <linux/workqueue.h>
37 #include <linux/module.h>
38 #include "../tty/hvc/hvc_console.h"
41 * This is a global struct for storing common data for all the devices
42 * this driver handles.
44 * Mainly, it has a linked list for all the consoles in one place so
45 * that callbacks from hvc for get_chars(), put_chars() work properly
46 * across multiple devices and multiple ports per device.
48 struct ports_driver_data {
49 /* Used for registering chardevs */
52 /* Used for exporting per-port information to debugfs */
53 struct dentry *debugfs_dir;
55 /* List of all the devices we're handling */
56 struct list_head portdevs;
58 /* Number of devices this driver is handling */
62 * This is used to keep track of the number of hvc consoles
63 * spawned by this driver. This number is given as the first
64 * argument to hvc_alloc(). To correctly map an initial
65 * console spawned via hvc_instantiate to the console being
66 * hooked up via hvc_alloc, we need to pass the same vtermno.
68 * We also just assume the first console being initialised was
69 * the first one that got used as the initial console.
71 unsigned int next_vtermno;
73 /* All the console devices handled by this driver */
74 struct list_head consoles;
76 static struct ports_driver_data pdrvdata;
78 DEFINE_SPINLOCK(pdrvdata_lock);
79 DECLARE_COMPLETION(early_console_added);
81 /* This struct holds information that's relevant only for console ports */
83 /* We'll place all consoles in a list in the pdrvdata struct */
84 struct list_head list;
86 /* The hvc device associated with this console port */
87 struct hvc_struct *hvc;
89 /* The size of the console */
93 * This number identifies the number that we used to register
94 * with hvc in hvc_instantiate() and hvc_alloc(); this is the
95 * number passed on by the hvc callbacks to us to
96 * differentiate between the other console ports handled by
105 /* size of the buffer in *buf above */
108 /* used length of the buffer */
110 /* offset in the buf from which to consume data */
115 * This is a per-device struct that stores data common to all the
116 * ports for that device (vdev->priv).
118 struct ports_device {
119 /* Next portdev in the list, head is in the pdrvdata struct */
120 struct list_head list;
123 * Workqueue handlers where we process deferred work after
126 struct work_struct control_work;
128 struct list_head ports;
130 /* To protect the list of ports */
131 spinlock_t ports_lock;
133 /* To protect the vq operations for the control channel */
134 spinlock_t c_ivq_lock;
135 spinlock_t c_ovq_lock;
137 /* The current config space is stored here */
138 struct virtio_console_config config;
140 /* The virtio device we're associated with */
141 struct virtio_device *vdev;
144 * A couple of virtqueues for the control channel: one for
145 * guest->host transfers, one for host->guest transfers
147 struct virtqueue *c_ivq, *c_ovq;
149 /* Array of per-port IO virtqueues */
150 struct virtqueue **in_vqs, **out_vqs;
152 /* Used for numbering devices for sysfs and debugfs */
153 unsigned int drv_index;
155 /* Major number for this device. Ports will be created as minors. */
160 unsigned long bytes_sent, bytes_received, bytes_discarded;
163 /* This struct holds the per-port data */
165 /* Next port in the list, head is in the ports_device */
166 struct list_head list;
168 /* Pointer to the parent virtio_console device */
169 struct ports_device *portdev;
171 /* The current buffer from which data has to be fed to readers */
172 struct port_buffer *inbuf;
175 * To protect the operations on the in_vq associated with this
176 * port. Has to be a spinlock because it can be called from
177 * interrupt context (get_char()).
179 spinlock_t inbuf_lock;
181 /* Protect the operations on the out_vq. */
182 spinlock_t outvq_lock;
184 /* The IO vqs for this port */
185 struct virtqueue *in_vq, *out_vq;
187 /* File in the debugfs directory that exposes this port's information */
188 struct dentry *debugfs_file;
191 * Keep count of the bytes sent, received and discarded for
192 * this port for accounting and debugging purposes. These
193 * counts are not reset across port open / close events.
195 struct port_stats stats;
198 * The entries in this struct will be valid if this port is
199 * hooked up to an hvc console
203 /* Each port associates with a separate char device */
207 /* Reference-counting to handle port hot-unplugs and file operations */
210 /* A waitqueue for poll() or blocking read operations */
211 wait_queue_head_t waitqueue;
213 /* The 'name' of the port that we expose via sysfs properties */
216 /* We can notify apps of host connect / disconnect events via SIGIO */
217 struct fasync_struct *async_queue;
219 /* The 'id' to identify the port with the Host */
224 /* Is the host device open */
227 /* We should allow only one process to open a port */
228 bool guest_connected;
231 /* This is the very early arch-specified put chars function. */
232 static int (*early_put_chars)(u32, const char *, int);
234 static struct port *find_port_by_vtermno(u32 vtermno)
237 struct console *cons;
240 spin_lock_irqsave(&pdrvdata_lock, flags);
241 list_for_each_entry(cons, &pdrvdata.consoles, list) {
242 if (cons->vtermno == vtermno) {
243 port = container_of(cons, struct port, cons);
249 spin_unlock_irqrestore(&pdrvdata_lock, flags);
253 static struct port *find_port_by_devt_in_portdev(struct ports_device *portdev,
259 spin_lock_irqsave(&portdev->ports_lock, flags);
260 list_for_each_entry(port, &portdev->ports, list)
261 if (port->cdev->dev == dev)
265 spin_unlock_irqrestore(&portdev->ports_lock, flags);
270 static struct port *find_port_by_devt(dev_t dev)
272 struct ports_device *portdev;
276 spin_lock_irqsave(&pdrvdata_lock, flags);
277 list_for_each_entry(portdev, &pdrvdata.portdevs, list) {
278 port = find_port_by_devt_in_portdev(portdev, dev);
284 spin_unlock_irqrestore(&pdrvdata_lock, flags);
288 static struct port *find_port_by_id(struct ports_device *portdev, u32 id)
293 spin_lock_irqsave(&portdev->ports_lock, flags);
294 list_for_each_entry(port, &portdev->ports, list)
299 spin_unlock_irqrestore(&portdev->ports_lock, flags);
304 static struct port *find_port_by_vq(struct ports_device *portdev,
305 struct virtqueue *vq)
310 spin_lock_irqsave(&portdev->ports_lock, flags);
311 list_for_each_entry(port, &portdev->ports, list)
312 if (port->in_vq == vq || port->out_vq == vq)
316 spin_unlock_irqrestore(&portdev->ports_lock, flags);
320 static bool is_console_port(struct port *port)
327 static inline bool use_multiport(struct ports_device *portdev)
330 * This condition can be true when put_chars is called from
335 return portdev->vdev->features[0] & (1 << VIRTIO_CONSOLE_F_MULTIPORT);
338 static void free_buf(struct port_buffer *buf)
344 static struct port_buffer *alloc_buf(size_t buf_size)
346 struct port_buffer *buf;
348 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
351 buf->buf = kzalloc(buf_size, GFP_KERNEL);
356 buf->size = buf_size;
365 /* Callers should take appropriate locks */
366 static struct port_buffer *get_inbuf(struct port *port)
368 struct port_buffer *buf;
374 buf = virtqueue_get_buf(port->in_vq, &len);
378 port->stats.bytes_received += len;
384 * Create a scatter-gather list representing our input buffer and put
387 * Callers should take appropriate locks.
389 static int add_inbuf(struct virtqueue *vq, struct port_buffer *buf)
391 struct scatterlist sg[1];
394 sg_init_one(sg, buf->buf, buf->size);
396 ret = virtqueue_add_buf(vq, sg, 0, 1, buf);
401 /* Discard any unread data this port has. Callers lockers. */
402 static void discard_port_data(struct port *port)
404 struct port_buffer *buf;
407 if (!port->portdev) {
408 /* Device has been unplugged. vqs are already gone. */
411 buf = get_inbuf(port);
415 port->stats.bytes_discarded += buf->len - buf->offset;
416 if (add_inbuf(port->in_vq, buf) < 0) {
421 buf = get_inbuf(port);
424 dev_warn(port->dev, "Errors adding %d buffers back to vq\n",
428 static bool port_has_data(struct port *port)
434 spin_lock_irqsave(&port->inbuf_lock, flags);
435 port->inbuf = get_inbuf(port);
439 spin_unlock_irqrestore(&port->inbuf_lock, flags);
443 static ssize_t __send_control_msg(struct ports_device *portdev, u32 port_id,
444 unsigned int event, unsigned int value)
446 struct scatterlist sg[1];
447 struct virtio_console_control cpkt;
448 struct virtqueue *vq;
451 if (!use_multiport(portdev))
460 sg_init_one(sg, &cpkt, sizeof(cpkt));
462 spin_lock(&portdev->c_ovq_lock);
463 if (virtqueue_add_buf(vq, sg, 1, 0, &cpkt) >= 0) {
465 while (!virtqueue_get_buf(vq, &len))
468 spin_unlock(&portdev->c_ovq_lock);
472 static ssize_t send_control_msg(struct port *port, unsigned int event,
475 /* Did the port get unplugged before userspace closed it? */
477 return __send_control_msg(port->portdev, port->id, event, value);
481 /* Callers must take the port->outvq_lock */
482 static void reclaim_consumed_buffers(struct port *port)
487 if (!port->portdev) {
488 /* Device has been unplugged. vqs are already gone. */
491 while ((buf = virtqueue_get_buf(port->out_vq, &len))) {
493 port->outvq_full = false;
497 static ssize_t send_buf(struct port *port, void *in_buf, size_t in_count,
500 struct scatterlist sg[1];
501 struct virtqueue *out_vq;
506 out_vq = port->out_vq;
508 spin_lock_irqsave(&port->outvq_lock, flags);
510 reclaim_consumed_buffers(port);
512 sg_init_one(sg, in_buf, in_count);
513 ret = virtqueue_add_buf(out_vq, sg, 1, 0, in_buf);
515 /* Tell Host to go! */
516 virtqueue_kick(out_vq);
524 port->outvq_full = true;
530 * Wait till the host acknowledges it pushed out the data we
531 * sent. This is done for data from the hvc_console; the tty
532 * operations are performed with spinlocks held so we can't
533 * sleep here. An alternative would be to copy the data to a
534 * buffer and relax the spinning requirement. The downside is
535 * we need to kmalloc a GFP_ATOMIC buffer each time the
536 * console driver writes something out.
538 while (!virtqueue_get_buf(out_vq, &len))
541 spin_unlock_irqrestore(&port->outvq_lock, flags);
543 port->stats.bytes_sent += in_count;
545 * We're expected to return the amount of data we wrote -- all
552 * Give out the data that's requested from the buffer that we have
555 static ssize_t fill_readbuf(struct port *port, char *out_buf, size_t out_count,
558 struct port_buffer *buf;
561 if (!out_count || !port_has_data(port))
565 out_count = min(out_count, buf->len - buf->offset);
570 ret = copy_to_user(out_buf, buf->buf + buf->offset, out_count);
574 memcpy(out_buf, buf->buf + buf->offset, out_count);
577 buf->offset += out_count;
579 if (buf->offset == buf->len) {
581 * We're done using all the data in this buffer.
582 * Re-queue so that the Host can send us more data.
584 spin_lock_irqsave(&port->inbuf_lock, flags);
587 if (add_inbuf(port->in_vq, buf) < 0)
588 dev_warn(port->dev, "failed add_buf\n");
590 spin_unlock_irqrestore(&port->inbuf_lock, flags);
592 /* Return the number of bytes actually copied */
596 /* The condition that must be true for polling to end */
597 static bool will_read_block(struct port *port)
599 if (!port->guest_connected) {
600 /* Port got hot-unplugged. Let's exit. */
603 return !port_has_data(port) && port->host_connected;
606 static bool will_write_block(struct port *port)
610 if (!port->guest_connected) {
611 /* Port got hot-unplugged. Let's exit. */
614 if (!port->host_connected)
617 spin_lock_irq(&port->outvq_lock);
619 * Check if the Host has consumed any buffers since we last
620 * sent data (this is only applicable for nonblocking ports).
622 reclaim_consumed_buffers(port);
623 ret = port->outvq_full;
624 spin_unlock_irq(&port->outvq_lock);
629 static ssize_t port_fops_read(struct file *filp, char __user *ubuf,
630 size_t count, loff_t *offp)
635 port = filp->private_data;
637 if (!port_has_data(port)) {
639 * If nothing's connected on the host just return 0 in
640 * case of list_empty; this tells the userspace app
641 * that there's no connection
643 if (!port->host_connected)
645 if (filp->f_flags & O_NONBLOCK)
648 ret = wait_event_freezable(port->waitqueue,
649 !will_read_block(port));
653 /* Port got hot-unplugged. */
654 if (!port->guest_connected)
657 * We could've received a disconnection message while we were
658 * waiting for more data.
660 * This check is not clubbed in the if() statement above as we
661 * might receive some data as well as the host could get
662 * disconnected after we got woken up from our wait. So we
663 * really want to give off whatever data we have and only then
664 * check for host_connected.
666 if (!port_has_data(port) && !port->host_connected)
669 return fill_readbuf(port, ubuf, count, true);
672 static ssize_t port_fops_write(struct file *filp, const char __user *ubuf,
673 size_t count, loff_t *offp)
680 /* Userspace could be out to fool us */
684 port = filp->private_data;
686 nonblock = filp->f_flags & O_NONBLOCK;
688 if (will_write_block(port)) {
692 ret = wait_event_freezable(port->waitqueue,
693 !will_write_block(port));
697 /* Port got hot-unplugged. */
698 if (!port->guest_connected)
701 count = min((size_t)(32 * 1024), count);
703 buf = kmalloc(count, GFP_KERNEL);
707 ret = copy_from_user(buf, ubuf, count);
714 * We now ask send_buf() to not spin for generic ports -- we
715 * can re-use the same code path that non-blocking file
716 * descriptors take for blocking file descriptors since the
717 * wait is already done and we're certain the write will go
718 * through to the host.
721 ret = send_buf(port, buf, count, nonblock);
723 if (nonblock && ret > 0)
732 static unsigned int port_fops_poll(struct file *filp, poll_table *wait)
737 port = filp->private_data;
738 poll_wait(filp, &port->waitqueue, wait);
740 if (!port->guest_connected) {
741 /* Port got unplugged */
745 if (!will_read_block(port))
746 ret |= POLLIN | POLLRDNORM;
747 if (!will_write_block(port))
749 if (!port->host_connected)
755 static void remove_port(struct kref *kref);
757 static int port_fops_release(struct inode *inode, struct file *filp)
761 port = filp->private_data;
763 /* Notify host of port being closed */
764 send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
766 spin_lock_irq(&port->inbuf_lock);
767 port->guest_connected = false;
769 discard_port_data(port);
771 spin_unlock_irq(&port->inbuf_lock);
773 spin_lock_irq(&port->outvq_lock);
774 reclaim_consumed_buffers(port);
775 spin_unlock_irq(&port->outvq_lock);
778 * Locks aren't necessary here as a port can't be opened after
779 * unplug, and if a port isn't unplugged, a kref would already
780 * exist for the port. Plus, taking ports_lock here would
781 * create a dependency on other locks taken by functions
782 * inside remove_port if we're the last holder of the port,
783 * creating many problems.
785 kref_put(&port->kref, remove_port);
790 static int port_fops_open(struct inode *inode, struct file *filp)
792 struct cdev *cdev = inode->i_cdev;
796 port = find_port_by_devt(cdev->dev);
797 filp->private_data = port;
799 /* Prevent against a port getting hot-unplugged at the same time */
800 spin_lock_irq(&port->portdev->ports_lock);
801 kref_get(&port->kref);
802 spin_unlock_irq(&port->portdev->ports_lock);
805 * Don't allow opening of console port devices -- that's done
808 if (is_console_port(port)) {
813 /* Allow only one process to open a particular port at a time */
814 spin_lock_irq(&port->inbuf_lock);
815 if (port->guest_connected) {
816 spin_unlock_irq(&port->inbuf_lock);
821 port->guest_connected = true;
822 spin_unlock_irq(&port->inbuf_lock);
824 spin_lock_irq(&port->outvq_lock);
826 * There might be a chance that we missed reclaiming a few
827 * buffers in the window of the port getting previously closed
830 reclaim_consumed_buffers(port);
831 spin_unlock_irq(&port->outvq_lock);
833 nonseekable_open(inode, filp);
835 /* Notify host of port being opened */
836 send_control_msg(filp->private_data, VIRTIO_CONSOLE_PORT_OPEN, 1);
840 kref_put(&port->kref, remove_port);
844 static int port_fops_fasync(int fd, struct file *filp, int mode)
848 port = filp->private_data;
849 return fasync_helper(fd, filp, mode, &port->async_queue);
853 * The file operations that we support: programs in the guest can open
854 * a console device, read from it, write to it, poll for data and
855 * close it. The devices are at
856 * /dev/vport<device number>p<port number>
858 static const struct file_operations port_fops = {
859 .owner = THIS_MODULE,
860 .open = port_fops_open,
861 .read = port_fops_read,
862 .write = port_fops_write,
863 .poll = port_fops_poll,
864 .release = port_fops_release,
865 .fasync = port_fops_fasync,
870 * The put_chars() callback is pretty straightforward.
872 * We turn the characters into a scatter-gather list, add it to the
873 * output queue and then kick the Host. Then we sit here waiting for
874 * it to finish: inefficient in theory, but in practice
875 * implementations will do it immediately (lguest's Launcher does).
877 static int put_chars(u32 vtermno, const char *buf, int count)
881 if (unlikely(early_put_chars))
882 return early_put_chars(vtermno, buf, count);
884 port = find_port_by_vtermno(vtermno);
888 return send_buf(port, (void *)buf, count, false);
892 * get_chars() is the callback from the hvc_console infrastructure
893 * when an interrupt is received.
895 * We call out to fill_readbuf that gets us the required data from the
896 * buffers that are queued up.
898 static int get_chars(u32 vtermno, char *buf, int count)
902 /* If we've not set up the port yet, we have no input to give. */
903 if (unlikely(early_put_chars))
906 port = find_port_by_vtermno(vtermno);
910 /* If we don't have an input queue yet, we can't get input. */
911 BUG_ON(!port->in_vq);
913 return fill_readbuf(port, buf, count, false);
916 static void resize_console(struct port *port)
918 struct virtio_device *vdev;
920 /* The port could have been hot-unplugged */
921 if (!port || !is_console_port(port))
924 vdev = port->portdev->vdev;
925 if (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE))
926 hvc_resize(port->cons.hvc, port->cons.ws);
929 /* We set the configuration at this point, since we now have a tty */
930 static int notifier_add_vio(struct hvc_struct *hp, int data)
934 port = find_port_by_vtermno(hp->vtermno);
938 hp->irq_requested = 1;
939 resize_console(port);
944 static void notifier_del_vio(struct hvc_struct *hp, int data)
946 hp->irq_requested = 0;
949 /* The operations for console ports. */
950 static const struct hv_ops hv_ops = {
951 .get_chars = get_chars,
952 .put_chars = put_chars,
953 .notifier_add = notifier_add_vio,
954 .notifier_del = notifier_del_vio,
955 .notifier_hangup = notifier_del_vio,
959 * Console drivers are initialized very early so boot messages can go
960 * out, so we do things slightly differently from the generic virtio
961 * initialization of the net and block drivers.
963 * At this stage, the console is output-only. It's too early to set
964 * up a virtqueue, so we let the drivers do some boutique early-output
967 int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int))
969 early_put_chars = put_chars;
970 return hvc_instantiate(0, 0, &hv_ops);
973 int init_port_console(struct port *port)
978 * The Host's telling us this port is a console port. Hook it
979 * up with an hvc console.
981 * To set up and manage our virtual console, we call
984 * The first argument of hvc_alloc() is the virtual console
985 * number. The second argument is the parameter for the
986 * notification mechanism (like irq number). We currently
987 * leave this as zero, virtqueues have implicit notifications.
989 * The third argument is a "struct hv_ops" containing the
990 * put_chars() get_chars(), notifier_add() and notifier_del()
991 * pointers. The final argument is the output buffer size: we
992 * can do any size, so we put PAGE_SIZE here.
994 port->cons.vtermno = pdrvdata.next_vtermno;
996 port->cons.hvc = hvc_alloc(port->cons.vtermno, 0, &hv_ops, PAGE_SIZE);
997 if (IS_ERR(port->cons.hvc)) {
998 ret = PTR_ERR(port->cons.hvc);
1000 "error %d allocating hvc for port\n", ret);
1001 port->cons.hvc = NULL;
1004 spin_lock_irq(&pdrvdata_lock);
1005 pdrvdata.next_vtermno++;
1006 list_add_tail(&port->cons.list, &pdrvdata.consoles);
1007 spin_unlock_irq(&pdrvdata_lock);
1008 port->guest_connected = true;
1011 * Start using the new console output if this is the first
1012 * console to come up.
1014 if (early_put_chars)
1015 early_put_chars = NULL;
1017 /* Notify host of port being opened */
1018 send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
1023 static ssize_t show_port_name(struct device *dev,
1024 struct device_attribute *attr, char *buffer)
1028 port = dev_get_drvdata(dev);
1030 return sprintf(buffer, "%s\n", port->name);
1033 static DEVICE_ATTR(name, S_IRUGO, show_port_name, NULL);
1035 static struct attribute *port_sysfs_entries[] = {
1036 &dev_attr_name.attr,
1040 static struct attribute_group port_attribute_group = {
1041 .name = NULL, /* put in device directory */
1042 .attrs = port_sysfs_entries,
1045 static int debugfs_open(struct inode *inode, struct file *filp)
1047 filp->private_data = inode->i_private;
1051 static ssize_t debugfs_read(struct file *filp, char __user *ubuf,
1052 size_t count, loff_t *offp)
1056 ssize_t ret, out_offset, out_count;
1059 buf = kmalloc(out_count, GFP_KERNEL);
1063 port = filp->private_data;
1065 out_offset += snprintf(buf + out_offset, out_count,
1066 "name: %s\n", port->name ? port->name : "");
1067 out_offset += snprintf(buf + out_offset, out_count - out_offset,
1068 "guest_connected: %d\n", port->guest_connected);
1069 out_offset += snprintf(buf + out_offset, out_count - out_offset,
1070 "host_connected: %d\n", port->host_connected);
1071 out_offset += snprintf(buf + out_offset, out_count - out_offset,
1072 "outvq_full: %d\n", port->outvq_full);
1073 out_offset += snprintf(buf + out_offset, out_count - out_offset,
1074 "bytes_sent: %lu\n", port->stats.bytes_sent);
1075 out_offset += snprintf(buf + out_offset, out_count - out_offset,
1076 "bytes_received: %lu\n",
1077 port->stats.bytes_received);
1078 out_offset += snprintf(buf + out_offset, out_count - out_offset,
1079 "bytes_discarded: %lu\n",
1080 port->stats.bytes_discarded);
1081 out_offset += snprintf(buf + out_offset, out_count - out_offset,
1083 is_console_port(port) ? "yes" : "no");
1084 out_offset += snprintf(buf + out_offset, out_count - out_offset,
1085 "console_vtermno: %u\n", port->cons.vtermno);
1087 ret = simple_read_from_buffer(ubuf, count, offp, buf, out_offset);
1092 static const struct file_operations port_debugfs_ops = {
1093 .owner = THIS_MODULE,
1094 .open = debugfs_open,
1095 .read = debugfs_read,
1098 static void set_console_size(struct port *port, u16 rows, u16 cols)
1100 if (!port || !is_console_port(port))
1103 port->cons.ws.ws_row = rows;
1104 port->cons.ws.ws_col = cols;
1107 static unsigned int fill_queue(struct virtqueue *vq, spinlock_t *lock)
1109 struct port_buffer *buf;
1110 unsigned int nr_added_bufs;
1115 buf = alloc_buf(PAGE_SIZE);
1119 spin_lock_irq(lock);
1120 ret = add_inbuf(vq, buf);
1122 spin_unlock_irq(lock);
1127 spin_unlock_irq(lock);
1130 return nr_added_bufs;
1133 static void send_sigio_to_port(struct port *port)
1135 if (port->async_queue && port->guest_connected)
1136 kill_fasync(&port->async_queue, SIGIO, POLL_OUT);
1139 static int add_port(struct ports_device *portdev, u32 id)
1141 char debugfs_name[16];
1143 struct port_buffer *buf;
1145 unsigned int nr_added_bufs;
1148 port = kmalloc(sizeof(*port), GFP_KERNEL);
1153 kref_init(&port->kref);
1155 port->portdev = portdev;
1160 port->cons.hvc = NULL;
1161 port->async_queue = NULL;
1163 port->cons.ws.ws_row = port->cons.ws.ws_col = 0;
1165 port->host_connected = port->guest_connected = false;
1166 port->stats = (struct port_stats) { 0 };
1168 port->outvq_full = false;
1170 port->in_vq = portdev->in_vqs[port->id];
1171 port->out_vq = portdev->out_vqs[port->id];
1173 port->cdev = cdev_alloc();
1175 dev_err(&port->portdev->vdev->dev, "Error allocating cdev\n");
1179 port->cdev->ops = &port_fops;
1181 devt = MKDEV(portdev->chr_major, id);
1182 err = cdev_add(port->cdev, devt, 1);
1184 dev_err(&port->portdev->vdev->dev,
1185 "Error %d adding cdev for port %u\n", err, id);
1188 port->dev = device_create(pdrvdata.class, &port->portdev->vdev->dev,
1189 devt, port, "vport%up%u",
1190 port->portdev->drv_index, id);
1191 if (IS_ERR(port->dev)) {
1192 err = PTR_ERR(port->dev);
1193 dev_err(&port->portdev->vdev->dev,
1194 "Error %d creating device for port %u\n",
1199 spin_lock_init(&port->inbuf_lock);
1200 spin_lock_init(&port->outvq_lock);
1201 init_waitqueue_head(&port->waitqueue);
1203 /* Fill the in_vq with buffers so the host can send us data. */
1204 nr_added_bufs = fill_queue(port->in_vq, &port->inbuf_lock);
1205 if (!nr_added_bufs) {
1206 dev_err(port->dev, "Error allocating inbufs\n");
1212 * If we're not using multiport support, this has to be a console port
1214 if (!use_multiport(port->portdev)) {
1215 err = init_port_console(port);
1220 spin_lock_irq(&portdev->ports_lock);
1221 list_add_tail(&port->list, &port->portdev->ports);
1222 spin_unlock_irq(&portdev->ports_lock);
1225 * Tell the Host we're set so that it can send us various
1226 * configuration parameters for this port (eg, port name,
1227 * caching, whether this is a console port, etc.)
1229 send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1231 if (pdrvdata.debugfs_dir) {
1233 * Finally, create the debugfs file that we can use to
1234 * inspect a port's state at any time
1236 sprintf(debugfs_name, "vport%up%u",
1237 port->portdev->drv_index, id);
1238 port->debugfs_file = debugfs_create_file(debugfs_name, 0444,
1239 pdrvdata.debugfs_dir,
1246 while ((buf = virtqueue_detach_unused_buf(port->in_vq)))
1249 device_destroy(pdrvdata.class, port->dev->devt);
1251 cdev_del(port->cdev);
1255 /* The host might want to notify management sw about port add failure */
1256 __send_control_msg(portdev, id, VIRTIO_CONSOLE_PORT_READY, 0);
1260 /* No users remain, remove all port-specific data. */
1261 static void remove_port(struct kref *kref)
1265 port = container_of(kref, struct port, kref);
1267 sysfs_remove_group(&port->dev->kobj, &port_attribute_group);
1268 device_destroy(pdrvdata.class, port->dev->devt);
1269 cdev_del(port->cdev);
1273 debugfs_remove(port->debugfs_file);
1279 * Port got unplugged. Remove port from portdev's list and drop the
1280 * kref reference. If no userspace has this port opened, it will
1281 * result in immediate removal the port.
1283 static void unplug_port(struct port *port)
1285 struct port_buffer *buf;
1287 spin_lock_irq(&port->portdev->ports_lock);
1288 list_del(&port->list);
1289 spin_unlock_irq(&port->portdev->ports_lock);
1291 if (port->guest_connected) {
1292 port->guest_connected = false;
1293 port->host_connected = false;
1294 wake_up_interruptible(&port->waitqueue);
1296 /* Let the app know the port is going down. */
1297 send_sigio_to_port(port);
1300 if (is_console_port(port)) {
1301 spin_lock_irq(&pdrvdata_lock);
1302 list_del(&port->cons.list);
1303 spin_unlock_irq(&pdrvdata_lock);
1304 hvc_remove(port->cons.hvc);
1307 /* Remove unused data this port might have received. */
1308 discard_port_data(port);
1310 reclaim_consumed_buffers(port);
1312 /* Remove buffers we queued up for the Host to send us data in. */
1313 while ((buf = virtqueue_detach_unused_buf(port->in_vq)))
1317 * We should just assume the device itself has gone off --
1318 * else a close on an open port later will try to send out a
1321 port->portdev = NULL;
1324 * Locks around here are not necessary - a port can't be
1325 * opened after we removed the port struct from ports_list
1328 kref_put(&port->kref, remove_port);
1331 /* Any private messages that the Host and Guest want to share */
1332 static void handle_control_message(struct ports_device *portdev,
1333 struct port_buffer *buf)
1335 struct virtio_console_control *cpkt;
1340 cpkt = (struct virtio_console_control *)(buf->buf + buf->offset);
1342 port = find_port_by_id(portdev, cpkt->id);
1343 if (!port && cpkt->event != VIRTIO_CONSOLE_PORT_ADD) {
1344 /* No valid header at start of buffer. Drop it. */
1345 dev_dbg(&portdev->vdev->dev,
1346 "Invalid index %u in control packet\n", cpkt->id);
1350 switch (cpkt->event) {
1351 case VIRTIO_CONSOLE_PORT_ADD:
1353 dev_dbg(&portdev->vdev->dev,
1354 "Port %u already added\n", port->id);
1355 send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1358 if (cpkt->id >= portdev->config.max_nr_ports) {
1359 dev_warn(&portdev->vdev->dev,
1360 "Request for adding port with out-of-bound id %u, max. supported id: %u\n",
1361 cpkt->id, portdev->config.max_nr_ports - 1);
1364 add_port(portdev, cpkt->id);
1366 case VIRTIO_CONSOLE_PORT_REMOVE:
1369 case VIRTIO_CONSOLE_CONSOLE_PORT:
1372 if (is_console_port(port))
1375 init_port_console(port);
1376 complete(&early_console_added);
1378 * Could remove the port here in case init fails - but
1379 * have to notify the host first.
1382 case VIRTIO_CONSOLE_RESIZE: {
1388 if (!is_console_port(port))
1391 memcpy(&size, buf->buf + buf->offset + sizeof(*cpkt),
1393 set_console_size(port, size.rows, size.cols);
1395 port->cons.hvc->irq_requested = 1;
1396 resize_console(port);
1399 case VIRTIO_CONSOLE_PORT_OPEN:
1400 port->host_connected = cpkt->value;
1401 wake_up_interruptible(&port->waitqueue);
1403 * If the host port got closed and the host had any
1404 * unconsumed buffers, we'll be able to reclaim them
1407 spin_lock_irq(&port->outvq_lock);
1408 reclaim_consumed_buffers(port);
1409 spin_unlock_irq(&port->outvq_lock);
1412 * If the guest is connected, it'll be interested in
1413 * knowing the host connection state changed.
1415 send_sigio_to_port(port);
1417 case VIRTIO_CONSOLE_PORT_NAME:
1419 * If we woke up after hibernation, we can get this
1420 * again. Skip it in that case.
1426 * Skip the size of the header and the cpkt to get the size
1427 * of the name that was sent
1429 name_size = buf->len - buf->offset - sizeof(*cpkt) + 1;
1431 port->name = kmalloc(name_size, GFP_KERNEL);
1434 "Not enough space to store port name\n");
1437 strncpy(port->name, buf->buf + buf->offset + sizeof(*cpkt),
1439 port->name[name_size - 1] = 0;
1442 * Since we only have one sysfs attribute, 'name',
1443 * create it only if we have a name for the port.
1445 err = sysfs_create_group(&port->dev->kobj,
1446 &port_attribute_group);
1449 "Error %d creating sysfs device attributes\n",
1453 * Generate a udev event so that appropriate
1454 * symlinks can be created based on udev
1457 kobject_uevent(&port->dev->kobj, KOBJ_CHANGE);
1463 static void control_work_handler(struct work_struct *work)
1465 struct ports_device *portdev;
1466 struct virtqueue *vq;
1467 struct port_buffer *buf;
1470 portdev = container_of(work, struct ports_device, control_work);
1471 vq = portdev->c_ivq;
1473 spin_lock(&portdev->c_ivq_lock);
1474 while ((buf = virtqueue_get_buf(vq, &len))) {
1475 spin_unlock(&portdev->c_ivq_lock);
1480 handle_control_message(portdev, buf);
1482 spin_lock(&portdev->c_ivq_lock);
1483 if (add_inbuf(portdev->c_ivq, buf) < 0) {
1484 dev_warn(&portdev->vdev->dev,
1485 "Error adding buffer to queue\n");
1489 spin_unlock(&portdev->c_ivq_lock);
1492 static void out_intr(struct virtqueue *vq)
1496 port = find_port_by_vq(vq->vdev->priv, vq);
1500 wake_up_interruptible(&port->waitqueue);
1503 static void in_intr(struct virtqueue *vq)
1506 unsigned long flags;
1508 port = find_port_by_vq(vq->vdev->priv, vq);
1512 spin_lock_irqsave(&port->inbuf_lock, flags);
1513 port->inbuf = get_inbuf(port);
1516 * Don't queue up data when port is closed. This condition
1517 * can be reached when a console port is not yet connected (no
1518 * tty is spawned) and the host sends out data to console
1519 * ports. For generic serial ports, the host won't
1520 * (shouldn't) send data till the guest is connected.
1522 if (!port->guest_connected)
1523 discard_port_data(port);
1525 spin_unlock_irqrestore(&port->inbuf_lock, flags);
1527 wake_up_interruptible(&port->waitqueue);
1529 /* Send a SIGIO indicating new data in case the process asked for it */
1530 send_sigio_to_port(port);
1532 if (is_console_port(port) && hvc_poll(port->cons.hvc))
1536 static void control_intr(struct virtqueue *vq)
1538 struct ports_device *portdev;
1540 portdev = vq->vdev->priv;
1541 schedule_work(&portdev->control_work);
1544 static void config_intr(struct virtio_device *vdev)
1546 struct ports_device *portdev;
1548 portdev = vdev->priv;
1550 if (!use_multiport(portdev)) {
1554 vdev->config->get(vdev,
1555 offsetof(struct virtio_console_config, cols),
1556 &cols, sizeof(u16));
1557 vdev->config->get(vdev,
1558 offsetof(struct virtio_console_config, rows),
1559 &rows, sizeof(u16));
1561 port = find_port_by_id(portdev, 0);
1562 set_console_size(port, rows, cols);
1565 * We'll use this way of resizing only for legacy
1566 * support. For newer userspace
1567 * (VIRTIO_CONSOLE_F_MULTPORT+), use control messages
1568 * to indicate console size changes so that it can be
1571 resize_console(port);
1575 static int init_vqs(struct ports_device *portdev)
1577 vq_callback_t **io_callbacks;
1579 struct virtqueue **vqs;
1580 u32 i, j, nr_ports, nr_queues;
1583 nr_ports = portdev->config.max_nr_ports;
1584 nr_queues = use_multiport(portdev) ? (nr_ports + 1) * 2 : 2;
1586 vqs = kmalloc(nr_queues * sizeof(struct virtqueue *), GFP_KERNEL);
1587 io_callbacks = kmalloc(nr_queues * sizeof(vq_callback_t *), GFP_KERNEL);
1588 io_names = kmalloc(nr_queues * sizeof(char *), GFP_KERNEL);
1589 portdev->in_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
1591 portdev->out_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
1593 if (!vqs || !io_callbacks || !io_names || !portdev->in_vqs ||
1594 !portdev->out_vqs) {
1600 * For backward compat (newer host but older guest), the host
1601 * spawns a console port first and also inits the vqs for port
1605 io_callbacks[j] = in_intr;
1606 io_callbacks[j + 1] = out_intr;
1607 io_names[j] = "input";
1608 io_names[j + 1] = "output";
1611 if (use_multiport(portdev)) {
1612 io_callbacks[j] = control_intr;
1613 io_callbacks[j + 1] = NULL;
1614 io_names[j] = "control-i";
1615 io_names[j + 1] = "control-o";
1617 for (i = 1; i < nr_ports; i++) {
1619 io_callbacks[j] = in_intr;
1620 io_callbacks[j + 1] = out_intr;
1621 io_names[j] = "input";
1622 io_names[j + 1] = "output";
1625 /* Find the queues. */
1626 err = portdev->vdev->config->find_vqs(portdev->vdev, nr_queues, vqs,
1628 (const char **)io_names);
1633 portdev->in_vqs[0] = vqs[0];
1634 portdev->out_vqs[0] = vqs[1];
1636 if (use_multiport(portdev)) {
1637 portdev->c_ivq = vqs[j];
1638 portdev->c_ovq = vqs[j + 1];
1640 for (i = 1; i < nr_ports; i++) {
1642 portdev->in_vqs[i] = vqs[j];
1643 portdev->out_vqs[i] = vqs[j + 1];
1647 kfree(io_callbacks);
1653 kfree(portdev->out_vqs);
1654 kfree(portdev->in_vqs);
1656 kfree(io_callbacks);
1662 static const struct file_operations portdev_fops = {
1663 .owner = THIS_MODULE,
1667 * Once we're further in boot, we get probed like any other virtio
1670 * If the host also supports multiple console ports, we check the
1671 * config space to see how many ports the host has spawned. We
1672 * initialize each port found.
1674 static int __devinit virtcons_probe(struct virtio_device *vdev)
1676 struct ports_device *portdev;
1679 bool early = early_put_chars != NULL;
1681 /* Ensure to read early_put_chars now */
1684 portdev = kmalloc(sizeof(*portdev), GFP_KERNEL);
1690 /* Attach this portdev to this virtio_device, and vice-versa. */
1691 portdev->vdev = vdev;
1692 vdev->priv = portdev;
1694 spin_lock_irq(&pdrvdata_lock);
1695 portdev->drv_index = pdrvdata.index++;
1696 spin_unlock_irq(&pdrvdata_lock);
1698 portdev->chr_major = register_chrdev(0, "virtio-portsdev",
1700 if (portdev->chr_major < 0) {
1702 "Error %d registering chrdev for device %u\n",
1703 portdev->chr_major, portdev->drv_index);
1704 err = portdev->chr_major;
1709 portdev->config.max_nr_ports = 1;
1710 if (virtio_config_val(vdev, VIRTIO_CONSOLE_F_MULTIPORT,
1711 offsetof(struct virtio_console_config,
1713 &portdev->config.max_nr_ports) == 0)
1716 err = init_vqs(portdev);
1718 dev_err(&vdev->dev, "Error %d initializing vqs\n", err);
1722 spin_lock_init(&portdev->ports_lock);
1723 INIT_LIST_HEAD(&portdev->ports);
1726 unsigned int nr_added_bufs;
1728 spin_lock_init(&portdev->c_ivq_lock);
1729 spin_lock_init(&portdev->c_ovq_lock);
1730 INIT_WORK(&portdev->control_work, &control_work_handler);
1732 nr_added_bufs = fill_queue(portdev->c_ivq,
1733 &portdev->c_ivq_lock);
1734 if (!nr_added_bufs) {
1736 "Error allocating buffers for control queue\n");
1742 * For backward compatibility: Create a console port
1743 * if we're running on older host.
1745 add_port(portdev, 0);
1748 spin_lock_irq(&pdrvdata_lock);
1749 list_add_tail(&portdev->list, &pdrvdata.portdevs);
1750 spin_unlock_irq(&pdrvdata_lock);
1752 __send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
1753 VIRTIO_CONSOLE_DEVICE_READY, 1);
1756 * If there was an early virtio console, assume that there are no
1757 * other consoles. We need to wait until the hvc_alloc matches the
1758 * hvc_instantiate, otherwise tty_open will complain, resulting in
1759 * a "Warning: unable to open an initial console" boot failure.
1760 * Without multiport this is done in add_port above. With multiport
1761 * this might take some host<->guest communication - thus we have to
1764 if (multiport && early)
1765 wait_for_completion(&early_console_added);
1770 /* The host might want to notify mgmt sw about device add failure */
1771 __send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
1772 VIRTIO_CONSOLE_DEVICE_READY, 0);
1773 vdev->config->del_vqs(vdev);
1774 kfree(portdev->in_vqs);
1775 kfree(portdev->out_vqs);
1777 unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1784 static void virtcons_remove(struct virtio_device *vdev)
1786 struct ports_device *portdev;
1787 struct port *port, *port2;
1789 portdev = vdev->priv;
1791 spin_lock_irq(&pdrvdata_lock);
1792 list_del(&portdev->list);
1793 spin_unlock_irq(&pdrvdata_lock);
1795 /* Disable interrupts for vqs */
1796 vdev->config->reset(vdev);
1797 /* Finish up work that's lined up */
1798 if (use_multiport(portdev))
1799 cancel_work_sync(&portdev->control_work);
1801 list_for_each_entry_safe(port, port2, &portdev->ports, list)
1804 unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1807 * When yanking out a device, we immediately lose the
1808 * (device-side) queues. So there's no point in keeping the
1809 * guest side around till we drop our final reference. This
1810 * also means that any ports which are in an open state will
1811 * have to just stop using the port, as the vqs are going
1814 if (use_multiport(portdev)) {
1815 struct port_buffer *buf;
1818 while ((buf = virtqueue_get_buf(portdev->c_ivq, &len)))
1821 while ((buf = virtqueue_detach_unused_buf(portdev->c_ivq)))
1825 vdev->config->del_vqs(vdev);
1826 kfree(portdev->in_vqs);
1827 kfree(portdev->out_vqs);
1832 static struct virtio_device_id id_table[] = {
1833 { VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID },
1837 static unsigned int features[] = {
1838 VIRTIO_CONSOLE_F_SIZE,
1839 VIRTIO_CONSOLE_F_MULTIPORT,
1842 static struct virtio_driver virtio_console = {
1843 .feature_table = features,
1844 .feature_table_size = ARRAY_SIZE(features),
1845 .driver.name = KBUILD_MODNAME,
1846 .driver.owner = THIS_MODULE,
1847 .id_table = id_table,
1848 .probe = virtcons_probe,
1849 .remove = virtcons_remove,
1850 .config_changed = config_intr,
1853 static int __init init(void)
1857 pdrvdata.class = class_create(THIS_MODULE, "virtio-ports");
1858 if (IS_ERR(pdrvdata.class)) {
1859 err = PTR_ERR(pdrvdata.class);
1860 pr_err("Error %d creating virtio-ports class\n", err);
1864 pdrvdata.debugfs_dir = debugfs_create_dir("virtio-ports", NULL);
1865 if (!pdrvdata.debugfs_dir) {
1866 pr_warning("Error %ld creating debugfs dir for virtio-ports\n",
1867 PTR_ERR(pdrvdata.debugfs_dir));
1869 INIT_LIST_HEAD(&pdrvdata.consoles);
1870 INIT_LIST_HEAD(&pdrvdata.portdevs);
1872 return register_virtio_driver(&virtio_console);
1875 static void __exit fini(void)
1877 unregister_virtio_driver(&virtio_console);
1879 class_destroy(pdrvdata.class);
1880 if (pdrvdata.debugfs_dir)
1881 debugfs_remove_recursive(pdrvdata.debugfs_dir);
1886 MODULE_DEVICE_TABLE(virtio, id_table);
1887 MODULE_DESCRIPTION("Virtio console driver");
1888 MODULE_LICENSE("GPL");