1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2006, 2007, 2009 Rusty Russell, IBM Corporation
4 * Copyright (C) 2009, 2010, 2011 Red Hat, Inc.
5 * Copyright (C) 2009, 2010, 2011 Amit Shah <amit.shah@redhat.com>
7 #include <linux/cdev.h>
8 #include <linux/debugfs.h>
9 #include <linux/completion.h>
10 #include <linux/device.h>
11 #include <linux/err.h>
12 #include <linux/freezer.h>
14 #include <linux/splice.h>
15 #include <linux/pagemap.h>
16 #include <linux/init.h>
17 #include <linux/list.h>
18 #include <linux/poll.h>
19 #include <linux/sched.h>
20 #include <linux/slab.h>
21 #include <linux/spinlock.h>
22 #include <linux/virtio.h>
23 #include <linux/virtio_console.h>
24 #include <linux/wait.h>
25 #include <linux/workqueue.h>
26 #include <linux/module.h>
27 #include <linux/dma-mapping.h>
28 #include "../tty/hvc/hvc_console.h"
30 #define is_rproc_enabled IS_ENABLED(CONFIG_REMOTEPROC)
31 #define VIRTCONS_MAX_PORTS 0x8000
34 * This is a global struct for storing common data for all the devices
35 * this driver handles.
37 * Mainly, it has a linked list for all the consoles in one place so
38 * that callbacks from hvc for get_chars(), put_chars() work properly
39 * across multiple devices and multiple ports per device.
41 struct ports_driver_data {
42 /* Used for registering chardevs */
45 /* Used for exporting per-port information to debugfs */
46 struct dentry *debugfs_dir;
48 /* List of all the devices we're handling */
49 struct list_head portdevs;
52 * This is used to keep track of the number of hvc consoles
53 * spawned by this driver. This number is given as the first
54 * argument to hvc_alloc(). To correctly map an initial
55 * console spawned via hvc_instantiate to the console being
56 * hooked up via hvc_alloc, we need to pass the same vtermno.
58 * We also just assume the first console being initialised was
59 * the first one that got used as the initial console.
61 unsigned int next_vtermno;
63 /* All the console devices handled by this driver */
64 struct list_head consoles;
66 static struct ports_driver_data pdrvdata = { .next_vtermno = 1};
68 static DEFINE_SPINLOCK(pdrvdata_lock);
69 static DECLARE_COMPLETION(early_console_added);
71 /* This struct holds information that's relevant only for console ports */
73 /* We'll place all consoles in a list in the pdrvdata struct */
74 struct list_head list;
76 /* The hvc device associated with this console port */
77 struct hvc_struct *hvc;
79 /* The size of the console */
83 * This number identifies the number that we used to register
84 * with hvc in hvc_instantiate() and hvc_alloc(); this is the
85 * number passed on by the hvc callbacks to us to
86 * differentiate between the other console ports handled by
95 /* size of the buffer in *buf above */
98 /* used length of the buffer */
100 /* offset in the buf from which to consume data */
103 /* DMA address of buffer */
106 /* Device we got DMA memory from */
109 /* List of pending dma buffers to free */
110 struct list_head list;
112 /* If sgpages == 0 then buf is used */
113 unsigned int sgpages;
115 /* sg is used if spages > 0. sg must be the last in is struct */
116 struct scatterlist sg[];
120 * This is a per-device struct that stores data common to all the
121 * ports for that device (vdev->priv).
123 struct ports_device {
124 /* Next portdev in the list, head is in the pdrvdata struct */
125 struct list_head list;
128 * Workqueue handlers where we process deferred work after
131 struct work_struct control_work;
132 struct work_struct config_work;
134 struct list_head ports;
136 /* To protect the list of ports */
137 spinlock_t ports_lock;
139 /* To protect the vq operations for the control channel */
140 spinlock_t c_ivq_lock;
141 spinlock_t c_ovq_lock;
143 /* max. number of ports this device can hold */
146 /* The virtio device we're associated with */
147 struct virtio_device *vdev;
150 * A couple of virtqueues for the control channel: one for
151 * guest->host transfers, one for host->guest transfers
153 struct virtqueue *c_ivq, *c_ovq;
156 * A control packet buffer for guest->host requests, protected
159 struct virtio_console_control cpkt;
161 /* Array of per-port IO virtqueues */
162 struct virtqueue **in_vqs, **out_vqs;
164 /* Major number for this device. Ports will be created as minors. */
169 unsigned long bytes_sent, bytes_received, bytes_discarded;
172 /* This struct holds the per-port data */
174 /* Next port in the list, head is in the ports_device */
175 struct list_head list;
177 /* Pointer to the parent virtio_console device */
178 struct ports_device *portdev;
180 /* The current buffer from which data has to be fed to readers */
181 struct port_buffer *inbuf;
184 * To protect the operations on the in_vq associated with this
185 * port. Has to be a spinlock because it can be called from
186 * interrupt context (get_char()).
188 spinlock_t inbuf_lock;
190 /* Protect the operations on the out_vq. */
191 spinlock_t outvq_lock;
193 /* The IO vqs for this port */
194 struct virtqueue *in_vq, *out_vq;
196 /* File in the debugfs directory that exposes this port's information */
197 struct dentry *debugfs_file;
200 * Keep count of the bytes sent, received and discarded for
201 * this port for accounting and debugging purposes. These
202 * counts are not reset across port open / close events.
204 struct port_stats stats;
207 * The entries in this struct will be valid if this port is
208 * hooked up to an hvc console
212 /* Each port associates with a separate char device */
216 /* Reference-counting to handle port hot-unplugs and file operations */
219 /* A waitqueue for poll() or blocking read operations */
220 wait_queue_head_t waitqueue;
222 /* The 'name' of the port that we expose via sysfs properties */
225 /* We can notify apps of host connect / disconnect events via SIGIO */
226 struct fasync_struct *async_queue;
228 /* The 'id' to identify the port with the Host */
233 /* Is the host device open */
236 /* We should allow only one process to open a port */
237 bool guest_connected;
240 /* This is the very early arch-specified put chars function. */
241 static int (*early_put_chars)(u32, const char *, int);
243 static struct port *find_port_by_vtermno(u32 vtermno)
246 struct console *cons;
249 spin_lock_irqsave(&pdrvdata_lock, flags);
250 list_for_each_entry(cons, &pdrvdata.consoles, list) {
251 if (cons->vtermno == vtermno) {
252 port = container_of(cons, struct port, cons);
258 spin_unlock_irqrestore(&pdrvdata_lock, flags);
262 static struct port *find_port_by_devt_in_portdev(struct ports_device *portdev,
268 spin_lock_irqsave(&portdev->ports_lock, flags);
269 list_for_each_entry(port, &portdev->ports, list) {
270 if (port->cdev->dev == dev) {
271 kref_get(&port->kref);
277 spin_unlock_irqrestore(&portdev->ports_lock, flags);
282 static struct port *find_port_by_devt(dev_t dev)
284 struct ports_device *portdev;
288 spin_lock_irqsave(&pdrvdata_lock, flags);
289 list_for_each_entry(portdev, &pdrvdata.portdevs, list) {
290 port = find_port_by_devt_in_portdev(portdev, dev);
296 spin_unlock_irqrestore(&pdrvdata_lock, flags);
300 static struct port *find_port_by_id(struct ports_device *portdev, u32 id)
305 spin_lock_irqsave(&portdev->ports_lock, flags);
306 list_for_each_entry(port, &portdev->ports, list)
311 spin_unlock_irqrestore(&portdev->ports_lock, flags);
316 static struct port *find_port_by_vq(struct ports_device *portdev,
317 struct virtqueue *vq)
322 spin_lock_irqsave(&portdev->ports_lock, flags);
323 list_for_each_entry(port, &portdev->ports, list)
324 if (port->in_vq == vq || port->out_vq == vq)
328 spin_unlock_irqrestore(&portdev->ports_lock, flags);
332 static bool is_console_port(struct port *port)
339 static bool is_rproc_serial(const struct virtio_device *vdev)
341 return is_rproc_enabled && vdev->id.device == VIRTIO_ID_RPROC_SERIAL;
344 static inline bool use_multiport(struct ports_device *portdev)
347 * This condition can be true when put_chars is called from
352 return __virtio_test_bit(portdev->vdev, VIRTIO_CONSOLE_F_MULTIPORT);
355 static DEFINE_SPINLOCK(dma_bufs_lock);
356 static LIST_HEAD(pending_free_dma_bufs);
358 static void free_buf(struct port_buffer *buf, bool can_sleep)
362 for (i = 0; i < buf->sgpages; i++) {
363 struct page *page = sg_page(&buf->sg[i]);
371 } else if (is_rproc_enabled) {
374 /* dma_free_coherent requires interrupts to be enabled. */
376 /* queue up dma-buffers to be freed later */
377 spin_lock_irqsave(&dma_bufs_lock, flags);
378 list_add_tail(&buf->list, &pending_free_dma_bufs);
379 spin_unlock_irqrestore(&dma_bufs_lock, flags);
382 dma_free_coherent(buf->dev, buf->size, buf->buf, buf->dma);
384 /* Release device refcnt and allow it to be freed */
385 put_device(buf->dev);
391 static void reclaim_dma_bufs(void)
394 struct port_buffer *buf, *tmp;
397 if (list_empty(&pending_free_dma_bufs))
400 /* Create a copy of the pending_free_dma_bufs while holding the lock */
401 spin_lock_irqsave(&dma_bufs_lock, flags);
402 list_cut_position(&tmp_list, &pending_free_dma_bufs,
403 pending_free_dma_bufs.prev);
404 spin_unlock_irqrestore(&dma_bufs_lock, flags);
406 /* Release the dma buffers, without irqs enabled */
407 list_for_each_entry_safe(buf, tmp, &tmp_list, list) {
408 list_del(&buf->list);
413 static struct port_buffer *alloc_buf(struct virtio_device *vdev, size_t buf_size,
416 struct port_buffer *buf;
421 * Allocate buffer and the sg list. The sg list array is allocated
422 * directly after the port_buffer struct.
424 buf = kmalloc(struct_size(buf, sg, pages), GFP_KERNEL);
428 buf->sgpages = pages;
435 if (is_rproc_serial(vdev)) {
437 * Allocate DMA memory from ancestor. When a virtio
438 * device is created by remoteproc, the DMA memory is
439 * associated with the parent device:
440 * virtioY => remoteprocX#vdevYbuffer.
442 buf->dev = vdev->dev.parent;
446 /* Increase device refcnt to avoid freeing it */
447 get_device(buf->dev);
448 buf->buf = dma_alloc_coherent(buf->dev, buf_size, &buf->dma,
452 buf->buf = kmalloc(buf_size, GFP_KERNEL);
459 buf->size = buf_size;
468 /* Callers should take appropriate locks */
469 static struct port_buffer *get_inbuf(struct port *port)
471 struct port_buffer *buf;
477 buf = virtqueue_get_buf(port->in_vq, &len);
479 buf->len = min_t(size_t, len, buf->size);
481 port->stats.bytes_received += len;
487 * Create a scatter-gather list representing our input buffer and put
490 * Callers should take appropriate locks.
492 static int add_inbuf(struct virtqueue *vq, struct port_buffer *buf)
494 struct scatterlist sg[1];
497 sg_init_one(sg, buf->buf, buf->size);
499 ret = virtqueue_add_inbuf(vq, sg, 1, buf, GFP_ATOMIC);
506 /* Discard any unread data this port has. Callers lockers. */
507 static void discard_port_data(struct port *port)
509 struct port_buffer *buf;
512 if (!port->portdev) {
513 /* Device has been unplugged. vqs are already gone. */
516 buf = get_inbuf(port);
520 port->stats.bytes_discarded += buf->len - buf->offset;
521 if (add_inbuf(port->in_vq, buf) < 0) {
523 free_buf(buf, false);
526 buf = get_inbuf(port);
529 dev_warn(port->dev, "Errors adding %d buffers back to vq\n",
533 static bool port_has_data(struct port *port)
539 spin_lock_irqsave(&port->inbuf_lock, flags);
540 port->inbuf = get_inbuf(port);
544 spin_unlock_irqrestore(&port->inbuf_lock, flags);
548 static ssize_t __send_control_msg(struct ports_device *portdev, u32 port_id,
549 unsigned int event, unsigned int value)
551 struct scatterlist sg[1];
552 struct virtqueue *vq;
555 if (!use_multiport(portdev))
560 spin_lock(&portdev->c_ovq_lock);
562 portdev->cpkt.id = cpu_to_virtio32(portdev->vdev, port_id);
563 portdev->cpkt.event = cpu_to_virtio16(portdev->vdev, event);
564 portdev->cpkt.value = cpu_to_virtio16(portdev->vdev, value);
566 sg_init_one(sg, &portdev->cpkt, sizeof(struct virtio_console_control));
568 if (virtqueue_add_outbuf(vq, sg, 1, &portdev->cpkt, GFP_ATOMIC) == 0) {
570 while (!virtqueue_get_buf(vq, &len)
571 && !virtqueue_is_broken(vq))
575 spin_unlock(&portdev->c_ovq_lock);
579 static ssize_t send_control_msg(struct port *port, unsigned int event,
582 /* Did the port get unplugged before userspace closed it? */
584 return __send_control_msg(port->portdev, port->id, event, value);
589 /* Callers must take the port->outvq_lock */
590 static void reclaim_consumed_buffers(struct port *port)
592 struct port_buffer *buf;
595 if (!port->portdev) {
596 /* Device has been unplugged. vqs are already gone. */
599 while ((buf = virtqueue_get_buf(port->out_vq, &len))) {
600 free_buf(buf, false);
601 port->outvq_full = false;
605 static ssize_t __send_to_port(struct port *port, struct scatterlist *sg,
606 int nents, size_t in_count,
607 void *data, bool nonblock)
609 struct virtqueue *out_vq;
614 out_vq = port->out_vq;
616 spin_lock_irqsave(&port->outvq_lock, flags);
618 reclaim_consumed_buffers(port);
620 err = virtqueue_add_outbuf(out_vq, sg, nents, data, GFP_ATOMIC);
622 /* Tell Host to go! */
623 virtqueue_kick(out_vq);
630 if (out_vq->num_free == 0)
631 port->outvq_full = true;
637 * Wait till the host acknowledges it pushed out the data we
638 * sent. This is done for data from the hvc_console; the tty
639 * operations are performed with spinlocks held so we can't
640 * sleep here. An alternative would be to copy the data to a
641 * buffer and relax the spinning requirement. The downside is
642 * we need to kmalloc a GFP_ATOMIC buffer each time the
643 * console driver writes something out.
645 while (!virtqueue_get_buf(out_vq, &len)
646 && !virtqueue_is_broken(out_vq))
649 spin_unlock_irqrestore(&port->outvq_lock, flags);
651 port->stats.bytes_sent += in_count;
653 * We're expected to return the amount of data we wrote -- all
660 * Give out the data that's requested from the buffer that we have
663 static ssize_t fill_readbuf(struct port *port, char __user *out_buf,
664 size_t out_count, bool to_user)
666 struct port_buffer *buf;
669 if (!out_count || !port_has_data(port))
673 out_count = min(out_count, buf->len - buf->offset);
678 ret = copy_to_user(out_buf, buf->buf + buf->offset, out_count);
682 memcpy((__force char *)out_buf, buf->buf + buf->offset,
686 buf->offset += out_count;
688 if (buf->offset == buf->len) {
690 * We're done using all the data in this buffer.
691 * Re-queue so that the Host can send us more data.
693 spin_lock_irqsave(&port->inbuf_lock, flags);
696 if (add_inbuf(port->in_vq, buf) < 0)
697 dev_warn(port->dev, "failed add_buf\n");
699 spin_unlock_irqrestore(&port->inbuf_lock, flags);
701 /* Return the number of bytes actually copied */
705 /* The condition that must be true for polling to end */
706 static bool will_read_block(struct port *port)
708 if (!port->guest_connected) {
709 /* Port got hot-unplugged. Let's exit. */
712 return !port_has_data(port) && port->host_connected;
715 static bool will_write_block(struct port *port)
719 if (!port->guest_connected) {
720 /* Port got hot-unplugged. Let's exit. */
723 if (!port->host_connected)
726 spin_lock_irq(&port->outvq_lock);
728 * Check if the Host has consumed any buffers since we last
729 * sent data (this is only applicable for nonblocking ports).
731 reclaim_consumed_buffers(port);
732 ret = port->outvq_full;
733 spin_unlock_irq(&port->outvq_lock);
738 static ssize_t port_fops_read(struct file *filp, char __user *ubuf,
739 size_t count, loff_t *offp)
744 port = filp->private_data;
746 /* Port is hot-unplugged. */
747 if (!port->guest_connected)
750 if (!port_has_data(port)) {
752 * If nothing's connected on the host just return 0 in
753 * case of list_empty; this tells the userspace app
754 * that there's no connection
756 if (!port->host_connected)
758 if (filp->f_flags & O_NONBLOCK)
761 ret = wait_event_freezable(port->waitqueue,
762 !will_read_block(port));
766 /* Port got hot-unplugged while we were waiting above. */
767 if (!port->guest_connected)
770 * We could've received a disconnection message while we were
771 * waiting for more data.
773 * This check is not clubbed in the if() statement above as we
774 * might receive some data as well as the host could get
775 * disconnected after we got woken up from our wait. So we
776 * really want to give off whatever data we have and only then
777 * check for host_connected.
779 if (!port_has_data(port) && !port->host_connected)
782 return fill_readbuf(port, ubuf, count, true);
785 static int wait_port_writable(struct port *port, bool nonblock)
789 if (will_write_block(port)) {
793 ret = wait_event_freezable(port->waitqueue,
794 !will_write_block(port));
798 /* Port got hot-unplugged. */
799 if (!port->guest_connected)
805 static ssize_t port_fops_write(struct file *filp, const char __user *ubuf,
806 size_t count, loff_t *offp)
809 struct port_buffer *buf;
812 struct scatterlist sg[1];
814 /* Userspace could be out to fool us */
818 port = filp->private_data;
820 nonblock = filp->f_flags & O_NONBLOCK;
822 ret = wait_port_writable(port, nonblock);
826 count = min((size_t)(32 * 1024), count);
828 buf = alloc_buf(port->portdev->vdev, count, 0);
832 ret = copy_from_user(buf->buf, ubuf, count);
839 * We now ask send_buf() to not spin for generic ports -- we
840 * can re-use the same code path that non-blocking file
841 * descriptors take for blocking file descriptors since the
842 * wait is already done and we're certain the write will go
843 * through to the host.
846 sg_init_one(sg, buf->buf, count);
847 ret = __send_to_port(port, sg, 1, count, buf, nonblock);
849 if (nonblock && ret > 0)
862 struct scatterlist *sg;
865 static int pipe_to_sg(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
866 struct splice_desc *sd)
868 struct sg_list *sgl = sd->u.data;
869 unsigned int offset, len;
871 if (sgl->n == sgl->size)
874 /* Try lock this page */
875 if (pipe_buf_try_steal(pipe, buf)) {
876 /* Get reference and unlock page for moving */
878 unlock_page(buf->page);
880 len = min(buf->len, sd->len);
881 sg_set_page(&(sgl->sg[sgl->n]), buf->page, len, buf->offset);
883 /* Failback to copying a page */
884 struct page *page = alloc_page(GFP_KERNEL);
890 offset = sd->pos & ~PAGE_MASK;
893 if (len + offset > PAGE_SIZE)
894 len = PAGE_SIZE - offset;
896 src = kmap_atomic(buf->page);
897 memcpy(page_address(page) + offset, src + buf->offset, len);
900 sg_set_page(&(sgl->sg[sgl->n]), page, len, offset);
908 /* Faster zero-copy write by splicing */
909 static ssize_t port_fops_splice_write(struct pipe_inode_info *pipe,
910 struct file *filp, loff_t *ppos,
911 size_t len, unsigned int flags)
913 struct port *port = filp->private_data;
916 struct port_buffer *buf;
917 struct splice_desc sd = {
923 unsigned int occupancy;
926 * Rproc_serial does not yet support splice. To support splice
927 * pipe_to_sg() must allocate dma-buffers and copy content from
928 * regular pages to dma pages. And alloc_buf and free_buf must
929 * support allocating and freeing such a list of dma-buffers.
931 if (is_rproc_serial(port->out_vq->vdev))
936 if (pipe_empty(pipe->head, pipe->tail))
939 ret = wait_port_writable(port, filp->f_flags & O_NONBLOCK);
943 occupancy = pipe_occupancy(pipe->head, pipe->tail);
944 buf = alloc_buf(port->portdev->vdev, 0, occupancy);
953 sgl.size = occupancy;
955 sg_init_table(sgl.sg, sgl.size);
956 ret = __splice_from_pipe(pipe, &sd, pipe_to_sg);
959 ret = __send_to_port(port, buf->sg, sgl.n, sgl.len, buf, true);
961 if (unlikely(ret <= 0))
970 static __poll_t port_fops_poll(struct file *filp, poll_table *wait)
975 port = filp->private_data;
976 poll_wait(filp, &port->waitqueue, wait);
978 if (!port->guest_connected) {
979 /* Port got unplugged */
983 if (!will_read_block(port))
984 ret |= EPOLLIN | EPOLLRDNORM;
985 if (!will_write_block(port))
987 if (!port->host_connected)
993 static void remove_port(struct kref *kref);
995 static int port_fops_release(struct inode *inode, struct file *filp)
999 port = filp->private_data;
1001 /* Notify host of port being closed */
1002 send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
1004 spin_lock_irq(&port->inbuf_lock);
1005 port->guest_connected = false;
1007 discard_port_data(port);
1009 spin_unlock_irq(&port->inbuf_lock);
1011 spin_lock_irq(&port->outvq_lock);
1012 reclaim_consumed_buffers(port);
1013 spin_unlock_irq(&port->outvq_lock);
1017 * Locks aren't necessary here as a port can't be opened after
1018 * unplug, and if a port isn't unplugged, a kref would already
1019 * exist for the port. Plus, taking ports_lock here would
1020 * create a dependency on other locks taken by functions
1021 * inside remove_port if we're the last holder of the port,
1022 * creating many problems.
1024 kref_put(&port->kref, remove_port);
1029 static int port_fops_open(struct inode *inode, struct file *filp)
1031 struct cdev *cdev = inode->i_cdev;
1035 /* We get the port with a kref here */
1036 port = find_port_by_devt(cdev->dev);
1038 /* Port was unplugged before we could proceed */
1041 filp->private_data = port;
1044 * Don't allow opening of console port devices -- that's done
1047 if (is_console_port(port)) {
1052 /* Allow only one process to open a particular port at a time */
1053 spin_lock_irq(&port->inbuf_lock);
1054 if (port->guest_connected) {
1055 spin_unlock_irq(&port->inbuf_lock);
1060 port->guest_connected = true;
1061 spin_unlock_irq(&port->inbuf_lock);
1063 spin_lock_irq(&port->outvq_lock);
1065 * There might be a chance that we missed reclaiming a few
1066 * buffers in the window of the port getting previously closed
1069 reclaim_consumed_buffers(port);
1070 spin_unlock_irq(&port->outvq_lock);
1072 nonseekable_open(inode, filp);
1074 /* Notify host of port being opened */
1075 send_control_msg(filp->private_data, VIRTIO_CONSOLE_PORT_OPEN, 1);
1079 kref_put(&port->kref, remove_port);
1083 static int port_fops_fasync(int fd, struct file *filp, int mode)
1087 port = filp->private_data;
1088 return fasync_helper(fd, filp, mode, &port->async_queue);
1092 * The file operations that we support: programs in the guest can open
1093 * a console device, read from it, write to it, poll for data and
1094 * close it. The devices are at
1095 * /dev/vport<device number>p<port number>
1097 static const struct file_operations port_fops = {
1098 .owner = THIS_MODULE,
1099 .open = port_fops_open,
1100 .read = port_fops_read,
1101 .write = port_fops_write,
1102 .splice_write = port_fops_splice_write,
1103 .poll = port_fops_poll,
1104 .release = port_fops_release,
1105 .fasync = port_fops_fasync,
1106 .llseek = no_llseek,
1110 * The put_chars() callback is pretty straightforward.
1112 * We turn the characters into a scatter-gather list, add it to the
1113 * output queue and then kick the Host. Then we sit here waiting for
1114 * it to finish: inefficient in theory, but in practice
1115 * implementations will do it immediately.
1117 static int put_chars(u32 vtermno, const char *buf, int count)
1120 struct scatterlist sg[1];
1124 if (unlikely(early_put_chars))
1125 return early_put_chars(vtermno, buf, count);
1127 port = find_port_by_vtermno(vtermno);
1131 data = kmemdup(buf, count, GFP_ATOMIC);
1135 sg_init_one(sg, data, count);
1136 ret = __send_to_port(port, sg, 1, count, data, false);
1142 * get_chars() is the callback from the hvc_console infrastructure
1143 * when an interrupt is received.
1145 * We call out to fill_readbuf that gets us the required data from the
1146 * buffers that are queued up.
1148 static int get_chars(u32 vtermno, char *buf, int count)
1152 /* If we've not set up the port yet, we have no input to give. */
1153 if (unlikely(early_put_chars))
1156 port = find_port_by_vtermno(vtermno);
1160 /* If we don't have an input queue yet, we can't get input. */
1161 BUG_ON(!port->in_vq);
1163 return fill_readbuf(port, (__force char __user *)buf, count, false);
1166 static void resize_console(struct port *port)
1168 struct virtio_device *vdev;
1170 /* The port could have been hot-unplugged */
1171 if (!port || !is_console_port(port))
1174 vdev = port->portdev->vdev;
1176 /* Don't test F_SIZE at all if we're rproc: not a valid feature! */
1177 if (!is_rproc_serial(vdev) &&
1178 virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE))
1179 hvc_resize(port->cons.hvc, port->cons.ws);
1182 /* We set the configuration at this point, since we now have a tty */
1183 static int notifier_add_vio(struct hvc_struct *hp, int data)
1187 port = find_port_by_vtermno(hp->vtermno);
1191 hp->irq_requested = 1;
1192 resize_console(port);
1197 static void notifier_del_vio(struct hvc_struct *hp, int data)
1199 hp->irq_requested = 0;
1202 /* The operations for console ports. */
1203 static const struct hv_ops hv_ops = {
1204 .get_chars = get_chars,
1205 .put_chars = put_chars,
1206 .notifier_add = notifier_add_vio,
1207 .notifier_del = notifier_del_vio,
1208 .notifier_hangup = notifier_del_vio,
1212 * Console drivers are initialized very early so boot messages can go
1213 * out, so we do things slightly differently from the generic virtio
1214 * initialization of the net and block drivers.
1216 * At this stage, the console is output-only. It's too early to set
1217 * up a virtqueue, so we let the drivers do some boutique early-output
1220 int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int))
1222 early_put_chars = put_chars;
1223 return hvc_instantiate(0, 0, &hv_ops);
1226 static int init_port_console(struct port *port)
1231 * The Host's telling us this port is a console port. Hook it
1232 * up with an hvc console.
1234 * To set up and manage our virtual console, we call
1237 * The first argument of hvc_alloc() is the virtual console
1238 * number. The second argument is the parameter for the
1239 * notification mechanism (like irq number). We currently
1240 * leave this as zero, virtqueues have implicit notifications.
1242 * The third argument is a "struct hv_ops" containing the
1243 * put_chars() get_chars(), notifier_add() and notifier_del()
1244 * pointers. The final argument is the output buffer size: we
1245 * can do any size, so we put PAGE_SIZE here.
1247 port->cons.vtermno = pdrvdata.next_vtermno;
1249 port->cons.hvc = hvc_alloc(port->cons.vtermno, 0, &hv_ops, PAGE_SIZE);
1250 if (IS_ERR(port->cons.hvc)) {
1251 ret = PTR_ERR(port->cons.hvc);
1253 "error %d allocating hvc for port\n", ret);
1254 port->cons.hvc = NULL;
1257 spin_lock_irq(&pdrvdata_lock);
1258 pdrvdata.next_vtermno++;
1259 list_add_tail(&port->cons.list, &pdrvdata.consoles);
1260 spin_unlock_irq(&pdrvdata_lock);
1261 port->guest_connected = true;
1264 * Start using the new console output if this is the first
1265 * console to come up.
1267 if (early_put_chars)
1268 early_put_chars = NULL;
1270 /* Notify host of port being opened */
1271 send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
1276 static ssize_t show_port_name(struct device *dev,
1277 struct device_attribute *attr, char *buffer)
1281 port = dev_get_drvdata(dev);
1283 return sprintf(buffer, "%s\n", port->name);
1286 static DEVICE_ATTR(name, S_IRUGO, show_port_name, NULL);
1288 static struct attribute *port_sysfs_entries[] = {
1289 &dev_attr_name.attr,
1293 static const struct attribute_group port_attribute_group = {
1294 .name = NULL, /* put in device directory */
1295 .attrs = port_sysfs_entries,
1298 static int port_debugfs_show(struct seq_file *s, void *data)
1300 struct port *port = s->private;
1302 seq_printf(s, "name: %s\n", port->name ? port->name : "");
1303 seq_printf(s, "guest_connected: %d\n", port->guest_connected);
1304 seq_printf(s, "host_connected: %d\n", port->host_connected);
1305 seq_printf(s, "outvq_full: %d\n", port->outvq_full);
1306 seq_printf(s, "bytes_sent: %lu\n", port->stats.bytes_sent);
1307 seq_printf(s, "bytes_received: %lu\n", port->stats.bytes_received);
1308 seq_printf(s, "bytes_discarded: %lu\n", port->stats.bytes_discarded);
1309 seq_printf(s, "is_console: %s\n",
1310 is_console_port(port) ? "yes" : "no");
1311 seq_printf(s, "console_vtermno: %u\n", port->cons.vtermno);
1316 DEFINE_SHOW_ATTRIBUTE(port_debugfs);
1318 static void set_console_size(struct port *port, u16 rows, u16 cols)
1320 if (!port || !is_console_port(port))
1323 port->cons.ws.ws_row = rows;
1324 port->cons.ws.ws_col = cols;
1327 static int fill_queue(struct virtqueue *vq, spinlock_t *lock)
1329 struct port_buffer *buf;
1335 buf = alloc_buf(vq->vdev, PAGE_SIZE, 0);
1339 spin_lock_irq(lock);
1340 ret = add_inbuf(vq, buf);
1342 spin_unlock_irq(lock);
1343 free_buf(buf, true);
1347 spin_unlock_irq(lock);
1350 return nr_added_bufs;
1353 static void send_sigio_to_port(struct port *port)
1355 if (port->async_queue && port->guest_connected)
1356 kill_fasync(&port->async_queue, SIGIO, POLL_OUT);
1359 static int add_port(struct ports_device *portdev, u32 id)
1361 char debugfs_name[16];
1366 port = kmalloc(sizeof(*port), GFP_KERNEL);
1371 kref_init(&port->kref);
1373 port->portdev = portdev;
1378 port->cons.hvc = NULL;
1379 port->async_queue = NULL;
1381 port->cons.ws.ws_row = port->cons.ws.ws_col = 0;
1382 port->cons.vtermno = 0;
1384 port->host_connected = port->guest_connected = false;
1385 port->stats = (struct port_stats) { 0 };
1387 port->outvq_full = false;
1389 port->in_vq = portdev->in_vqs[port->id];
1390 port->out_vq = portdev->out_vqs[port->id];
1392 port->cdev = cdev_alloc();
1394 dev_err(&port->portdev->vdev->dev, "Error allocating cdev\n");
1398 port->cdev->ops = &port_fops;
1400 devt = MKDEV(portdev->chr_major, id);
1401 err = cdev_add(port->cdev, devt, 1);
1403 dev_err(&port->portdev->vdev->dev,
1404 "Error %d adding cdev for port %u\n", err, id);
1407 port->dev = device_create(pdrvdata.class, &port->portdev->vdev->dev,
1408 devt, port, "vport%up%u",
1409 port->portdev->vdev->index, id);
1410 if (IS_ERR(port->dev)) {
1411 err = PTR_ERR(port->dev);
1412 dev_err(&port->portdev->vdev->dev,
1413 "Error %d creating device for port %u\n",
1418 spin_lock_init(&port->inbuf_lock);
1419 spin_lock_init(&port->outvq_lock);
1420 init_waitqueue_head(&port->waitqueue);
1422 /* We can safely ignore ENOSPC because it means
1423 * the queue already has buffers. Buffers are removed
1424 * only by virtcons_remove(), not by unplug_port()
1426 err = fill_queue(port->in_vq, &port->inbuf_lock);
1427 if (err < 0 && err != -ENOSPC) {
1428 dev_err(port->dev, "Error allocating inbufs\n");
1432 if (is_rproc_serial(port->portdev->vdev))
1434 * For rproc_serial assume remote processor is connected.
1435 * rproc_serial does not want the console port, only
1436 * the generic port implementation.
1438 port->host_connected = true;
1439 else if (!use_multiport(port->portdev)) {
1441 * If we're not using multiport support,
1442 * this has to be a console port.
1444 err = init_port_console(port);
1449 spin_lock_irq(&portdev->ports_lock);
1450 list_add_tail(&port->list, &port->portdev->ports);
1451 spin_unlock_irq(&portdev->ports_lock);
1454 * Tell the Host we're set so that it can send us various
1455 * configuration parameters for this port (eg, port name,
1456 * caching, whether this is a console port, etc.)
1458 send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1461 * Finally, create the debugfs file that we can use to
1462 * inspect a port's state at any time
1464 snprintf(debugfs_name, sizeof(debugfs_name), "vport%up%u",
1465 port->portdev->vdev->index, id);
1466 port->debugfs_file = debugfs_create_file(debugfs_name, 0444,
1467 pdrvdata.debugfs_dir,
1468 port, &port_debugfs_fops);
1473 device_destroy(pdrvdata.class, port->dev->devt);
1475 cdev_del(port->cdev);
1479 /* The host might want to notify management sw about port add failure */
1480 __send_control_msg(portdev, id, VIRTIO_CONSOLE_PORT_READY, 0);
1484 /* No users remain, remove all port-specific data. */
1485 static void remove_port(struct kref *kref)
1489 port = container_of(kref, struct port, kref);
1494 static void remove_port_data(struct port *port)
1496 spin_lock_irq(&port->inbuf_lock);
1497 /* Remove unused data this port might have received. */
1498 discard_port_data(port);
1499 spin_unlock_irq(&port->inbuf_lock);
1501 spin_lock_irq(&port->outvq_lock);
1502 reclaim_consumed_buffers(port);
1503 spin_unlock_irq(&port->outvq_lock);
1507 * Port got unplugged. Remove port from portdev's list and drop the
1508 * kref reference. If no userspace has this port opened, it will
1509 * result in immediate removal the port.
1511 static void unplug_port(struct port *port)
1513 spin_lock_irq(&port->portdev->ports_lock);
1514 list_del(&port->list);
1515 spin_unlock_irq(&port->portdev->ports_lock);
1517 spin_lock_irq(&port->inbuf_lock);
1518 if (port->guest_connected) {
1519 /* Let the app know the port is going down. */
1520 send_sigio_to_port(port);
1522 /* Do this after sigio is actually sent */
1523 port->guest_connected = false;
1524 port->host_connected = false;
1526 wake_up_interruptible(&port->waitqueue);
1528 spin_unlock_irq(&port->inbuf_lock);
1530 if (is_console_port(port)) {
1531 spin_lock_irq(&pdrvdata_lock);
1532 list_del(&port->cons.list);
1533 spin_unlock_irq(&pdrvdata_lock);
1534 hvc_remove(port->cons.hvc);
1537 remove_port_data(port);
1540 * We should just assume the device itself has gone off --
1541 * else a close on an open port later will try to send out a
1544 port->portdev = NULL;
1546 sysfs_remove_group(&port->dev->kobj, &port_attribute_group);
1547 device_destroy(pdrvdata.class, port->dev->devt);
1548 cdev_del(port->cdev);
1550 debugfs_remove(port->debugfs_file);
1554 * Locks around here are not necessary - a port can't be
1555 * opened after we removed the port struct from ports_list
1558 kref_put(&port->kref, remove_port);
1561 /* Any private messages that the Host and Guest want to share */
1562 static void handle_control_message(struct virtio_device *vdev,
1563 struct ports_device *portdev,
1564 struct port_buffer *buf)
1566 struct virtio_console_control *cpkt;
1571 cpkt = (struct virtio_console_control *)(buf->buf + buf->offset);
1573 port = find_port_by_id(portdev, virtio32_to_cpu(vdev, cpkt->id));
1575 cpkt->event != cpu_to_virtio16(vdev, VIRTIO_CONSOLE_PORT_ADD)) {
1576 /* No valid header at start of buffer. Drop it. */
1577 dev_dbg(&portdev->vdev->dev,
1578 "Invalid index %u in control packet\n", cpkt->id);
1582 switch (virtio16_to_cpu(vdev, cpkt->event)) {
1583 case VIRTIO_CONSOLE_PORT_ADD:
1585 dev_dbg(&portdev->vdev->dev,
1586 "Port %u already added\n", port->id);
1587 send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1590 if (virtio32_to_cpu(vdev, cpkt->id) >=
1591 portdev->max_nr_ports) {
1592 dev_warn(&portdev->vdev->dev,
1593 "Request for adding port with "
1594 "out-of-bound id %u, max. supported id: %u\n",
1595 cpkt->id, portdev->max_nr_ports - 1);
1598 add_port(portdev, virtio32_to_cpu(vdev, cpkt->id));
1600 case VIRTIO_CONSOLE_PORT_REMOVE:
1603 case VIRTIO_CONSOLE_CONSOLE_PORT:
1606 if (is_console_port(port))
1609 init_port_console(port);
1610 complete(&early_console_added);
1612 * Could remove the port here in case init fails - but
1613 * have to notify the host first.
1616 case VIRTIO_CONSOLE_RESIZE: {
1622 if (!is_console_port(port))
1625 memcpy(&size, buf->buf + buf->offset + sizeof(*cpkt),
1627 set_console_size(port, size.rows, size.cols);
1629 port->cons.hvc->irq_requested = 1;
1630 resize_console(port);
1633 case VIRTIO_CONSOLE_PORT_OPEN:
1634 port->host_connected = virtio16_to_cpu(vdev, cpkt->value);
1635 wake_up_interruptible(&port->waitqueue);
1637 * If the host port got closed and the host had any
1638 * unconsumed buffers, we'll be able to reclaim them
1641 spin_lock_irq(&port->outvq_lock);
1642 reclaim_consumed_buffers(port);
1643 spin_unlock_irq(&port->outvq_lock);
1646 * If the guest is connected, it'll be interested in
1647 * knowing the host connection state changed.
1649 spin_lock_irq(&port->inbuf_lock);
1650 send_sigio_to_port(port);
1651 spin_unlock_irq(&port->inbuf_lock);
1653 case VIRTIO_CONSOLE_PORT_NAME:
1655 * If we woke up after hibernation, we can get this
1656 * again. Skip it in that case.
1662 * Skip the size of the header and the cpkt to get the size
1663 * of the name that was sent
1665 name_size = buf->len - buf->offset - sizeof(*cpkt) + 1;
1667 port->name = kmalloc(name_size, GFP_KERNEL);
1670 "Not enough space to store port name\n");
1673 strncpy(port->name, buf->buf + buf->offset + sizeof(*cpkt),
1675 port->name[name_size - 1] = 0;
1678 * Since we only have one sysfs attribute, 'name',
1679 * create it only if we have a name for the port.
1681 err = sysfs_create_group(&port->dev->kobj,
1682 &port_attribute_group);
1685 "Error %d creating sysfs device attributes\n",
1689 * Generate a udev event so that appropriate
1690 * symlinks can be created based on udev
1693 kobject_uevent(&port->dev->kobj, KOBJ_CHANGE);
1699 static void control_work_handler(struct work_struct *work)
1701 struct ports_device *portdev;
1702 struct virtqueue *vq;
1703 struct port_buffer *buf;
1706 portdev = container_of(work, struct ports_device, control_work);
1707 vq = portdev->c_ivq;
1709 spin_lock(&portdev->c_ivq_lock);
1710 while ((buf = virtqueue_get_buf(vq, &len))) {
1711 spin_unlock(&portdev->c_ivq_lock);
1713 buf->len = min_t(size_t, len, buf->size);
1716 handle_control_message(vq->vdev, portdev, buf);
1718 spin_lock(&portdev->c_ivq_lock);
1719 if (add_inbuf(portdev->c_ivq, buf) < 0) {
1720 dev_warn(&portdev->vdev->dev,
1721 "Error adding buffer to queue\n");
1722 free_buf(buf, false);
1725 spin_unlock(&portdev->c_ivq_lock);
1728 static void flush_bufs(struct virtqueue *vq, bool can_sleep)
1730 struct port_buffer *buf;
1733 while ((buf = virtqueue_get_buf(vq, &len)))
1734 free_buf(buf, can_sleep);
1737 static void out_intr(struct virtqueue *vq)
1741 port = find_port_by_vq(vq->vdev->priv, vq);
1743 flush_bufs(vq, false);
1747 wake_up_interruptible(&port->waitqueue);
1750 static void in_intr(struct virtqueue *vq)
1753 unsigned long flags;
1755 port = find_port_by_vq(vq->vdev->priv, vq);
1757 flush_bufs(vq, false);
1761 spin_lock_irqsave(&port->inbuf_lock, flags);
1762 port->inbuf = get_inbuf(port);
1765 * Normally the port should not accept data when the port is
1766 * closed. For generic serial ports, the host won't (shouldn't)
1767 * send data till the guest is connected. But this condition
1768 * can be reached when a console port is not yet connected (no
1769 * tty is spawned) and the other side sends out data over the
1770 * vring, or when a remote devices start sending data before
1771 * the ports are opened.
1773 * A generic serial port will discard data if not connected,
1774 * while console ports and rproc-serial ports accepts data at
1775 * any time. rproc-serial is initiated with guest_connected to
1776 * false because port_fops_open expects this. Console ports are
1777 * hooked up with an HVC console and is initialized with
1778 * guest_connected to true.
1781 if (!port->guest_connected && !is_rproc_serial(port->portdev->vdev))
1782 discard_port_data(port);
1784 /* Send a SIGIO indicating new data in case the process asked for it */
1785 send_sigio_to_port(port);
1787 spin_unlock_irqrestore(&port->inbuf_lock, flags);
1789 wake_up_interruptible(&port->waitqueue);
1791 if (is_console_port(port) && hvc_poll(port->cons.hvc))
1795 static void control_intr(struct virtqueue *vq)
1797 struct ports_device *portdev;
1799 portdev = vq->vdev->priv;
1800 schedule_work(&portdev->control_work);
1803 static void config_intr(struct virtio_device *vdev)
1805 struct ports_device *portdev;
1807 portdev = vdev->priv;
1809 if (!use_multiport(portdev))
1810 schedule_work(&portdev->config_work);
1813 static void config_work_handler(struct work_struct *work)
1815 struct ports_device *portdev;
1817 portdev = container_of(work, struct ports_device, config_work);
1818 if (!use_multiport(portdev)) {
1819 struct virtio_device *vdev;
1823 vdev = portdev->vdev;
1824 virtio_cread(vdev, struct virtio_console_config, cols, &cols);
1825 virtio_cread(vdev, struct virtio_console_config, rows, &rows);
1827 port = find_port_by_id(portdev, 0);
1828 set_console_size(port, rows, cols);
1831 * We'll use this way of resizing only for legacy
1832 * support. For newer userspace
1833 * (VIRTIO_CONSOLE_F_MULTPORT+), use control messages
1834 * to indicate console size changes so that it can be
1837 resize_console(port);
1841 static int init_vqs(struct ports_device *portdev)
1843 vq_callback_t **io_callbacks;
1845 struct virtqueue **vqs;
1846 u32 i, j, nr_ports, nr_queues;
1849 nr_ports = portdev->max_nr_ports;
1850 nr_queues = use_multiport(portdev) ? (nr_ports + 1) * 2 : 2;
1852 vqs = kmalloc_array(nr_queues, sizeof(struct virtqueue *), GFP_KERNEL);
1853 io_callbacks = kmalloc_array(nr_queues, sizeof(vq_callback_t *),
1855 io_names = kmalloc_array(nr_queues, sizeof(char *), GFP_KERNEL);
1856 portdev->in_vqs = kmalloc_array(nr_ports, sizeof(struct virtqueue *),
1858 portdev->out_vqs = kmalloc_array(nr_ports, sizeof(struct virtqueue *),
1860 if (!vqs || !io_callbacks || !io_names || !portdev->in_vqs ||
1861 !portdev->out_vqs) {
1867 * For backward compat (newer host but older guest), the host
1868 * spawns a console port first and also inits the vqs for port
1872 io_callbacks[j] = in_intr;
1873 io_callbacks[j + 1] = out_intr;
1874 io_names[j] = "input";
1875 io_names[j + 1] = "output";
1878 if (use_multiport(portdev)) {
1879 io_callbacks[j] = control_intr;
1880 io_callbacks[j + 1] = NULL;
1881 io_names[j] = "control-i";
1882 io_names[j + 1] = "control-o";
1884 for (i = 1; i < nr_ports; i++) {
1886 io_callbacks[j] = in_intr;
1887 io_callbacks[j + 1] = out_intr;
1888 io_names[j] = "input";
1889 io_names[j + 1] = "output";
1892 /* Find the queues. */
1893 err = virtio_find_vqs(portdev->vdev, nr_queues, vqs,
1895 (const char **)io_names, NULL);
1900 portdev->in_vqs[0] = vqs[0];
1901 portdev->out_vqs[0] = vqs[1];
1903 if (use_multiport(portdev)) {
1904 portdev->c_ivq = vqs[j];
1905 portdev->c_ovq = vqs[j + 1];
1907 for (i = 1; i < nr_ports; i++) {
1909 portdev->in_vqs[i] = vqs[j];
1910 portdev->out_vqs[i] = vqs[j + 1];
1914 kfree(io_callbacks);
1920 kfree(portdev->out_vqs);
1921 kfree(portdev->in_vqs);
1923 kfree(io_callbacks);
1929 static const struct file_operations portdev_fops = {
1930 .owner = THIS_MODULE,
1933 static void remove_vqs(struct ports_device *portdev)
1935 struct virtqueue *vq;
1937 virtio_device_for_each_vq(portdev->vdev, vq) {
1938 struct port_buffer *buf;
1940 flush_bufs(vq, true);
1941 while ((buf = virtqueue_detach_unused_buf(vq)))
1942 free_buf(buf, true);
1944 portdev->vdev->config->del_vqs(portdev->vdev);
1945 kfree(portdev->in_vqs);
1946 kfree(portdev->out_vqs);
1949 static void virtcons_remove(struct virtio_device *vdev)
1951 struct ports_device *portdev;
1952 struct port *port, *port2;
1954 portdev = vdev->priv;
1956 spin_lock_irq(&pdrvdata_lock);
1957 list_del(&portdev->list);
1958 spin_unlock_irq(&pdrvdata_lock);
1960 /* Device is going away, exit any polling for buffers */
1961 virtio_break_device(vdev);
1962 if (use_multiport(portdev))
1963 flush_work(&portdev->control_work);
1965 flush_work(&portdev->config_work);
1967 /* Disable interrupts for vqs */
1968 virtio_reset_device(vdev);
1969 /* Finish up work that's lined up */
1970 if (use_multiport(portdev))
1971 cancel_work_sync(&portdev->control_work);
1973 cancel_work_sync(&portdev->config_work);
1975 list_for_each_entry_safe(port, port2, &portdev->ports, list)
1978 unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1981 * When yanking out a device, we immediately lose the
1982 * (device-side) queues. So there's no point in keeping the
1983 * guest side around till we drop our final reference. This
1984 * also means that any ports which are in an open state will
1985 * have to just stop using the port, as the vqs are going
1988 remove_vqs(portdev);
1993 * Once we're further in boot, we get probed like any other virtio
1996 * If the host also supports multiple console ports, we check the
1997 * config space to see how many ports the host has spawned. We
1998 * initialize each port found.
2000 static int virtcons_probe(struct virtio_device *vdev)
2002 struct ports_device *portdev;
2005 bool early = early_put_chars != NULL;
2007 /* We only need a config space if features are offered */
2008 if (!vdev->config->get &&
2009 (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE)
2010 || virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT))) {
2011 dev_err(&vdev->dev, "%s failure: config access disabled\n",
2016 /* Ensure to read early_put_chars now */
2019 portdev = kmalloc(sizeof(*portdev), GFP_KERNEL);
2025 /* Attach this portdev to this virtio_device, and vice-versa. */
2026 portdev->vdev = vdev;
2027 vdev->priv = portdev;
2029 portdev->chr_major = register_chrdev(0, "virtio-portsdev",
2031 if (portdev->chr_major < 0) {
2033 "Error %d registering chrdev for device %u\n",
2034 portdev->chr_major, vdev->index);
2035 err = portdev->chr_major;
2040 portdev->max_nr_ports = 1;
2042 /* Don't test MULTIPORT at all if we're rproc: not a valid feature! */
2043 if (!is_rproc_serial(vdev) &&
2044 virtio_cread_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT,
2045 struct virtio_console_config, max_nr_ports,
2046 &portdev->max_nr_ports) == 0) {
2047 if (portdev->max_nr_ports == 0 ||
2048 portdev->max_nr_ports > VIRTCONS_MAX_PORTS) {
2050 "Invalidate max_nr_ports %d",
2051 portdev->max_nr_ports);
2058 err = init_vqs(portdev);
2060 dev_err(&vdev->dev, "Error %d initializing vqs\n", err);
2064 spin_lock_init(&portdev->ports_lock);
2065 INIT_LIST_HEAD(&portdev->ports);
2066 INIT_LIST_HEAD(&portdev->list);
2068 virtio_device_ready(portdev->vdev);
2070 INIT_WORK(&portdev->config_work, &config_work_handler);
2071 INIT_WORK(&portdev->control_work, &control_work_handler);
2074 spin_lock_init(&portdev->c_ivq_lock);
2075 spin_lock_init(&portdev->c_ovq_lock);
2077 err = fill_queue(portdev->c_ivq, &portdev->c_ivq_lock);
2080 "Error allocating buffers for control queue\n");
2082 * The host might want to notify mgmt sw about device
2085 __send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
2086 VIRTIO_CONSOLE_DEVICE_READY, 0);
2087 /* Device was functional: we need full cleanup. */
2088 virtcons_remove(vdev);
2093 * For backward compatibility: Create a console port
2094 * if we're running on older host.
2096 add_port(portdev, 0);
2099 spin_lock_irq(&pdrvdata_lock);
2100 list_add_tail(&portdev->list, &pdrvdata.portdevs);
2101 spin_unlock_irq(&pdrvdata_lock);
2103 __send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
2104 VIRTIO_CONSOLE_DEVICE_READY, 1);
2107 * If there was an early virtio console, assume that there are no
2108 * other consoles. We need to wait until the hvc_alloc matches the
2109 * hvc_instantiate, otherwise tty_open will complain, resulting in
2110 * a "Warning: unable to open an initial console" boot failure.
2111 * Without multiport this is done in add_port above. With multiport
2112 * this might take some host<->guest communication - thus we have to
2115 if (multiport && early)
2116 wait_for_completion(&early_console_added);
2121 unregister_chrdev(portdev->chr_major, "virtio-portsdev");
2128 static const struct virtio_device_id id_table[] = {
2129 { VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID },
2132 MODULE_DEVICE_TABLE(virtio, id_table);
2134 static const unsigned int features[] = {
2135 VIRTIO_CONSOLE_F_SIZE,
2136 VIRTIO_CONSOLE_F_MULTIPORT,
2139 static const struct virtio_device_id rproc_serial_id_table[] = {
2140 #if IS_ENABLED(CONFIG_REMOTEPROC)
2141 { VIRTIO_ID_RPROC_SERIAL, VIRTIO_DEV_ANY_ID },
2145 MODULE_DEVICE_TABLE(virtio, rproc_serial_id_table);
2147 static const unsigned int rproc_serial_features[] = {
2150 #ifdef CONFIG_PM_SLEEP
2151 static int virtcons_freeze(struct virtio_device *vdev)
2153 struct ports_device *portdev;
2156 portdev = vdev->priv;
2158 virtio_reset_device(vdev);
2160 if (use_multiport(portdev))
2161 virtqueue_disable_cb(portdev->c_ivq);
2162 cancel_work_sync(&portdev->control_work);
2163 cancel_work_sync(&portdev->config_work);
2165 * Once more: if control_work_handler() was running, it would
2166 * enable the cb as the last step.
2168 if (use_multiport(portdev))
2169 virtqueue_disable_cb(portdev->c_ivq);
2171 list_for_each_entry(port, &portdev->ports, list) {
2172 virtqueue_disable_cb(port->in_vq);
2173 virtqueue_disable_cb(port->out_vq);
2175 * We'll ask the host later if the new invocation has
2176 * the port opened or closed.
2178 port->host_connected = false;
2179 remove_port_data(port);
2181 remove_vqs(portdev);
2186 static int virtcons_restore(struct virtio_device *vdev)
2188 struct ports_device *portdev;
2192 portdev = vdev->priv;
2194 ret = init_vqs(portdev);
2198 virtio_device_ready(portdev->vdev);
2200 if (use_multiport(portdev))
2201 fill_queue(portdev->c_ivq, &portdev->c_ivq_lock);
2203 list_for_each_entry(port, &portdev->ports, list) {
2204 port->in_vq = portdev->in_vqs[port->id];
2205 port->out_vq = portdev->out_vqs[port->id];
2207 fill_queue(port->in_vq, &port->inbuf_lock);
2209 /* Get port open/close status on the host */
2210 send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
2213 * If a port was open at the time of suspending, we
2214 * have to let the host know that it's still open.
2216 if (port->guest_connected)
2217 send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
2223 static struct virtio_driver virtio_console = {
2224 .feature_table = features,
2225 .feature_table_size = ARRAY_SIZE(features),
2226 .driver.name = KBUILD_MODNAME,
2227 .driver.owner = THIS_MODULE,
2228 .id_table = id_table,
2229 .probe = virtcons_probe,
2230 .remove = virtcons_remove,
2231 .config_changed = config_intr,
2232 #ifdef CONFIG_PM_SLEEP
2233 .freeze = virtcons_freeze,
2234 .restore = virtcons_restore,
2238 static struct virtio_driver virtio_rproc_serial = {
2239 .feature_table = rproc_serial_features,
2240 .feature_table_size = ARRAY_SIZE(rproc_serial_features),
2241 .driver.name = "virtio_rproc_serial",
2242 .driver.owner = THIS_MODULE,
2243 .id_table = rproc_serial_id_table,
2244 .probe = virtcons_probe,
2245 .remove = virtcons_remove,
2248 static int __init virtio_console_init(void)
2252 pdrvdata.class = class_create(THIS_MODULE, "virtio-ports");
2253 if (IS_ERR(pdrvdata.class)) {
2254 err = PTR_ERR(pdrvdata.class);
2255 pr_err("Error %d creating virtio-ports class\n", err);
2259 pdrvdata.debugfs_dir = debugfs_create_dir("virtio-ports", NULL);
2260 INIT_LIST_HEAD(&pdrvdata.consoles);
2261 INIT_LIST_HEAD(&pdrvdata.portdevs);
2263 err = register_virtio_driver(&virtio_console);
2265 pr_err("Error %d registering virtio driver\n", err);
2268 err = register_virtio_driver(&virtio_rproc_serial);
2270 pr_err("Error %d registering virtio rproc serial driver\n",
2276 unregister_virtio_driver(&virtio_console);
2278 debugfs_remove_recursive(pdrvdata.debugfs_dir);
2279 class_destroy(pdrvdata.class);
2283 static void __exit virtio_console_fini(void)
2287 unregister_virtio_driver(&virtio_console);
2288 unregister_virtio_driver(&virtio_rproc_serial);
2290 class_destroy(pdrvdata.class);
2291 debugfs_remove_recursive(pdrvdata.debugfs_dir);
2293 module_init(virtio_console_init);
2294 module_exit(virtio_console_fini);
2296 MODULE_DESCRIPTION("Virtio console driver");
2297 MODULE_LICENSE("GPL");