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.
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/idr.h>
17 #include <linux/init.h>
18 #include <linux/list.h>
19 #include <linux/poll.h>
20 #include <linux/sched.h>
21 #include <linux/slab.h>
22 #include <linux/spinlock.h>
23 #include <linux/virtio.h>
24 #include <linux/virtio_console.h>
25 #include <linux/wait.h>
26 #include <linux/workqueue.h>
27 #include <linux/module.h>
28 #include <linux/dma-mapping.h>
29 #include "../tty/hvc/hvc_console.h"
31 #define is_rproc_enabled IS_ENABLED(CONFIG_REMOTEPROC)
32 #define VIRTCONS_MAX_PORTS 0x8000
35 * This is a global struct for storing common data for all the devices
36 * this driver handles.
38 * Mainly, it has a linked list for all the consoles in one place so
39 * that callbacks from hvc for get_chars(), put_chars() work properly
40 * across multiple devices and multiple ports per device.
42 struct ports_driver_data {
43 /* Used for registering chardevs */
46 /* Used for exporting per-port information to debugfs */
47 struct dentry *debugfs_dir;
49 /* List of all the devices we're handling */
50 struct list_head portdevs;
52 /* All the console devices handled by this driver */
53 struct list_head consoles;
56 static struct ports_driver_data pdrvdata;
58 static DEFINE_SPINLOCK(pdrvdata_lock);
59 static DECLARE_COMPLETION(early_console_added);
61 /* This struct holds information that's relevant only for console ports */
63 /* We'll place all consoles in a list in the pdrvdata struct */
64 struct list_head list;
66 /* The hvc device associated with this console port */
67 struct hvc_struct *hvc;
69 /* The size of the console */
73 * This number identifies the number that we used to register
74 * with hvc in hvc_instantiate() and hvc_alloc(); this is the
75 * number passed on by the hvc callbacks to us to
76 * differentiate between the other console ports handled by
82 static DEFINE_IDA(vtermno_ida);
87 /* size of the buffer in *buf above */
90 /* used length of the buffer */
92 /* offset in the buf from which to consume data */
95 /* DMA address of buffer */
98 /* Device we got DMA memory from */
101 /* List of pending dma buffers to free */
102 struct list_head list;
104 /* If sgpages == 0 then buf is used */
105 unsigned int sgpages;
107 /* sg is used if spages > 0. sg must be the last in is struct */
108 struct scatterlist sg[];
112 * This is a per-device struct that stores data common to all the
113 * ports for that device (vdev->priv).
115 struct ports_device {
116 /* Next portdev in the list, head is in the pdrvdata struct */
117 struct list_head list;
120 * Workqueue handlers where we process deferred work after
123 struct work_struct control_work;
124 struct work_struct config_work;
126 struct list_head ports;
128 /* To protect the list of ports */
129 spinlock_t ports_lock;
131 /* To protect the vq operations for the control channel */
132 spinlock_t c_ivq_lock;
133 spinlock_t c_ovq_lock;
135 /* max. number of ports this device can hold */
138 /* The virtio device we're associated with */
139 struct virtio_device *vdev;
142 * A couple of virtqueues for the control channel: one for
143 * guest->host transfers, one for host->guest transfers
145 struct virtqueue *c_ivq, *c_ovq;
148 * A control packet buffer for guest->host requests, protected
151 struct virtio_console_control cpkt;
153 /* Array of per-port IO virtqueues */
154 struct virtqueue **in_vqs, **out_vqs;
156 /* Major number for this device. Ports will be created as minors. */
161 unsigned long bytes_sent, bytes_received, bytes_discarded;
164 /* This struct holds the per-port data */
166 /* Next port in the list, head is in the ports_device */
167 struct list_head list;
169 /* Pointer to the parent virtio_console device */
170 struct ports_device *portdev;
172 /* The current buffer from which data has to be fed to readers */
173 struct port_buffer *inbuf;
176 * To protect the operations on the in_vq associated with this
177 * port. Has to be a spinlock because it can be called from
178 * interrupt context (get_char()).
180 spinlock_t inbuf_lock;
182 /* Protect the operations on the out_vq. */
183 spinlock_t outvq_lock;
185 /* The IO vqs for this port */
186 struct virtqueue *in_vq, *out_vq;
188 /* File in the debugfs directory that exposes this port's information */
189 struct dentry *debugfs_file;
192 * Keep count of the bytes sent, received and discarded for
193 * this port for accounting and debugging purposes. These
194 * counts are not reset across port open / close events.
196 struct port_stats stats;
199 * The entries in this struct will be valid if this port is
200 * hooked up to an hvc console
204 /* Each port associates with a separate char device */
208 /* Reference-counting to handle port hot-unplugs and file operations */
211 /* A waitqueue for poll() or blocking read operations */
212 wait_queue_head_t waitqueue;
214 /* The 'name' of the port that we expose via sysfs properties */
217 /* We can notify apps of host connect / disconnect events via SIGIO */
218 struct fasync_struct *async_queue;
220 /* The 'id' to identify the port with the Host */
225 /* Is the host device open */
228 /* We should allow only one process to open a port */
229 bool guest_connected;
232 /* This is the very early arch-specified put chars function. */
233 static int (*early_put_chars)(u32, const char *, int);
235 static struct port *find_port_by_vtermno(u32 vtermno)
238 struct console *cons;
241 spin_lock_irqsave(&pdrvdata_lock, flags);
242 list_for_each_entry(cons, &pdrvdata.consoles, list) {
243 if (cons->vtermno == vtermno) {
244 port = container_of(cons, struct port, cons);
250 spin_unlock_irqrestore(&pdrvdata_lock, flags);
254 static struct port *find_port_by_devt_in_portdev(struct ports_device *portdev,
260 spin_lock_irqsave(&portdev->ports_lock, flags);
261 list_for_each_entry(port, &portdev->ports, list) {
262 if (port->cdev->dev == dev) {
263 kref_get(&port->kref);
269 spin_unlock_irqrestore(&portdev->ports_lock, flags);
274 static struct port *find_port_by_devt(dev_t dev)
276 struct ports_device *portdev;
280 spin_lock_irqsave(&pdrvdata_lock, flags);
281 list_for_each_entry(portdev, &pdrvdata.portdevs, list) {
282 port = find_port_by_devt_in_portdev(portdev, dev);
288 spin_unlock_irqrestore(&pdrvdata_lock, flags);
292 static struct port *find_port_by_id(struct ports_device *portdev, u32 id)
297 spin_lock_irqsave(&portdev->ports_lock, flags);
298 list_for_each_entry(port, &portdev->ports, list)
303 spin_unlock_irqrestore(&portdev->ports_lock, flags);
308 static struct port *find_port_by_vq(struct ports_device *portdev,
309 struct virtqueue *vq)
314 spin_lock_irqsave(&portdev->ports_lock, flags);
315 list_for_each_entry(port, &portdev->ports, list)
316 if (port->in_vq == vq || port->out_vq == vq)
320 spin_unlock_irqrestore(&portdev->ports_lock, flags);
324 static bool is_console_port(struct port *port)
331 static bool is_rproc_serial(const struct virtio_device *vdev)
333 return is_rproc_enabled && vdev->id.device == VIRTIO_ID_RPROC_SERIAL;
336 static inline bool use_multiport(struct ports_device *portdev)
339 * This condition can be true when put_chars is called from
344 return __virtio_test_bit(portdev->vdev, VIRTIO_CONSOLE_F_MULTIPORT);
347 static DEFINE_SPINLOCK(dma_bufs_lock);
348 static LIST_HEAD(pending_free_dma_bufs);
350 static void free_buf(struct port_buffer *buf, bool can_sleep)
354 for (i = 0; i < buf->sgpages; i++) {
355 struct page *page = sg_page(&buf->sg[i]);
363 } else if (is_rproc_enabled) {
366 /* dma_free_coherent requires interrupts to be enabled. */
368 /* queue up dma-buffers to be freed later */
369 spin_lock_irqsave(&dma_bufs_lock, flags);
370 list_add_tail(&buf->list, &pending_free_dma_bufs);
371 spin_unlock_irqrestore(&dma_bufs_lock, flags);
374 dma_free_coherent(buf->dev, buf->size, buf->buf, buf->dma);
376 /* Release device refcnt and allow it to be freed */
377 put_device(buf->dev);
383 static void reclaim_dma_bufs(void)
386 struct port_buffer *buf, *tmp;
389 if (list_empty(&pending_free_dma_bufs))
392 /* Create a copy of the pending_free_dma_bufs while holding the lock */
393 spin_lock_irqsave(&dma_bufs_lock, flags);
394 list_cut_position(&tmp_list, &pending_free_dma_bufs,
395 pending_free_dma_bufs.prev);
396 spin_unlock_irqrestore(&dma_bufs_lock, flags);
398 /* Release the dma buffers, without irqs enabled */
399 list_for_each_entry_safe(buf, tmp, &tmp_list, list) {
400 list_del(&buf->list);
405 static struct port_buffer *alloc_buf(struct virtio_device *vdev, size_t buf_size,
408 struct port_buffer *buf;
413 * Allocate buffer and the sg list. The sg list array is allocated
414 * directly after the port_buffer struct.
416 buf = kmalloc(struct_size(buf, sg, pages), GFP_KERNEL);
420 buf->sgpages = pages;
427 if (is_rproc_serial(vdev)) {
429 * Allocate DMA memory from ancestor. When a virtio
430 * device is created by remoteproc, the DMA memory is
431 * associated with the parent device:
432 * virtioY => remoteprocX#vdevYbuffer.
434 buf->dev = vdev->dev.parent;
438 /* Increase device refcnt to avoid freeing it */
439 get_device(buf->dev);
440 buf->buf = dma_alloc_coherent(buf->dev, buf_size, &buf->dma,
444 buf->buf = kmalloc(buf_size, GFP_KERNEL);
451 buf->size = buf_size;
460 /* Callers should take appropriate locks */
461 static struct port_buffer *get_inbuf(struct port *port)
463 struct port_buffer *buf;
469 buf = virtqueue_get_buf(port->in_vq, &len);
471 buf->len = min_t(size_t, len, buf->size);
473 port->stats.bytes_received += len;
479 * Create a scatter-gather list representing our input buffer and put
482 * Callers should take appropriate locks.
484 static int add_inbuf(struct virtqueue *vq, struct port_buffer *buf)
486 struct scatterlist sg[1];
489 sg_init_one(sg, buf->buf, buf->size);
491 ret = virtqueue_add_inbuf(vq, sg, 1, buf, GFP_ATOMIC);
498 /* Discard any unread data this port has. Callers lockers. */
499 static void discard_port_data(struct port *port)
501 struct port_buffer *buf;
504 if (!port->portdev) {
505 /* Device has been unplugged. vqs are already gone. */
508 buf = get_inbuf(port);
512 port->stats.bytes_discarded += buf->len - buf->offset;
513 if (add_inbuf(port->in_vq, buf) < 0) {
515 free_buf(buf, false);
518 buf = get_inbuf(port);
521 dev_warn(port->dev, "Errors adding %d buffers back to vq\n",
525 static bool port_has_data(struct port *port)
531 spin_lock_irqsave(&port->inbuf_lock, flags);
532 port->inbuf = get_inbuf(port);
536 spin_unlock_irqrestore(&port->inbuf_lock, flags);
540 static ssize_t __send_control_msg(struct ports_device *portdev, u32 port_id,
541 unsigned int event, unsigned int value)
543 struct scatterlist sg[1];
544 struct virtqueue *vq;
547 if (!use_multiport(portdev))
552 spin_lock(&portdev->c_ovq_lock);
554 portdev->cpkt.id = cpu_to_virtio32(portdev->vdev, port_id);
555 portdev->cpkt.event = cpu_to_virtio16(portdev->vdev, event);
556 portdev->cpkt.value = cpu_to_virtio16(portdev->vdev, value);
558 sg_init_one(sg, &portdev->cpkt, sizeof(struct virtio_console_control));
560 if (virtqueue_add_outbuf(vq, sg, 1, &portdev->cpkt, GFP_ATOMIC) == 0) {
562 while (!virtqueue_get_buf(vq, &len)
563 && !virtqueue_is_broken(vq))
567 spin_unlock(&portdev->c_ovq_lock);
571 static ssize_t send_control_msg(struct port *port, unsigned int event,
574 /* Did the port get unplugged before userspace closed it? */
576 return __send_control_msg(port->portdev, port->id, event, value);
581 /* Callers must take the port->outvq_lock */
582 static void reclaim_consumed_buffers(struct port *port)
584 struct port_buffer *buf;
587 if (!port->portdev) {
588 /* Device has been unplugged. vqs are already gone. */
591 while ((buf = virtqueue_get_buf(port->out_vq, &len))) {
592 free_buf(buf, false);
593 port->outvq_full = false;
597 static ssize_t __send_to_port(struct port *port, struct scatterlist *sg,
598 int nents, size_t in_count,
599 void *data, bool nonblock)
601 struct virtqueue *out_vq;
606 out_vq = port->out_vq;
608 spin_lock_irqsave(&port->outvq_lock, flags);
610 reclaim_consumed_buffers(port);
612 err = virtqueue_add_outbuf(out_vq, sg, nents, data, GFP_ATOMIC);
614 /* Tell Host to go! */
615 virtqueue_kick(out_vq);
622 if (out_vq->num_free == 0)
623 port->outvq_full = true;
629 * Wait till the host acknowledges it pushed out the data we
630 * sent. This is done for data from the hvc_console; the tty
631 * operations are performed with spinlocks held so we can't
632 * sleep here. An alternative would be to copy the data to a
633 * buffer and relax the spinning requirement. The downside is
634 * we need to kmalloc a GFP_ATOMIC buffer each time the
635 * console driver writes something out.
637 while (!virtqueue_get_buf(out_vq, &len)
638 && !virtqueue_is_broken(out_vq))
641 spin_unlock_irqrestore(&port->outvq_lock, flags);
643 port->stats.bytes_sent += in_count;
645 * We're expected to return the amount of data we wrote -- all
652 * Give out the data that's requested from the buffer that we have
655 static ssize_t fill_readbuf(struct port *port, char __user *out_buf,
656 size_t out_count, bool to_user)
658 struct port_buffer *buf;
661 if (!out_count || !port_has_data(port))
665 out_count = min(out_count, buf->len - buf->offset);
670 ret = copy_to_user(out_buf, buf->buf + buf->offset, out_count);
674 memcpy((__force char *)out_buf, buf->buf + buf->offset,
678 buf->offset += out_count;
680 if (buf->offset == buf->len) {
682 * We're done using all the data in this buffer.
683 * Re-queue so that the Host can send us more data.
685 spin_lock_irqsave(&port->inbuf_lock, flags);
688 if (add_inbuf(port->in_vq, buf) < 0)
689 dev_warn(port->dev, "failed add_buf\n");
691 spin_unlock_irqrestore(&port->inbuf_lock, flags);
693 /* Return the number of bytes actually copied */
697 /* The condition that must be true for polling to end */
698 static bool will_read_block(struct port *port)
700 if (!port->guest_connected) {
701 /* Port got hot-unplugged. Let's exit. */
704 return !port_has_data(port) && port->host_connected;
707 static bool will_write_block(struct port *port)
711 if (!port->guest_connected) {
712 /* Port got hot-unplugged. Let's exit. */
715 if (!port->host_connected)
718 spin_lock_irq(&port->outvq_lock);
720 * Check if the Host has consumed any buffers since we last
721 * sent data (this is only applicable for nonblocking ports).
723 reclaim_consumed_buffers(port);
724 ret = port->outvq_full;
725 spin_unlock_irq(&port->outvq_lock);
730 static ssize_t port_fops_read(struct file *filp, char __user *ubuf,
731 size_t count, loff_t *offp)
736 port = filp->private_data;
738 /* Port is hot-unplugged. */
739 if (!port->guest_connected)
742 if (!port_has_data(port)) {
744 * If nothing's connected on the host just return 0 in
745 * case of list_empty; this tells the userspace app
746 * that there's no connection
748 if (!port->host_connected)
750 if (filp->f_flags & O_NONBLOCK)
753 ret = wait_event_freezable(port->waitqueue,
754 !will_read_block(port));
758 /* Port got hot-unplugged while we were waiting above. */
759 if (!port->guest_connected)
762 * We could've received a disconnection message while we were
763 * waiting for more data.
765 * This check is not clubbed in the if() statement above as we
766 * might receive some data as well as the host could get
767 * disconnected after we got woken up from our wait. So we
768 * really want to give off whatever data we have and only then
769 * check for host_connected.
771 if (!port_has_data(port) && !port->host_connected)
774 return fill_readbuf(port, ubuf, count, true);
777 static int wait_port_writable(struct port *port, bool nonblock)
781 if (will_write_block(port)) {
785 ret = wait_event_freezable(port->waitqueue,
786 !will_write_block(port));
790 /* Port got hot-unplugged. */
791 if (!port->guest_connected)
797 static ssize_t port_fops_write(struct file *filp, const char __user *ubuf,
798 size_t count, loff_t *offp)
801 struct port_buffer *buf;
804 struct scatterlist sg[1];
806 /* Userspace could be out to fool us */
810 port = filp->private_data;
812 nonblock = filp->f_flags & O_NONBLOCK;
814 ret = wait_port_writable(port, nonblock);
818 count = min((size_t)(32 * 1024), count);
820 buf = alloc_buf(port->portdev->vdev, count, 0);
824 ret = copy_from_user(buf->buf, ubuf, count);
831 * We now ask send_buf() to not spin for generic ports -- we
832 * can re-use the same code path that non-blocking file
833 * descriptors take for blocking file descriptors since the
834 * wait is already done and we're certain the write will go
835 * through to the host.
838 sg_init_one(sg, buf->buf, count);
839 ret = __send_to_port(port, sg, 1, count, buf, nonblock);
841 if (nonblock && ret > 0)
854 struct scatterlist *sg;
857 static int pipe_to_sg(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
858 struct splice_desc *sd)
860 struct sg_list *sgl = sd->u.data;
861 unsigned int offset, len;
863 if (sgl->n == sgl->size)
866 /* Try lock this page */
867 if (pipe_buf_try_steal(pipe, buf)) {
868 /* Get reference and unlock page for moving */
870 unlock_page(buf->page);
872 len = min(buf->len, sd->len);
873 sg_set_page(&(sgl->sg[sgl->n]), buf->page, len, buf->offset);
875 /* Failback to copying a page */
876 struct page *page = alloc_page(GFP_KERNEL);
882 offset = sd->pos & ~PAGE_MASK;
885 if (len + offset > PAGE_SIZE)
886 len = PAGE_SIZE - offset;
888 src = kmap_atomic(buf->page);
889 memcpy(page_address(page) + offset, src + buf->offset, len);
892 sg_set_page(&(sgl->sg[sgl->n]), page, len, offset);
900 /* Faster zero-copy write by splicing */
901 static ssize_t port_fops_splice_write(struct pipe_inode_info *pipe,
902 struct file *filp, loff_t *ppos,
903 size_t len, unsigned int flags)
905 struct port *port = filp->private_data;
908 struct port_buffer *buf;
909 struct splice_desc sd = {
915 unsigned int occupancy;
918 * Rproc_serial does not yet support splice. To support splice
919 * pipe_to_sg() must allocate dma-buffers and copy content from
920 * regular pages to dma pages. And alloc_buf and free_buf must
921 * support allocating and freeing such a list of dma-buffers.
923 if (is_rproc_serial(port->out_vq->vdev))
928 if (pipe_empty(pipe->head, pipe->tail))
931 ret = wait_port_writable(port, filp->f_flags & O_NONBLOCK);
935 occupancy = pipe_occupancy(pipe->head, pipe->tail);
936 buf = alloc_buf(port->portdev->vdev, 0, occupancy);
945 sgl.size = occupancy;
947 sg_init_table(sgl.sg, sgl.size);
948 ret = __splice_from_pipe(pipe, &sd, pipe_to_sg);
951 ret = __send_to_port(port, buf->sg, sgl.n, sgl.len, buf, true);
953 if (unlikely(ret <= 0))
962 static __poll_t port_fops_poll(struct file *filp, poll_table *wait)
967 port = filp->private_data;
968 poll_wait(filp, &port->waitqueue, wait);
970 if (!port->guest_connected) {
971 /* Port got unplugged */
975 if (!will_read_block(port))
976 ret |= EPOLLIN | EPOLLRDNORM;
977 if (!will_write_block(port))
979 if (!port->host_connected)
985 static void remove_port(struct kref *kref);
987 static int port_fops_release(struct inode *inode, struct file *filp)
991 port = filp->private_data;
993 /* Notify host of port being closed */
994 send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
996 spin_lock_irq(&port->inbuf_lock);
997 port->guest_connected = false;
999 discard_port_data(port);
1001 spin_unlock_irq(&port->inbuf_lock);
1003 spin_lock_irq(&port->outvq_lock);
1004 reclaim_consumed_buffers(port);
1005 spin_unlock_irq(&port->outvq_lock);
1009 * Locks aren't necessary here as a port can't be opened after
1010 * unplug, and if a port isn't unplugged, a kref would already
1011 * exist for the port. Plus, taking ports_lock here would
1012 * create a dependency on other locks taken by functions
1013 * inside remove_port if we're the last holder of the port,
1014 * creating many problems.
1016 kref_put(&port->kref, remove_port);
1021 static int port_fops_open(struct inode *inode, struct file *filp)
1023 struct cdev *cdev = inode->i_cdev;
1027 /* We get the port with a kref here */
1028 port = find_port_by_devt(cdev->dev);
1030 /* Port was unplugged before we could proceed */
1033 filp->private_data = port;
1036 * Don't allow opening of console port devices -- that's done
1039 if (is_console_port(port)) {
1044 /* Allow only one process to open a particular port at a time */
1045 spin_lock_irq(&port->inbuf_lock);
1046 if (port->guest_connected) {
1047 spin_unlock_irq(&port->inbuf_lock);
1052 port->guest_connected = true;
1053 spin_unlock_irq(&port->inbuf_lock);
1055 spin_lock_irq(&port->outvq_lock);
1057 * There might be a chance that we missed reclaiming a few
1058 * buffers in the window of the port getting previously closed
1061 reclaim_consumed_buffers(port);
1062 spin_unlock_irq(&port->outvq_lock);
1064 nonseekable_open(inode, filp);
1066 /* Notify host of port being opened */
1067 send_control_msg(filp->private_data, VIRTIO_CONSOLE_PORT_OPEN, 1);
1071 kref_put(&port->kref, remove_port);
1075 static int port_fops_fasync(int fd, struct file *filp, int mode)
1079 port = filp->private_data;
1080 return fasync_helper(fd, filp, mode, &port->async_queue);
1084 * The file operations that we support: programs in the guest can open
1085 * a console device, read from it, write to it, poll for data and
1086 * close it. The devices are at
1087 * /dev/vport<device number>p<port number>
1089 static const struct file_operations port_fops = {
1090 .owner = THIS_MODULE,
1091 .open = port_fops_open,
1092 .read = port_fops_read,
1093 .write = port_fops_write,
1094 .splice_write = port_fops_splice_write,
1095 .poll = port_fops_poll,
1096 .release = port_fops_release,
1097 .fasync = port_fops_fasync,
1098 .llseek = no_llseek,
1102 * The put_chars() callback is pretty straightforward.
1104 * We turn the characters into a scatter-gather list, add it to the
1105 * output queue and then kick the Host. Then we sit here waiting for
1106 * it to finish: inefficient in theory, but in practice
1107 * implementations will do it immediately.
1109 static int put_chars(u32 vtermno, const char *buf, int count)
1112 struct scatterlist sg[1];
1116 if (unlikely(early_put_chars))
1117 return early_put_chars(vtermno, buf, count);
1119 port = find_port_by_vtermno(vtermno);
1123 data = kmemdup(buf, count, GFP_ATOMIC);
1127 sg_init_one(sg, data, count);
1128 ret = __send_to_port(port, sg, 1, count, data, false);
1134 * get_chars() is the callback from the hvc_console infrastructure
1135 * when an interrupt is received.
1137 * We call out to fill_readbuf that gets us the required data from the
1138 * buffers that are queued up.
1140 static int get_chars(u32 vtermno, char *buf, int count)
1144 /* If we've not set up the port yet, we have no input to give. */
1145 if (unlikely(early_put_chars))
1148 port = find_port_by_vtermno(vtermno);
1152 /* If we don't have an input queue yet, we can't get input. */
1153 BUG_ON(!port->in_vq);
1155 return fill_readbuf(port, (__force char __user *)buf, count, false);
1158 static void resize_console(struct port *port)
1160 struct virtio_device *vdev;
1162 /* The port could have been hot-unplugged */
1163 if (!port || !is_console_port(port))
1166 vdev = port->portdev->vdev;
1168 /* Don't test F_SIZE at all if we're rproc: not a valid feature! */
1169 if (!is_rproc_serial(vdev) &&
1170 virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE))
1171 hvc_resize(port->cons.hvc, port->cons.ws);
1174 /* We set the configuration at this point, since we now have a tty */
1175 static int notifier_add_vio(struct hvc_struct *hp, int data)
1179 port = find_port_by_vtermno(hp->vtermno);
1183 hp->irq_requested = 1;
1184 resize_console(port);
1189 static void notifier_del_vio(struct hvc_struct *hp, int data)
1191 hp->irq_requested = 0;
1194 /* The operations for console ports. */
1195 static const struct hv_ops hv_ops = {
1196 .get_chars = get_chars,
1197 .put_chars = put_chars,
1198 .notifier_add = notifier_add_vio,
1199 .notifier_del = notifier_del_vio,
1200 .notifier_hangup = notifier_del_vio,
1204 * Console drivers are initialized very early so boot messages can go
1205 * out, so we do things slightly differently from the generic virtio
1206 * initialization of the net and block drivers.
1208 * At this stage, the console is output-only. It's too early to set
1209 * up a virtqueue, so we let the drivers do some boutique early-output
1212 int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int))
1214 early_put_chars = put_chars;
1215 return hvc_instantiate(0, 0, &hv_ops);
1218 static int init_port_console(struct port *port)
1223 * The Host's telling us this port is a console port. Hook it
1224 * up with an hvc console.
1226 * To set up and manage our virtual console, we call
1229 * The first argument of hvc_alloc() is the virtual console
1230 * number. The second argument is the parameter for the
1231 * notification mechanism (like irq number). We currently
1232 * leave this as zero, virtqueues have implicit notifications.
1234 * The third argument is a "struct hv_ops" containing the
1235 * put_chars() get_chars(), notifier_add() and notifier_del()
1236 * pointers. The final argument is the output buffer size: we
1237 * can do any size, so we put PAGE_SIZE here.
1239 ret = ida_alloc_min(&vtermno_ida, 1, GFP_KERNEL);
1243 port->cons.vtermno = ret;
1244 port->cons.hvc = hvc_alloc(port->cons.vtermno, 0, &hv_ops, PAGE_SIZE);
1245 if (IS_ERR(port->cons.hvc)) {
1246 ret = PTR_ERR(port->cons.hvc);
1248 "error %d allocating hvc for port\n", ret);
1249 port->cons.hvc = NULL;
1250 ida_free(&vtermno_ida, port->cons.vtermno);
1253 spin_lock_irq(&pdrvdata_lock);
1254 list_add_tail(&port->cons.list, &pdrvdata.consoles);
1255 spin_unlock_irq(&pdrvdata_lock);
1256 port->guest_connected = true;
1259 * Start using the new console output if this is the first
1260 * console to come up.
1262 if (early_put_chars)
1263 early_put_chars = NULL;
1265 /* Notify host of port being opened */
1266 send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
1271 static ssize_t show_port_name(struct device *dev,
1272 struct device_attribute *attr, char *buffer)
1276 port = dev_get_drvdata(dev);
1278 return sprintf(buffer, "%s\n", port->name);
1281 static DEVICE_ATTR(name, S_IRUGO, show_port_name, NULL);
1283 static struct attribute *port_sysfs_entries[] = {
1284 &dev_attr_name.attr,
1288 static const struct attribute_group port_attribute_group = {
1289 .name = NULL, /* put in device directory */
1290 .attrs = port_sysfs_entries,
1293 static int port_debugfs_show(struct seq_file *s, void *data)
1295 struct port *port = s->private;
1297 seq_printf(s, "name: %s\n", port->name ? port->name : "");
1298 seq_printf(s, "guest_connected: %d\n", port->guest_connected);
1299 seq_printf(s, "host_connected: %d\n", port->host_connected);
1300 seq_printf(s, "outvq_full: %d\n", port->outvq_full);
1301 seq_printf(s, "bytes_sent: %lu\n", port->stats.bytes_sent);
1302 seq_printf(s, "bytes_received: %lu\n", port->stats.bytes_received);
1303 seq_printf(s, "bytes_discarded: %lu\n", port->stats.bytes_discarded);
1304 seq_printf(s, "is_console: %s\n",
1305 is_console_port(port) ? "yes" : "no");
1306 seq_printf(s, "console_vtermno: %u\n", port->cons.vtermno);
1311 DEFINE_SHOW_ATTRIBUTE(port_debugfs);
1313 static void set_console_size(struct port *port, u16 rows, u16 cols)
1315 if (!port || !is_console_port(port))
1318 port->cons.ws.ws_row = rows;
1319 port->cons.ws.ws_col = cols;
1322 static int fill_queue(struct virtqueue *vq, spinlock_t *lock)
1324 struct port_buffer *buf;
1330 buf = alloc_buf(vq->vdev, PAGE_SIZE, 0);
1334 spin_lock_irq(lock);
1335 ret = add_inbuf(vq, buf);
1337 spin_unlock_irq(lock);
1338 free_buf(buf, true);
1342 spin_unlock_irq(lock);
1345 return nr_added_bufs;
1348 static void send_sigio_to_port(struct port *port)
1350 if (port->async_queue && port->guest_connected)
1351 kill_fasync(&port->async_queue, SIGIO, POLL_OUT);
1354 static int add_port(struct ports_device *portdev, u32 id)
1356 char debugfs_name[16];
1361 port = kmalloc(sizeof(*port), GFP_KERNEL);
1366 kref_init(&port->kref);
1368 port->portdev = portdev;
1373 port->cons.hvc = NULL;
1374 port->async_queue = NULL;
1376 port->cons.ws.ws_row = port->cons.ws.ws_col = 0;
1377 port->cons.vtermno = 0;
1379 port->host_connected = port->guest_connected = false;
1380 port->stats = (struct port_stats) { 0 };
1382 port->outvq_full = false;
1384 port->in_vq = portdev->in_vqs[port->id];
1385 port->out_vq = portdev->out_vqs[port->id];
1387 port->cdev = cdev_alloc();
1389 dev_err(&port->portdev->vdev->dev, "Error allocating cdev\n");
1393 port->cdev->ops = &port_fops;
1395 devt = MKDEV(portdev->chr_major, id);
1396 err = cdev_add(port->cdev, devt, 1);
1398 dev_err(&port->portdev->vdev->dev,
1399 "Error %d adding cdev for port %u\n", err, id);
1402 port->dev = device_create(pdrvdata.class, &port->portdev->vdev->dev,
1403 devt, port, "vport%up%u",
1404 port->portdev->vdev->index, id);
1405 if (IS_ERR(port->dev)) {
1406 err = PTR_ERR(port->dev);
1407 dev_err(&port->portdev->vdev->dev,
1408 "Error %d creating device for port %u\n",
1413 spin_lock_init(&port->inbuf_lock);
1414 spin_lock_init(&port->outvq_lock);
1415 init_waitqueue_head(&port->waitqueue);
1417 /* We can safely ignore ENOSPC because it means
1418 * the queue already has buffers. Buffers are removed
1419 * only by virtcons_remove(), not by unplug_port()
1421 err = fill_queue(port->in_vq, &port->inbuf_lock);
1422 if (err < 0 && err != -ENOSPC) {
1423 dev_err(port->dev, "Error allocating inbufs\n");
1427 if (is_rproc_serial(port->portdev->vdev))
1429 * For rproc_serial assume remote processor is connected.
1430 * rproc_serial does not want the console port, only
1431 * the generic port implementation.
1433 port->host_connected = true;
1434 else if (!use_multiport(port->portdev)) {
1436 * If we're not using multiport support,
1437 * this has to be a console port.
1439 err = init_port_console(port);
1444 spin_lock_irq(&portdev->ports_lock);
1445 list_add_tail(&port->list, &port->portdev->ports);
1446 spin_unlock_irq(&portdev->ports_lock);
1449 * Tell the Host we're set so that it can send us various
1450 * configuration parameters for this port (eg, port name,
1451 * caching, whether this is a console port, etc.)
1453 send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1456 * Finally, create the debugfs file that we can use to
1457 * inspect a port's state at any time
1459 snprintf(debugfs_name, sizeof(debugfs_name), "vport%up%u",
1460 port->portdev->vdev->index, id);
1461 port->debugfs_file = debugfs_create_file(debugfs_name, 0444,
1462 pdrvdata.debugfs_dir,
1463 port, &port_debugfs_fops);
1468 device_destroy(pdrvdata.class, port->dev->devt);
1470 cdev_del(port->cdev);
1474 /* The host might want to notify management sw about port add failure */
1475 __send_control_msg(portdev, id, VIRTIO_CONSOLE_PORT_READY, 0);
1479 /* No users remain, remove all port-specific data. */
1480 static void remove_port(struct kref *kref)
1484 port = container_of(kref, struct port, kref);
1489 static void remove_port_data(struct port *port)
1491 spin_lock_irq(&port->inbuf_lock);
1492 /* Remove unused data this port might have received. */
1493 discard_port_data(port);
1494 spin_unlock_irq(&port->inbuf_lock);
1496 spin_lock_irq(&port->outvq_lock);
1497 reclaim_consumed_buffers(port);
1498 spin_unlock_irq(&port->outvq_lock);
1502 * Port got unplugged. Remove port from portdev's list and drop the
1503 * kref reference. If no userspace has this port opened, it will
1504 * result in immediate removal the port.
1506 static void unplug_port(struct port *port)
1508 spin_lock_irq(&port->portdev->ports_lock);
1509 list_del(&port->list);
1510 spin_unlock_irq(&port->portdev->ports_lock);
1512 spin_lock_irq(&port->inbuf_lock);
1513 if (port->guest_connected) {
1514 /* Let the app know the port is going down. */
1515 send_sigio_to_port(port);
1517 /* Do this after sigio is actually sent */
1518 port->guest_connected = false;
1519 port->host_connected = false;
1521 wake_up_interruptible(&port->waitqueue);
1523 spin_unlock_irq(&port->inbuf_lock);
1525 if (is_console_port(port)) {
1526 spin_lock_irq(&pdrvdata_lock);
1527 list_del(&port->cons.list);
1528 spin_unlock_irq(&pdrvdata_lock);
1529 hvc_remove(port->cons.hvc);
1530 ida_free(&vtermno_ida, port->cons.vtermno);
1533 remove_port_data(port);
1536 * We should just assume the device itself has gone off --
1537 * else a close on an open port later will try to send out a
1540 port->portdev = NULL;
1542 sysfs_remove_group(&port->dev->kobj, &port_attribute_group);
1543 device_destroy(pdrvdata.class, port->dev->devt);
1544 cdev_del(port->cdev);
1546 debugfs_remove(port->debugfs_file);
1550 * Locks around here are not necessary - a port can't be
1551 * opened after we removed the port struct from ports_list
1554 kref_put(&port->kref, remove_port);
1557 /* Any private messages that the Host and Guest want to share */
1558 static void handle_control_message(struct virtio_device *vdev,
1559 struct ports_device *portdev,
1560 struct port_buffer *buf)
1562 struct virtio_console_control *cpkt;
1567 cpkt = (struct virtio_console_control *)(buf->buf + buf->offset);
1569 port = find_port_by_id(portdev, virtio32_to_cpu(vdev, cpkt->id));
1571 cpkt->event != cpu_to_virtio16(vdev, VIRTIO_CONSOLE_PORT_ADD)) {
1572 /* No valid header at start of buffer. Drop it. */
1573 dev_dbg(&portdev->vdev->dev,
1574 "Invalid index %u in control packet\n", cpkt->id);
1578 switch (virtio16_to_cpu(vdev, cpkt->event)) {
1579 case VIRTIO_CONSOLE_PORT_ADD:
1581 dev_dbg(&portdev->vdev->dev,
1582 "Port %u already added\n", port->id);
1583 send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1586 if (virtio32_to_cpu(vdev, cpkt->id) >=
1587 portdev->max_nr_ports) {
1588 dev_warn(&portdev->vdev->dev,
1589 "Request for adding port with "
1590 "out-of-bound id %u, max. supported id: %u\n",
1591 cpkt->id, portdev->max_nr_ports - 1);
1594 add_port(portdev, virtio32_to_cpu(vdev, cpkt->id));
1596 case VIRTIO_CONSOLE_PORT_REMOVE:
1599 case VIRTIO_CONSOLE_CONSOLE_PORT:
1602 if (is_console_port(port))
1605 init_port_console(port);
1606 complete(&early_console_added);
1608 * Could remove the port here in case init fails - but
1609 * have to notify the host first.
1612 case VIRTIO_CONSOLE_RESIZE: {
1618 if (!is_console_port(port))
1621 memcpy(&size, buf->buf + buf->offset + sizeof(*cpkt),
1623 set_console_size(port, size.rows, size.cols);
1625 port->cons.hvc->irq_requested = 1;
1626 resize_console(port);
1629 case VIRTIO_CONSOLE_PORT_OPEN:
1630 port->host_connected = virtio16_to_cpu(vdev, cpkt->value);
1631 wake_up_interruptible(&port->waitqueue);
1633 * If the host port got closed and the host had any
1634 * unconsumed buffers, we'll be able to reclaim them
1637 spin_lock_irq(&port->outvq_lock);
1638 reclaim_consumed_buffers(port);
1639 spin_unlock_irq(&port->outvq_lock);
1642 * If the guest is connected, it'll be interested in
1643 * knowing the host connection state changed.
1645 spin_lock_irq(&port->inbuf_lock);
1646 send_sigio_to_port(port);
1647 spin_unlock_irq(&port->inbuf_lock);
1649 case VIRTIO_CONSOLE_PORT_NAME:
1651 * If we woke up after hibernation, we can get this
1652 * again. Skip it in that case.
1658 * Skip the size of the header and the cpkt to get the size
1659 * of the name that was sent
1661 name_size = buf->len - buf->offset - sizeof(*cpkt) + 1;
1663 port->name = kmalloc(name_size, GFP_KERNEL);
1666 "Not enough space to store port name\n");
1669 strncpy(port->name, buf->buf + buf->offset + sizeof(*cpkt),
1671 port->name[name_size - 1] = 0;
1674 * Since we only have one sysfs attribute, 'name',
1675 * create it only if we have a name for the port.
1677 err = sysfs_create_group(&port->dev->kobj,
1678 &port_attribute_group);
1681 "Error %d creating sysfs device attributes\n",
1685 * Generate a udev event so that appropriate
1686 * symlinks can be created based on udev
1689 kobject_uevent(&port->dev->kobj, KOBJ_CHANGE);
1695 static void control_work_handler(struct work_struct *work)
1697 struct ports_device *portdev;
1698 struct virtqueue *vq;
1699 struct port_buffer *buf;
1702 portdev = container_of(work, struct ports_device, control_work);
1703 vq = portdev->c_ivq;
1705 spin_lock(&portdev->c_ivq_lock);
1706 while ((buf = virtqueue_get_buf(vq, &len))) {
1707 spin_unlock(&portdev->c_ivq_lock);
1709 buf->len = min_t(size_t, len, buf->size);
1712 handle_control_message(vq->vdev, portdev, buf);
1714 spin_lock(&portdev->c_ivq_lock);
1715 if (add_inbuf(portdev->c_ivq, buf) < 0) {
1716 dev_warn(&portdev->vdev->dev,
1717 "Error adding buffer to queue\n");
1718 free_buf(buf, false);
1721 spin_unlock(&portdev->c_ivq_lock);
1724 static void flush_bufs(struct virtqueue *vq, bool can_sleep)
1726 struct port_buffer *buf;
1729 while ((buf = virtqueue_get_buf(vq, &len)))
1730 free_buf(buf, can_sleep);
1733 static void out_intr(struct virtqueue *vq)
1737 port = find_port_by_vq(vq->vdev->priv, vq);
1739 flush_bufs(vq, false);
1743 wake_up_interruptible(&port->waitqueue);
1746 static void in_intr(struct virtqueue *vq)
1749 unsigned long flags;
1751 port = find_port_by_vq(vq->vdev->priv, vq);
1753 flush_bufs(vq, false);
1757 spin_lock_irqsave(&port->inbuf_lock, flags);
1758 port->inbuf = get_inbuf(port);
1761 * Normally the port should not accept data when the port is
1762 * closed. For generic serial ports, the host won't (shouldn't)
1763 * send data till the guest is connected. But this condition
1764 * can be reached when a console port is not yet connected (no
1765 * tty is spawned) and the other side sends out data over the
1766 * vring, or when a remote devices start sending data before
1767 * the ports are opened.
1769 * A generic serial port will discard data if not connected,
1770 * while console ports and rproc-serial ports accepts data at
1771 * any time. rproc-serial is initiated with guest_connected to
1772 * false because port_fops_open expects this. Console ports are
1773 * hooked up with an HVC console and is initialized with
1774 * guest_connected to true.
1777 if (!port->guest_connected && !is_rproc_serial(port->portdev->vdev))
1778 discard_port_data(port);
1780 /* Send a SIGIO indicating new data in case the process asked for it */
1781 send_sigio_to_port(port);
1783 spin_unlock_irqrestore(&port->inbuf_lock, flags);
1785 wake_up_interruptible(&port->waitqueue);
1787 if (is_console_port(port) && hvc_poll(port->cons.hvc))
1791 static void control_intr(struct virtqueue *vq)
1793 struct ports_device *portdev;
1795 portdev = vq->vdev->priv;
1796 schedule_work(&portdev->control_work);
1799 static void config_intr(struct virtio_device *vdev)
1801 struct ports_device *portdev;
1803 portdev = vdev->priv;
1805 if (!use_multiport(portdev))
1806 schedule_work(&portdev->config_work);
1809 static void config_work_handler(struct work_struct *work)
1811 struct ports_device *portdev;
1813 portdev = container_of(work, struct ports_device, config_work);
1814 if (!use_multiport(portdev)) {
1815 struct virtio_device *vdev;
1819 vdev = portdev->vdev;
1820 virtio_cread(vdev, struct virtio_console_config, cols, &cols);
1821 virtio_cread(vdev, struct virtio_console_config, rows, &rows);
1823 port = find_port_by_id(portdev, 0);
1824 set_console_size(port, rows, cols);
1827 * We'll use this way of resizing only for legacy
1828 * support. For newer userspace
1829 * (VIRTIO_CONSOLE_F_MULTPORT+), use control messages
1830 * to indicate console size changes so that it can be
1833 resize_console(port);
1837 static int init_vqs(struct ports_device *portdev)
1839 vq_callback_t **io_callbacks;
1841 struct virtqueue **vqs;
1842 u32 i, j, nr_ports, nr_queues;
1845 nr_ports = portdev->max_nr_ports;
1846 nr_queues = use_multiport(portdev) ? (nr_ports + 1) * 2 : 2;
1848 vqs = kmalloc_array(nr_queues, sizeof(struct virtqueue *), GFP_KERNEL);
1849 io_callbacks = kmalloc_array(nr_queues, sizeof(vq_callback_t *),
1851 io_names = kmalloc_array(nr_queues, sizeof(char *), GFP_KERNEL);
1852 portdev->in_vqs = kmalloc_array(nr_ports, sizeof(struct virtqueue *),
1854 portdev->out_vqs = kmalloc_array(nr_ports, sizeof(struct virtqueue *),
1856 if (!vqs || !io_callbacks || !io_names || !portdev->in_vqs ||
1857 !portdev->out_vqs) {
1863 * For backward compat (newer host but older guest), the host
1864 * spawns a console port first and also inits the vqs for port
1868 io_callbacks[j] = in_intr;
1869 io_callbacks[j + 1] = out_intr;
1870 io_names[j] = "input";
1871 io_names[j + 1] = "output";
1874 if (use_multiport(portdev)) {
1875 io_callbacks[j] = control_intr;
1876 io_callbacks[j + 1] = NULL;
1877 io_names[j] = "control-i";
1878 io_names[j + 1] = "control-o";
1880 for (i = 1; i < nr_ports; i++) {
1882 io_callbacks[j] = in_intr;
1883 io_callbacks[j + 1] = out_intr;
1884 io_names[j] = "input";
1885 io_names[j + 1] = "output";
1888 /* Find the queues. */
1889 err = virtio_find_vqs(portdev->vdev, nr_queues, vqs,
1891 (const char **)io_names, NULL);
1896 portdev->in_vqs[0] = vqs[0];
1897 portdev->out_vqs[0] = vqs[1];
1899 if (use_multiport(portdev)) {
1900 portdev->c_ivq = vqs[j];
1901 portdev->c_ovq = vqs[j + 1];
1903 for (i = 1; i < nr_ports; i++) {
1905 portdev->in_vqs[i] = vqs[j];
1906 portdev->out_vqs[i] = vqs[j + 1];
1910 kfree(io_callbacks);
1916 kfree(portdev->out_vqs);
1917 kfree(portdev->in_vqs);
1919 kfree(io_callbacks);
1925 static const struct file_operations portdev_fops = {
1926 .owner = THIS_MODULE,
1929 static void remove_vqs(struct ports_device *portdev)
1931 struct virtqueue *vq;
1933 virtio_device_for_each_vq(portdev->vdev, vq) {
1934 struct port_buffer *buf;
1936 flush_bufs(vq, true);
1937 while ((buf = virtqueue_detach_unused_buf(vq)))
1938 free_buf(buf, true);
1940 portdev->vdev->config->del_vqs(portdev->vdev);
1941 kfree(portdev->in_vqs);
1942 kfree(portdev->out_vqs);
1945 static void virtcons_remove(struct virtio_device *vdev)
1947 struct ports_device *portdev;
1948 struct port *port, *port2;
1950 portdev = vdev->priv;
1952 spin_lock_irq(&pdrvdata_lock);
1953 list_del(&portdev->list);
1954 spin_unlock_irq(&pdrvdata_lock);
1956 /* Device is going away, exit any polling for buffers */
1957 virtio_break_device(vdev);
1958 if (use_multiport(portdev))
1959 flush_work(&portdev->control_work);
1961 flush_work(&portdev->config_work);
1963 /* Disable interrupts for vqs */
1964 virtio_reset_device(vdev);
1965 /* Finish up work that's lined up */
1966 if (use_multiport(portdev))
1967 cancel_work_sync(&portdev->control_work);
1969 cancel_work_sync(&portdev->config_work);
1971 list_for_each_entry_safe(port, port2, &portdev->ports, list)
1974 unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1977 * When yanking out a device, we immediately lose the
1978 * (device-side) queues. So there's no point in keeping the
1979 * guest side around till we drop our final reference. This
1980 * also means that any ports which are in an open state will
1981 * have to just stop using the port, as the vqs are going
1984 remove_vqs(portdev);
1989 * Once we're further in boot, we get probed like any other virtio
1992 * If the host also supports multiple console ports, we check the
1993 * config space to see how many ports the host has spawned. We
1994 * initialize each port found.
1996 static int virtcons_probe(struct virtio_device *vdev)
1998 struct ports_device *portdev;
2001 bool early = early_put_chars != NULL;
2003 /* We only need a config space if features are offered */
2004 if (!vdev->config->get &&
2005 (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE)
2006 || virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT))) {
2007 dev_err(&vdev->dev, "%s failure: config access disabled\n",
2012 /* Ensure to read early_put_chars now */
2015 portdev = kmalloc(sizeof(*portdev), GFP_KERNEL);
2021 /* Attach this portdev to this virtio_device, and vice-versa. */
2022 portdev->vdev = vdev;
2023 vdev->priv = portdev;
2025 portdev->chr_major = register_chrdev(0, "virtio-portsdev",
2027 if (portdev->chr_major < 0) {
2029 "Error %d registering chrdev for device %u\n",
2030 portdev->chr_major, vdev->index);
2031 err = portdev->chr_major;
2036 portdev->max_nr_ports = 1;
2038 /* Don't test MULTIPORT at all if we're rproc: not a valid feature! */
2039 if (!is_rproc_serial(vdev) &&
2040 virtio_cread_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT,
2041 struct virtio_console_config, max_nr_ports,
2042 &portdev->max_nr_ports) == 0) {
2043 if (portdev->max_nr_ports == 0 ||
2044 portdev->max_nr_ports > VIRTCONS_MAX_PORTS) {
2046 "Invalidate max_nr_ports %d",
2047 portdev->max_nr_ports);
2054 err = init_vqs(portdev);
2056 dev_err(&vdev->dev, "Error %d initializing vqs\n", err);
2060 spin_lock_init(&portdev->ports_lock);
2061 INIT_LIST_HEAD(&portdev->ports);
2062 INIT_LIST_HEAD(&portdev->list);
2064 virtio_device_ready(portdev->vdev);
2066 INIT_WORK(&portdev->config_work, &config_work_handler);
2067 INIT_WORK(&portdev->control_work, &control_work_handler);
2070 spin_lock_init(&portdev->c_ivq_lock);
2071 spin_lock_init(&portdev->c_ovq_lock);
2073 err = fill_queue(portdev->c_ivq, &portdev->c_ivq_lock);
2076 "Error allocating buffers for control queue\n");
2078 * The host might want to notify mgmt sw about device
2081 __send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
2082 VIRTIO_CONSOLE_DEVICE_READY, 0);
2083 /* Device was functional: we need full cleanup. */
2084 virtcons_remove(vdev);
2089 * For backward compatibility: Create a console port
2090 * if we're running on older host.
2092 add_port(portdev, 0);
2095 spin_lock_irq(&pdrvdata_lock);
2096 list_add_tail(&portdev->list, &pdrvdata.portdevs);
2097 spin_unlock_irq(&pdrvdata_lock);
2099 __send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
2100 VIRTIO_CONSOLE_DEVICE_READY, 1);
2103 * If there was an early virtio console, assume that there are no
2104 * other consoles. We need to wait until the hvc_alloc matches the
2105 * hvc_instantiate, otherwise tty_open will complain, resulting in
2106 * a "Warning: unable to open an initial console" boot failure.
2107 * Without multiport this is done in add_port above. With multiport
2108 * this might take some host<->guest communication - thus we have to
2111 if (multiport && early)
2112 wait_for_completion(&early_console_added);
2117 unregister_chrdev(portdev->chr_major, "virtio-portsdev");
2124 static const struct virtio_device_id id_table[] = {
2125 { VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID },
2128 MODULE_DEVICE_TABLE(virtio, id_table);
2130 static const unsigned int features[] = {
2131 VIRTIO_CONSOLE_F_SIZE,
2132 VIRTIO_CONSOLE_F_MULTIPORT,
2135 static const struct virtio_device_id rproc_serial_id_table[] = {
2136 #if IS_ENABLED(CONFIG_REMOTEPROC)
2137 { VIRTIO_ID_RPROC_SERIAL, VIRTIO_DEV_ANY_ID },
2141 MODULE_DEVICE_TABLE(virtio, rproc_serial_id_table);
2143 static const unsigned int rproc_serial_features[] = {
2146 #ifdef CONFIG_PM_SLEEP
2147 static int virtcons_freeze(struct virtio_device *vdev)
2149 struct ports_device *portdev;
2152 portdev = vdev->priv;
2154 virtio_reset_device(vdev);
2156 if (use_multiport(portdev))
2157 virtqueue_disable_cb(portdev->c_ivq);
2158 cancel_work_sync(&portdev->control_work);
2159 cancel_work_sync(&portdev->config_work);
2161 * Once more: if control_work_handler() was running, it would
2162 * enable the cb as the last step.
2164 if (use_multiport(portdev))
2165 virtqueue_disable_cb(portdev->c_ivq);
2167 list_for_each_entry(port, &portdev->ports, list) {
2168 virtqueue_disable_cb(port->in_vq);
2169 virtqueue_disable_cb(port->out_vq);
2171 * We'll ask the host later if the new invocation has
2172 * the port opened or closed.
2174 port->host_connected = false;
2175 remove_port_data(port);
2177 remove_vqs(portdev);
2182 static int virtcons_restore(struct virtio_device *vdev)
2184 struct ports_device *portdev;
2188 portdev = vdev->priv;
2190 ret = init_vqs(portdev);
2194 virtio_device_ready(portdev->vdev);
2196 if (use_multiport(portdev))
2197 fill_queue(portdev->c_ivq, &portdev->c_ivq_lock);
2199 list_for_each_entry(port, &portdev->ports, list) {
2200 port->in_vq = portdev->in_vqs[port->id];
2201 port->out_vq = portdev->out_vqs[port->id];
2203 fill_queue(port->in_vq, &port->inbuf_lock);
2205 /* Get port open/close status on the host */
2206 send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
2209 * If a port was open at the time of suspending, we
2210 * have to let the host know that it's still open.
2212 if (port->guest_connected)
2213 send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
2219 static struct virtio_driver virtio_console = {
2220 .feature_table = features,
2221 .feature_table_size = ARRAY_SIZE(features),
2222 .driver.name = KBUILD_MODNAME,
2223 .driver.owner = THIS_MODULE,
2224 .id_table = id_table,
2225 .probe = virtcons_probe,
2226 .remove = virtcons_remove,
2227 .config_changed = config_intr,
2228 #ifdef CONFIG_PM_SLEEP
2229 .freeze = virtcons_freeze,
2230 .restore = virtcons_restore,
2234 static struct virtio_driver virtio_rproc_serial = {
2235 .feature_table = rproc_serial_features,
2236 .feature_table_size = ARRAY_SIZE(rproc_serial_features),
2237 .driver.name = "virtio_rproc_serial",
2238 .driver.owner = THIS_MODULE,
2239 .id_table = rproc_serial_id_table,
2240 .probe = virtcons_probe,
2241 .remove = virtcons_remove,
2244 static int __init virtio_console_init(void)
2248 pdrvdata.class = class_create(THIS_MODULE, "virtio-ports");
2249 if (IS_ERR(pdrvdata.class)) {
2250 err = PTR_ERR(pdrvdata.class);
2251 pr_err("Error %d creating virtio-ports class\n", err);
2255 pdrvdata.debugfs_dir = debugfs_create_dir("virtio-ports", NULL);
2256 INIT_LIST_HEAD(&pdrvdata.consoles);
2257 INIT_LIST_HEAD(&pdrvdata.portdevs);
2259 err = register_virtio_driver(&virtio_console);
2261 pr_err("Error %d registering virtio driver\n", err);
2264 err = register_virtio_driver(&virtio_rproc_serial);
2266 pr_err("Error %d registering virtio rproc serial driver\n",
2272 unregister_virtio_driver(&virtio_console);
2274 debugfs_remove_recursive(pdrvdata.debugfs_dir);
2275 class_destroy(pdrvdata.class);
2279 static void __exit virtio_console_fini(void)
2283 unregister_virtio_driver(&virtio_console);
2284 unregister_virtio_driver(&virtio_rproc_serial);
2286 class_destroy(pdrvdata.class);
2287 debugfs_remove_recursive(pdrvdata.debugfs_dir);
2289 module_init(virtio_console_init);
2290 module_exit(virtio_console_fini);
2292 MODULE_DESCRIPTION("Virtio console driver");
2293 MODULE_LICENSE("GPL");