1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
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>
6 */
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>
13#include <linux/fs.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"
30
31#define is_rproc_enabled IS_ENABLED(CONFIG_REMOTEPROC)
32#define VIRTCONS_MAX_PORTS 0x8000
33
34/*
35 * This is a global struct for storing common data for all the devices
36 * this driver handles.
37 *
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.
41 */
42struct ports_driver_data {
43	/* Used for exporting per-port information to debugfs */
44	struct dentry *debugfs_dir;
45
46	/* List of all the devices we're handling */
47	struct list_head portdevs;
48
49	/* All the console devices handled by this driver */
50	struct list_head consoles;
51};
52
53static struct ports_driver_data pdrvdata;
54
55static const struct class port_class = {
56	.name = "virtio-ports",
57};
58
59static DEFINE_SPINLOCK(pdrvdata_lock);
60static DECLARE_COMPLETION(early_console_added);
61
62/* This struct holds information that's relevant only for console ports */
63struct console {
64	/* We'll place all consoles in a list in the pdrvdata struct */
65	struct list_head list;
66
67	/* The hvc device associated with this console port */
68	struct hvc_struct *hvc;
69
70	/* The size of the console */
71	struct winsize ws;
72
73	/*
74	 * This number identifies the number that we used to register
75	 * with hvc in hvc_instantiate() and hvc_alloc(); this is the
76	 * number passed on by the hvc callbacks to us to
77	 * differentiate between the other console ports handled by
78	 * this driver
79	 */
80	u32 vtermno;
81};
82
83static DEFINE_IDA(vtermno_ida);
84
85struct port_buffer {
86	char *buf;
87
88	/* size of the buffer in *buf above */
89	size_t size;
90
91	/* used length of the buffer */
92	size_t len;
93	/* offset in the buf from which to consume data */
94	size_t offset;
95
96	/* DMA address of buffer */
97	dma_addr_t dma;
98
99	/* Device we got DMA memory from */
100	struct device *dev;
101
102	/* List of pending dma buffers to free */
103	struct list_head list;
104
105	/* If sgpages == 0 then buf is used */
106	unsigned int sgpages;
107
108	/* sg is used if spages > 0. sg must be the last in is struct */
109	struct scatterlist sg[];
110};
111
112/*
113 * This is a per-device struct that stores data common to all the
114 * ports for that device (vdev->priv).
115 */
116struct ports_device {
117	/* Next portdev in the list, head is in the pdrvdata struct */
118	struct list_head list;
119
120	/*
121	 * Workqueue handlers where we process deferred work after
122	 * notification
123	 */
124	struct work_struct control_work;
125	struct work_struct config_work;
126
127	struct list_head ports;
128
129	/* To protect the list of ports */
130	spinlock_t ports_lock;
131
132	/* To protect the vq operations for the control channel */
133	spinlock_t c_ivq_lock;
134	spinlock_t c_ovq_lock;
135
136	/* max. number of ports this device can hold */
137	u32 max_nr_ports;
138
139	/* The virtio device we're associated with */
140	struct virtio_device *vdev;
141
142	/*
143	 * A couple of virtqueues for the control channel: one for
144	 * guest->host transfers, one for host->guest transfers
145	 */
146	struct virtqueue *c_ivq, *c_ovq;
147
148	/*
149	 * A control packet buffer for guest->host requests, protected
150	 * by c_ovq_lock.
151	 */
152	struct virtio_console_control cpkt;
153
154	/* Array of per-port IO virtqueues */
155	struct virtqueue **in_vqs, **out_vqs;
156
157	/* Major number for this device.  Ports will be created as minors. */
158	int chr_major;
159};
160
161struct port_stats {
162	unsigned long bytes_sent, bytes_received, bytes_discarded;
163};
164
165/* This struct holds the per-port data */
166struct port {
167	/* Next port in the list, head is in the ports_device */
168	struct list_head list;
169
170	/* Pointer to the parent virtio_console device */
171	struct ports_device *portdev;
172
173	/* The current buffer from which data has to be fed to readers */
174	struct port_buffer *inbuf;
175
176	/*
177	 * To protect the operations on the in_vq associated with this
178	 * port.  Has to be a spinlock because it can be called from
179	 * interrupt context (get_char()).
180	 */
181	spinlock_t inbuf_lock;
182
183	/* Protect the operations on the out_vq. */
184	spinlock_t outvq_lock;
185
186	/* The IO vqs for this port */
187	struct virtqueue *in_vq, *out_vq;
188
189	/* File in the debugfs directory that exposes this port's information */
190	struct dentry *debugfs_file;
191
192	/*
193	 * Keep count of the bytes sent, received and discarded for
194	 * this port for accounting and debugging purposes.  These
195	 * counts are not reset across port open / close events.
196	 */
197	struct port_stats stats;
198
199	/*
200	 * The entries in this struct will be valid if this port is
201	 * hooked up to an hvc console
202	 */
203	struct console cons;
204
205	/* Each port associates with a separate char device */
206	struct cdev *cdev;
207	struct device *dev;
208
209	/* Reference-counting to handle port hot-unplugs and file operations */
210	struct kref kref;
211
212	/* A waitqueue for poll() or blocking read operations */
213	wait_queue_head_t waitqueue;
214
215	/* The 'name' of the port that we expose via sysfs properties */
216	char *name;
217
218	/* We can notify apps of host connect / disconnect events via SIGIO */
219	struct fasync_struct *async_queue;
220
221	/* The 'id' to identify the port with the Host */
222	u32 id;
223
224	bool outvq_full;
225
226	/* Is the host device open */
227	bool host_connected;
228
229	/* We should allow only one process to open a port */
230	bool guest_connected;
231};
232
233/* This is the very early arch-specified put chars function. */
234static int (*early_put_chars)(u32, const char *, int);
235
236static struct port *find_port_by_vtermno(u32 vtermno)
237{
238	struct port *port;
239	struct console *cons;
240	unsigned long flags;
241
242	spin_lock_irqsave(&pdrvdata_lock, flags);
243	list_for_each_entry(cons, &pdrvdata.consoles, list) {
244		if (cons->vtermno == vtermno) {
245			port = container_of(cons, struct port, cons);
246			goto out;
247		}
248	}
249	port = NULL;
250out:
251	spin_unlock_irqrestore(&pdrvdata_lock, flags);
252	return port;
253}
254
255static struct port *find_port_by_devt_in_portdev(struct ports_device *portdev,
256						 dev_t dev)
257{
258	struct port *port;
259	unsigned long flags;
260
261	spin_lock_irqsave(&portdev->ports_lock, flags);
262	list_for_each_entry(port, &portdev->ports, list) {
263		if (port->cdev->dev == dev) {
264			kref_get(&port->kref);
265			goto out;
266		}
267	}
268	port = NULL;
269out:
270	spin_unlock_irqrestore(&portdev->ports_lock, flags);
271
272	return port;
273}
274
275static struct port *find_port_by_devt(dev_t dev)
276{
277	struct ports_device *portdev;
278	struct port *port;
279	unsigned long flags;
280
281	spin_lock_irqsave(&pdrvdata_lock, flags);
282	list_for_each_entry(portdev, &pdrvdata.portdevs, list) {
283		port = find_port_by_devt_in_portdev(portdev, dev);
284		if (port)
285			goto out;
286	}
287	port = NULL;
288out:
289	spin_unlock_irqrestore(&pdrvdata_lock, flags);
290	return port;
291}
292
293static struct port *find_port_by_id(struct ports_device *portdev, u32 id)
294{
295	struct port *port;
296	unsigned long flags;
297
298	spin_lock_irqsave(&portdev->ports_lock, flags);
299	list_for_each_entry(port, &portdev->ports, list)
300		if (port->id == id)
301			goto out;
302	port = NULL;
303out:
304	spin_unlock_irqrestore(&portdev->ports_lock, flags);
305
306	return port;
307}
308
309static struct port *find_port_by_vq(struct ports_device *portdev,
310				    struct virtqueue *vq)
311{
312	struct port *port;
313	unsigned long flags;
314
315	spin_lock_irqsave(&portdev->ports_lock, flags);
316	list_for_each_entry(port, &portdev->ports, list)
317		if (port->in_vq == vq || port->out_vq == vq)
318			goto out;
319	port = NULL;
320out:
321	spin_unlock_irqrestore(&portdev->ports_lock, flags);
322	return port;
323}
324
325static bool is_console_port(struct port *port)
326{
327	if (port->cons.hvc)
328		return true;
329	return false;
330}
331
332static bool is_rproc_serial(const struct virtio_device *vdev)
333{
334	return is_rproc_enabled && vdev->id.device == VIRTIO_ID_RPROC_SERIAL;
335}
336
337static inline bool use_multiport(struct ports_device *portdev)
338{
339	/*
340	 * This condition can be true when put_chars is called from
341	 * early_init
342	 */
343	if (!portdev->vdev)
344		return false;
345	return __virtio_test_bit(portdev->vdev, VIRTIO_CONSOLE_F_MULTIPORT);
346}
347
348static DEFINE_SPINLOCK(dma_bufs_lock);
349static LIST_HEAD(pending_free_dma_bufs);
350
351static void free_buf(struct port_buffer *buf, bool can_sleep)
352{
353	unsigned int i;
354
355	for (i = 0; i < buf->sgpages; i++) {
356		struct page *page = sg_page(&buf->sg[i]);
357		if (!page)
358			break;
359		put_page(page);
360	}
361
362	if (!buf->dev) {
363		kfree(buf->buf);
364	} else if (is_rproc_enabled) {
365		unsigned long flags;
366
367		/* dma_free_coherent requires interrupts to be enabled. */
368		if (!can_sleep) {
369			/* queue up dma-buffers to be freed later */
370			spin_lock_irqsave(&dma_bufs_lock, flags);
371			list_add_tail(&buf->list, &pending_free_dma_bufs);
372			spin_unlock_irqrestore(&dma_bufs_lock, flags);
373			return;
374		}
375		dma_free_coherent(buf->dev, buf->size, buf->buf, buf->dma);
376
377		/* Release device refcnt and allow it to be freed */
378		put_device(buf->dev);
379	}
380
381	kfree(buf);
382}
383
384static void reclaim_dma_bufs(void)
385{
386	unsigned long flags;
387	struct port_buffer *buf, *tmp;
388	LIST_HEAD(tmp_list);
389
390	if (list_empty(&pending_free_dma_bufs))
391		return;
392
393	/* Create a copy of the pending_free_dma_bufs while holding the lock */
394	spin_lock_irqsave(&dma_bufs_lock, flags);
395	list_cut_position(&tmp_list, &pending_free_dma_bufs,
396			  pending_free_dma_bufs.prev);
397	spin_unlock_irqrestore(&dma_bufs_lock, flags);
398
399	/* Release the dma buffers, without irqs enabled */
400	list_for_each_entry_safe(buf, tmp, &tmp_list, list) {
401		list_del(&buf->list);
402		free_buf(buf, true);
403	}
404}
405
406static struct port_buffer *alloc_buf(struct virtio_device *vdev, size_t buf_size,
407				     int pages)
408{
409	struct port_buffer *buf;
410
411	reclaim_dma_bufs();
412
413	/*
414	 * Allocate buffer and the sg list. The sg list array is allocated
415	 * directly after the port_buffer struct.
416	 */
417	buf = kmalloc(struct_size(buf, sg, pages), GFP_KERNEL);
418	if (!buf)
419		goto fail;
420
421	buf->sgpages = pages;
422	if (pages > 0) {
423		buf->dev = NULL;
424		buf->buf = NULL;
425		return buf;
426	}
427
428	if (is_rproc_serial(vdev)) {
429		/*
430		 * Allocate DMA memory from ancestor. When a virtio
431		 * device is created by remoteproc, the DMA memory is
432		 * associated with the parent device:
433		 * virtioY => remoteprocX#vdevYbuffer.
434		 */
435		buf->dev = vdev->dev.parent;
436		if (!buf->dev)
437			goto free_buf;
438
439		/* Increase device refcnt to avoid freeing it */
440		get_device(buf->dev);
441		buf->buf = dma_alloc_coherent(buf->dev, buf_size, &buf->dma,
442					      GFP_KERNEL);
443	} else {
444		buf->dev = NULL;
445		buf->buf = kmalloc(buf_size, GFP_KERNEL);
446	}
447
448	if (!buf->buf)
449		goto free_buf;
450	buf->len = 0;
451	buf->offset = 0;
452	buf->size = buf_size;
453	return buf;
454
455free_buf:
456	kfree(buf);
457fail:
458	return NULL;
459}
460
461/* Callers should take appropriate locks */
462static struct port_buffer *get_inbuf(struct port *port)
463{
464	struct port_buffer *buf;
465	unsigned int len;
466
467	if (port->inbuf)
468		return port->inbuf;
469
470	buf = virtqueue_get_buf(port->in_vq, &len);
471	if (buf) {
472		buf->len = min_t(size_t, len, buf->size);
473		buf->offset = 0;
474		port->stats.bytes_received += len;
475	}
476	return buf;
477}
478
479/*
480 * Create a scatter-gather list representing our input buffer and put
481 * it in the queue.
482 *
483 * Callers should take appropriate locks.
484 */
485static int add_inbuf(struct virtqueue *vq, struct port_buffer *buf)
486{
487	struct scatterlist sg[1];
488	int ret;
489
490	sg_init_one(sg, buf->buf, buf->size);
491
492	ret = virtqueue_add_inbuf(vq, sg, 1, buf, GFP_ATOMIC);
493	virtqueue_kick(vq);
494	if (!ret)
495		ret = vq->num_free;
496	return ret;
497}
498
499/* Discard any unread data this port has. Callers lockers. */
500static void discard_port_data(struct port *port)
501{
502	struct port_buffer *buf;
503	unsigned int err;
504
505	if (!port->portdev) {
506		/* Device has been unplugged.  vqs are already gone. */
507		return;
508	}
509	buf = get_inbuf(port);
510
511	err = 0;
512	while (buf) {
513		port->stats.bytes_discarded += buf->len - buf->offset;
514		if (add_inbuf(port->in_vq, buf) < 0) {
515			err++;
516			free_buf(buf, false);
517		}
518		port->inbuf = NULL;
519		buf = get_inbuf(port);
520	}
521	if (err)
522		dev_warn(port->dev, "Errors adding %d buffers back to vq\n",
523			 err);
524}
525
526static bool port_has_data(struct port *port)
527{
528	unsigned long flags;
529	bool ret;
530
531	ret = false;
532	spin_lock_irqsave(&port->inbuf_lock, flags);
533	port->inbuf = get_inbuf(port);
534	if (port->inbuf)
535		ret = true;
536
537	spin_unlock_irqrestore(&port->inbuf_lock, flags);
538	return ret;
539}
540
541static ssize_t __send_control_msg(struct ports_device *portdev, u32 port_id,
542				  unsigned int event, unsigned int value)
543{
544	struct scatterlist sg[1];
545	struct virtqueue *vq;
546	unsigned int len;
547
548	if (!use_multiport(portdev))
549		return 0;
550
551	vq = portdev->c_ovq;
552
553	spin_lock(&portdev->c_ovq_lock);
554
555	portdev->cpkt.id = cpu_to_virtio32(portdev->vdev, port_id);
556	portdev->cpkt.event = cpu_to_virtio16(portdev->vdev, event);
557	portdev->cpkt.value = cpu_to_virtio16(portdev->vdev, value);
558
559	sg_init_one(sg, &portdev->cpkt, sizeof(struct virtio_console_control));
560
561	if (virtqueue_add_outbuf(vq, sg, 1, &portdev->cpkt, GFP_ATOMIC) == 0) {
562		virtqueue_kick(vq);
563		while (!virtqueue_get_buf(vq, &len)
564			&& !virtqueue_is_broken(vq))
565			cpu_relax();
566	}
567
568	spin_unlock(&portdev->c_ovq_lock);
569	return 0;
570}
571
572static ssize_t send_control_msg(struct port *port, unsigned int event,
573				unsigned int value)
574{
575	/* Did the port get unplugged before userspace closed it? */
576	if (port->portdev)
577		return __send_control_msg(port->portdev, port->id, event, value);
578	return 0;
579}
580
581
582/* Callers must take the port->outvq_lock */
583static void reclaim_consumed_buffers(struct port *port)
584{
585	struct port_buffer *buf;
586	unsigned int len;
587
588	if (!port->portdev) {
589		/* Device has been unplugged.  vqs are already gone. */
590		return;
591	}
592	while ((buf = virtqueue_get_buf(port->out_vq, &len))) {
593		free_buf(buf, false);
594		port->outvq_full = false;
595	}
596}
597
598static ssize_t __send_to_port(struct port *port, struct scatterlist *sg,
599			      int nents, size_t in_count,
600			      void *data, bool nonblock)
601{
602	struct virtqueue *out_vq;
603	int err;
604	unsigned long flags;
605	unsigned int len;
606
607	out_vq = port->out_vq;
608
609	spin_lock_irqsave(&port->outvq_lock, flags);
610
611	reclaim_consumed_buffers(port);
612
613	err = virtqueue_add_outbuf(out_vq, sg, nents, data, GFP_ATOMIC);
614
615	/* Tell Host to go! */
616	virtqueue_kick(out_vq);
617
618	if (err) {
619		in_count = 0;
620		goto done;
621	}
622
623	if (out_vq->num_free == 0)
624		port->outvq_full = true;
625
626	if (nonblock)
627		goto done;
628
629	/*
630	 * Wait till the host acknowledges it pushed out the data we
631	 * sent.  This is done for data from the hvc_console; the tty
632	 * operations are performed with spinlocks held so we can't
633	 * sleep here.  An alternative would be to copy the data to a
634	 * buffer and relax the spinning requirement.  The downside is
635	 * we need to kmalloc a GFP_ATOMIC buffer each time the
636	 * console driver writes something out.
637	 */
638	while (!virtqueue_get_buf(out_vq, &len)
639		&& !virtqueue_is_broken(out_vq))
640		cpu_relax();
641done:
642	spin_unlock_irqrestore(&port->outvq_lock, flags);
643
644	port->stats.bytes_sent += in_count;
645	/*
646	 * We're expected to return the amount of data we wrote -- all
647	 * of it
648	 */
649	return in_count;
650}
651
652/*
653 * Give out the data that's requested from the buffer that we have
654 * queued up.
655 */
656static ssize_t fill_readbuf(struct port *port, char __user *out_buf,
657			    size_t out_count, bool to_user)
658{
659	struct port_buffer *buf;
660	unsigned long flags;
661
662	if (!out_count || !port_has_data(port))
663		return 0;
664
665	buf = port->inbuf;
666	out_count = min(out_count, buf->len - buf->offset);
667
668	if (to_user) {
669		ssize_t ret;
670
671		ret = copy_to_user(out_buf, buf->buf + buf->offset, out_count);
672		if (ret)
673			return -EFAULT;
674	} else {
675		memcpy((__force char *)out_buf, buf->buf + buf->offset,
676		       out_count);
677	}
678
679	buf->offset += out_count;
680
681	if (buf->offset == buf->len) {
682		/*
683		 * We're done using all the data in this buffer.
684		 * Re-queue so that the Host can send us more data.
685		 */
686		spin_lock_irqsave(&port->inbuf_lock, flags);
687		port->inbuf = NULL;
688
689		if (add_inbuf(port->in_vq, buf) < 0)
690			dev_warn(port->dev, "failed add_buf\n");
691
692		spin_unlock_irqrestore(&port->inbuf_lock, flags);
693	}
694	/* Return the number of bytes actually copied */
695	return out_count;
696}
697
698/* The condition that must be true for polling to end */
699static bool will_read_block(struct port *port)
700{
701	if (!port->guest_connected) {
702		/* Port got hot-unplugged. Let's exit. */
703		return false;
704	}
705	return !port_has_data(port) && port->host_connected;
706}
707
708static bool will_write_block(struct port *port)
709{
710	bool ret;
711
712	if (!port->guest_connected) {
713		/* Port got hot-unplugged. Let's exit. */
714		return false;
715	}
716	if (!port->host_connected)
717		return true;
718
719	spin_lock_irq(&port->outvq_lock);
720	/*
721	 * Check if the Host has consumed any buffers since we last
722	 * sent data (this is only applicable for nonblocking ports).
723	 */
724	reclaim_consumed_buffers(port);
725	ret = port->outvq_full;
726	spin_unlock_irq(&port->outvq_lock);
727
728	return ret;
729}
730
731static ssize_t port_fops_read(struct file *filp, char __user *ubuf,
732			      size_t count, loff_t *offp)
733{
734	struct port *port;
735	ssize_t ret;
736
737	port = filp->private_data;
738
739	/* Port is hot-unplugged. */
740	if (!port->guest_connected)
741		return -ENODEV;
742
743	if (!port_has_data(port)) {
744		/*
745		 * If nothing's connected on the host just return 0 in
746		 * case of list_empty; this tells the userspace app
747		 * that there's no connection
748		 */
749		if (!port->host_connected)
750			return 0;
751		if (filp->f_flags & O_NONBLOCK)
752			return -EAGAIN;
753
754		ret = wait_event_freezable(port->waitqueue,
755					   !will_read_block(port));
756		if (ret < 0)
757			return ret;
758	}
759	/* Port got hot-unplugged while we were waiting above. */
760	if (!port->guest_connected)
761		return -ENODEV;
762	/*
763	 * We could've received a disconnection message while we were
764	 * waiting for more data.
765	 *
766	 * This check is not clubbed in the if() statement above as we
767	 * might receive some data as well as the host could get
768	 * disconnected after we got woken up from our wait.  So we
769	 * really want to give off whatever data we have and only then
770	 * check for host_connected.
771	 */
772	if (!port_has_data(port) && !port->host_connected)
773		return 0;
774
775	return fill_readbuf(port, ubuf, count, true);
776}
777
778static int wait_port_writable(struct port *port, bool nonblock)
779{
780	int ret;
781
782	if (will_write_block(port)) {
783		if (nonblock)
784			return -EAGAIN;
785
786		ret = wait_event_freezable(port->waitqueue,
787					   !will_write_block(port));
788		if (ret < 0)
789			return ret;
790	}
791	/* Port got hot-unplugged. */
792	if (!port->guest_connected)
793		return -ENODEV;
794
795	return 0;
796}
797
798static ssize_t port_fops_write(struct file *filp, const char __user *ubuf,
799			       size_t count, loff_t *offp)
800{
801	struct port *port;
802	struct port_buffer *buf;
803	ssize_t ret;
804	bool nonblock;
805	struct scatterlist sg[1];
806
807	/* Userspace could be out to fool us */
808	if (!count)
809		return 0;
810
811	port = filp->private_data;
812
813	nonblock = filp->f_flags & O_NONBLOCK;
814
815	ret = wait_port_writable(port, nonblock);
816	if (ret < 0)
817		return ret;
818
819	count = min((size_t)(32 * 1024), count);
820
821	buf = alloc_buf(port->portdev->vdev, count, 0);
822	if (!buf)
823		return -ENOMEM;
824
825	ret = copy_from_user(buf->buf, ubuf, count);
826	if (ret) {
827		ret = -EFAULT;
828		goto free_buf;
829	}
830
831	/*
832	 * We now ask send_buf() to not spin for generic ports -- we
833	 * can re-use the same code path that non-blocking file
834	 * descriptors take for blocking file descriptors since the
835	 * wait is already done and we're certain the write will go
836	 * through to the host.
837	 */
838	nonblock = true;
839	sg_init_one(sg, buf->buf, count);
840	ret = __send_to_port(port, sg, 1, count, buf, nonblock);
841
842	if (nonblock && ret > 0)
843		goto out;
844
845free_buf:
846	free_buf(buf, true);
847out:
848	return ret;
849}
850
851struct sg_list {
852	unsigned int n;
853	unsigned int size;
854	size_t len;
855	struct scatterlist *sg;
856};
857
858static int pipe_to_sg(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
859			struct splice_desc *sd)
860{
861	struct sg_list *sgl = sd->u.data;
862	unsigned int offset, len;
863
864	if (sgl->n == sgl->size)
865		return 0;
866
867	/* Try lock this page */
868	if (pipe_buf_try_steal(pipe, buf)) {
869		/* Get reference and unlock page for moving */
870		get_page(buf->page);
871		unlock_page(buf->page);
872
873		len = min(buf->len, sd->len);
874		sg_set_page(&(sgl->sg[sgl->n]), buf->page, len, buf->offset);
875	} else {
876		/* Failback to copying a page */
877		struct page *page = alloc_page(GFP_KERNEL);
878		char *src;
879
880		if (!page)
881			return -ENOMEM;
882
883		offset = sd->pos & ~PAGE_MASK;
884
885		len = sd->len;
886		if (len + offset > PAGE_SIZE)
887			len = PAGE_SIZE - offset;
888
889		src = kmap_atomic(buf->page);
890		memcpy(page_address(page) + offset, src + buf->offset, len);
891		kunmap_atomic(src);
892
893		sg_set_page(&(sgl->sg[sgl->n]), page, len, offset);
894	}
895	sgl->n++;
896	sgl->len += len;
897
898	return len;
899}
900
901/* Faster zero-copy write by splicing */
902static ssize_t port_fops_splice_write(struct pipe_inode_info *pipe,
903				      struct file *filp, loff_t *ppos,
904				      size_t len, unsigned int flags)
905{
906	struct port *port = filp->private_data;
907	struct sg_list sgl;
908	ssize_t ret;
909	struct port_buffer *buf;
910	struct splice_desc sd = {
911		.total_len = len,
912		.flags = flags,
913		.pos = *ppos,
914		.u.data = &sgl,
915	};
916	unsigned int occupancy;
917
918	/*
919	 * Rproc_serial does not yet support splice. To support splice
920	 * pipe_to_sg() must allocate dma-buffers and copy content from
921	 * regular pages to dma pages. And alloc_buf and free_buf must
922	 * support allocating and freeing such a list of dma-buffers.
923	 */
924	if (is_rproc_serial(port->out_vq->vdev))
925		return -EINVAL;
926
927	pipe_lock(pipe);
928	ret = 0;
929	if (pipe_empty(pipe->head, pipe->tail))
930		goto error_out;
931
932	ret = wait_port_writable(port, filp->f_flags & O_NONBLOCK);
933	if (ret < 0)
934		goto error_out;
935
936	occupancy = pipe_occupancy(pipe->head, pipe->tail);
937	buf = alloc_buf(port->portdev->vdev, 0, occupancy);
938
939	if (!buf) {
940		ret = -ENOMEM;
941		goto error_out;
942	}
943
944	sgl.n = 0;
945	sgl.len = 0;
946	sgl.size = occupancy;
947	sgl.sg = buf->sg;
948	sg_init_table(sgl.sg, sgl.size);
949	ret = __splice_from_pipe(pipe, &sd, pipe_to_sg);
950	pipe_unlock(pipe);
951	if (likely(ret > 0))
952		ret = __send_to_port(port, buf->sg, sgl.n, sgl.len, buf, true);
953
954	if (unlikely(ret <= 0))
955		free_buf(buf, true);
956	return ret;
957
958error_out:
959	pipe_unlock(pipe);
960	return ret;
961}
962
963static __poll_t port_fops_poll(struct file *filp, poll_table *wait)
964{
965	struct port *port;
966	__poll_t ret;
967
968	port = filp->private_data;
969	poll_wait(filp, &port->waitqueue, wait);
970
971	if (!port->guest_connected) {
972		/* Port got unplugged */
973		return EPOLLHUP;
974	}
975	ret = 0;
976	if (!will_read_block(port))
977		ret |= EPOLLIN | EPOLLRDNORM;
978	if (!will_write_block(port))
979		ret |= EPOLLOUT;
980	if (!port->host_connected)
981		ret |= EPOLLHUP;
982
983	return ret;
984}
985
986static void remove_port(struct kref *kref);
987
988static int port_fops_release(struct inode *inode, struct file *filp)
989{
990	struct port *port;
991
992	port = filp->private_data;
993
994	/* Notify host of port being closed */
995	send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
996
997	spin_lock_irq(&port->inbuf_lock);
998	port->guest_connected = false;
999
1000	discard_port_data(port);
1001
1002	spin_unlock_irq(&port->inbuf_lock);
1003
1004	spin_lock_irq(&port->outvq_lock);
1005	reclaim_consumed_buffers(port);
1006	spin_unlock_irq(&port->outvq_lock);
1007
1008	reclaim_dma_bufs();
1009	/*
1010	 * Locks aren't necessary here as a port can't be opened after
1011	 * unplug, and if a port isn't unplugged, a kref would already
1012	 * exist for the port.  Plus, taking ports_lock here would
1013	 * create a dependency on other locks taken by functions
1014	 * inside remove_port if we're the last holder of the port,
1015	 * creating many problems.
1016	 */
1017	kref_put(&port->kref, remove_port);
1018
1019	return 0;
1020}
1021
1022static int port_fops_open(struct inode *inode, struct file *filp)
1023{
1024	struct cdev *cdev = inode->i_cdev;
1025	struct port *port;
1026	int ret;
1027
1028	/* We get the port with a kref here */
1029	port = find_port_by_devt(cdev->dev);
1030	if (!port) {
1031		/* Port was unplugged before we could proceed */
1032		return -ENXIO;
1033	}
1034	filp->private_data = port;
1035
1036	/*
1037	 * Don't allow opening of console port devices -- that's done
1038	 * via /dev/hvc
1039	 */
1040	if (is_console_port(port)) {
1041		ret = -ENXIO;
1042		goto out;
1043	}
1044
1045	/* Allow only one process to open a particular port at a time */
1046	spin_lock_irq(&port->inbuf_lock);
1047	if (port->guest_connected) {
1048		spin_unlock_irq(&port->inbuf_lock);
1049		ret = -EBUSY;
1050		goto out;
1051	}
1052
1053	port->guest_connected = true;
1054	spin_unlock_irq(&port->inbuf_lock);
1055
1056	spin_lock_irq(&port->outvq_lock);
1057	/*
1058	 * There might be a chance that we missed reclaiming a few
1059	 * buffers in the window of the port getting previously closed
1060	 * and opening now.
1061	 */
1062	reclaim_consumed_buffers(port);
1063	spin_unlock_irq(&port->outvq_lock);
1064
1065	nonseekable_open(inode, filp);
1066
1067	/* Notify host of port being opened */
1068	send_control_msg(filp->private_data, VIRTIO_CONSOLE_PORT_OPEN, 1);
1069
1070	return 0;
1071out:
1072	kref_put(&port->kref, remove_port);
1073	return ret;
1074}
1075
1076static int port_fops_fasync(int fd, struct file *filp, int mode)
1077{
1078	struct port *port;
1079
1080	port = filp->private_data;
1081	return fasync_helper(fd, filp, mode, &port->async_queue);
1082}
1083
1084/*
1085 * The file operations that we support: programs in the guest can open
1086 * a console device, read from it, write to it, poll for data and
1087 * close it.  The devices are at
1088 *   /dev/vport<device number>p<port number>
1089 */
1090static const struct file_operations port_fops = {
1091	.owner = THIS_MODULE,
1092	.open  = port_fops_open,
1093	.read  = port_fops_read,
1094	.write = port_fops_write,
1095	.splice_write = port_fops_splice_write,
1096	.poll  = port_fops_poll,
1097	.release = port_fops_release,
1098	.fasync = port_fops_fasync,
1099	.llseek = no_llseek,
1100};
1101
1102/*
1103 * The put_chars() callback is pretty straightforward.
1104 *
1105 * We turn the characters into a scatter-gather list, add it to the
1106 * output queue and then kick the Host.  Then we sit here waiting for
1107 * it to finish: inefficient in theory, but in practice
1108 * implementations will do it immediately.
1109 */
1110static int put_chars(u32 vtermno, const char *buf, int count)
1111{
1112	struct port *port;
1113	struct scatterlist sg[1];
1114	void *data;
1115	int ret;
1116
1117	if (unlikely(early_put_chars))
1118		return early_put_chars(vtermno, buf, count);
1119
1120	port = find_port_by_vtermno(vtermno);
1121	if (!port)
1122		return -EPIPE;
1123
1124	data = kmemdup(buf, count, GFP_ATOMIC);
1125	if (!data)
1126		return -ENOMEM;
1127
1128	sg_init_one(sg, data, count);
1129	ret = __send_to_port(port, sg, 1, count, data, false);
1130	kfree(data);
1131	return ret;
1132}
1133
1134/*
1135 * get_chars() is the callback from the hvc_console infrastructure
1136 * when an interrupt is received.
1137 *
1138 * We call out to fill_readbuf that gets us the required data from the
1139 * buffers that are queued up.
1140 */
1141static int get_chars(u32 vtermno, char *buf, int count)
1142{
1143	struct port *port;
1144
1145	/* If we've not set up the port yet, we have no input to give. */
1146	if (unlikely(early_put_chars))
1147		return 0;
1148
1149	port = find_port_by_vtermno(vtermno);
1150	if (!port)
1151		return -EPIPE;
1152
1153	/* If we don't have an input queue yet, we can't get input. */
1154	BUG_ON(!port->in_vq);
1155
1156	return fill_readbuf(port, (__force char __user *)buf, count, false);
1157}
1158
1159static void resize_console(struct port *port)
1160{
1161	struct virtio_device *vdev;
1162
1163	/* The port could have been hot-unplugged */
1164	if (!port || !is_console_port(port))
1165		return;
1166
1167	vdev = port->portdev->vdev;
1168
1169	/* Don't test F_SIZE at all if we're rproc: not a valid feature! */
1170	if (!is_rproc_serial(vdev) &&
1171	    virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE))
1172		hvc_resize(port->cons.hvc, port->cons.ws);
1173}
1174
1175/* We set the configuration at this point, since we now have a tty */
1176static int notifier_add_vio(struct hvc_struct *hp, int data)
1177{
1178	struct port *port;
1179
1180	port = find_port_by_vtermno(hp->vtermno);
1181	if (!port)
1182		return -EINVAL;
1183
1184	hp->irq_requested = 1;
1185	resize_console(port);
1186
1187	return 0;
1188}
1189
1190static void notifier_del_vio(struct hvc_struct *hp, int data)
1191{
1192	hp->irq_requested = 0;
1193}
1194
1195/* The operations for console ports. */
1196static const struct hv_ops hv_ops = {
1197	.get_chars = get_chars,
1198	.put_chars = put_chars,
1199	.notifier_add = notifier_add_vio,
1200	.notifier_del = notifier_del_vio,
1201	.notifier_hangup = notifier_del_vio,
1202};
1203
1204/*
1205 * Console drivers are initialized very early so boot messages can go
1206 * out, so we do things slightly differently from the generic virtio
1207 * initialization of the net and block drivers.
1208 *
1209 * At this stage, the console is output-only.  It's too early to set
1210 * up a virtqueue, so we let the drivers do some boutique early-output
1211 * thing.
1212 */
1213int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int))
1214{
1215	early_put_chars = put_chars;
1216	return hvc_instantiate(0, 0, &hv_ops);
1217}
1218
1219static int init_port_console(struct port *port)
1220{
1221	int ret;
1222
1223	/*
1224	 * The Host's telling us this port is a console port.  Hook it
1225	 * up with an hvc console.
1226	 *
1227	 * To set up and manage our virtual console, we call
1228	 * hvc_alloc().
1229	 *
1230	 * The first argument of hvc_alloc() is the virtual console
1231	 * number.  The second argument is the parameter for the
1232	 * notification mechanism (like irq number).  We currently
1233	 * leave this as zero, virtqueues have implicit notifications.
1234	 *
1235	 * The third argument is a "struct hv_ops" containing the
1236	 * put_chars() get_chars(), notifier_add() and notifier_del()
1237	 * pointers.  The final argument is the output buffer size: we
1238	 * can do any size, so we put PAGE_SIZE here.
1239	 */
1240	ret = ida_alloc_min(&vtermno_ida, 1, GFP_KERNEL);
1241	if (ret < 0)
1242		return ret;
1243
1244	port->cons.vtermno = ret;
1245	port->cons.hvc = hvc_alloc(port->cons.vtermno, 0, &hv_ops, PAGE_SIZE);
1246	if (IS_ERR(port->cons.hvc)) {
1247		ret = PTR_ERR(port->cons.hvc);
1248		dev_err(port->dev,
1249			"error %d allocating hvc for port\n", ret);
1250		port->cons.hvc = NULL;
1251		ida_free(&vtermno_ida, port->cons.vtermno);
1252		return ret;
1253	}
1254	spin_lock_irq(&pdrvdata_lock);
1255	list_add_tail(&port->cons.list, &pdrvdata.consoles);
1256	spin_unlock_irq(&pdrvdata_lock);
1257	port->guest_connected = true;
1258
1259	/*
1260	 * Start using the new console output if this is the first
1261	 * console to come up.
1262	 */
1263	if (early_put_chars)
1264		early_put_chars = NULL;
1265
1266	/* Notify host of port being opened */
1267	send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
1268
1269	return 0;
1270}
1271
1272static ssize_t show_port_name(struct device *dev,
1273			      struct device_attribute *attr, char *buffer)
1274{
1275	struct port *port;
1276
1277	port = dev_get_drvdata(dev);
1278
1279	return sprintf(buffer, "%s\n", port->name);
1280}
1281
1282static DEVICE_ATTR(name, S_IRUGO, show_port_name, NULL);
1283
1284static struct attribute *port_sysfs_entries[] = {
1285	&dev_attr_name.attr,
1286	NULL
1287};
1288
1289static const struct attribute_group port_attribute_group = {
1290	.name = NULL,		/* put in device directory */
1291	.attrs = port_sysfs_entries,
1292};
1293
1294static int port_debugfs_show(struct seq_file *s, void *data)
1295{
1296	struct port *port = s->private;
1297
1298	seq_printf(s, "name: %s\n", port->name ? port->name : "");
1299	seq_printf(s, "guest_connected: %d\n", port->guest_connected);
1300	seq_printf(s, "host_connected: %d\n", port->host_connected);
1301	seq_printf(s, "outvq_full: %d\n", port->outvq_full);
1302	seq_printf(s, "bytes_sent: %lu\n", port->stats.bytes_sent);
1303	seq_printf(s, "bytes_received: %lu\n", port->stats.bytes_received);
1304	seq_printf(s, "bytes_discarded: %lu\n", port->stats.bytes_discarded);
1305	seq_printf(s, "is_console: %s\n",
1306		   is_console_port(port) ? "yes" : "no");
1307	seq_printf(s, "console_vtermno: %u\n", port->cons.vtermno);
1308
1309	return 0;
1310}
1311
1312DEFINE_SHOW_ATTRIBUTE(port_debugfs);
1313
1314static void set_console_size(struct port *port, u16 rows, u16 cols)
1315{
1316	if (!port || !is_console_port(port))
1317		return;
1318
1319	port->cons.ws.ws_row = rows;
1320	port->cons.ws.ws_col = cols;
1321}
1322
1323static int fill_queue(struct virtqueue *vq, spinlock_t *lock)
1324{
1325	struct port_buffer *buf;
1326	int nr_added_bufs;
1327	int ret;
1328
1329	nr_added_bufs = 0;
1330	do {
1331		buf = alloc_buf(vq->vdev, PAGE_SIZE, 0);
1332		if (!buf)
1333			return -ENOMEM;
1334
1335		spin_lock_irq(lock);
1336		ret = add_inbuf(vq, buf);
1337		if (ret < 0) {
1338			spin_unlock_irq(lock);
1339			free_buf(buf, true);
1340			return ret;
1341		}
1342		nr_added_bufs++;
1343		spin_unlock_irq(lock);
1344	} while (ret > 0);
1345
1346	return nr_added_bufs;
1347}
1348
1349static void send_sigio_to_port(struct port *port)
1350{
1351	if (port->async_queue && port->guest_connected)
1352		kill_fasync(&port->async_queue, SIGIO, POLL_OUT);
1353}
1354
1355static int add_port(struct ports_device *portdev, u32 id)
1356{
1357	char debugfs_name[16];
1358	struct port *port;
1359	dev_t devt;
1360	int err;
1361
1362	port = kmalloc(sizeof(*port), GFP_KERNEL);
1363	if (!port) {
1364		err = -ENOMEM;
1365		goto fail;
1366	}
1367	kref_init(&port->kref);
1368
1369	port->portdev = portdev;
1370	port->id = id;
1371
1372	port->name = NULL;
1373	port->inbuf = NULL;
1374	port->cons.hvc = NULL;
1375	port->async_queue = NULL;
1376
1377	port->cons.ws.ws_row = port->cons.ws.ws_col = 0;
1378	port->cons.vtermno = 0;
1379
1380	port->host_connected = port->guest_connected = false;
1381	port->stats = (struct port_stats) { 0 };
1382
1383	port->outvq_full = false;
1384
1385	port->in_vq = portdev->in_vqs[port->id];
1386	port->out_vq = portdev->out_vqs[port->id];
1387
1388	port->cdev = cdev_alloc();
1389	if (!port->cdev) {
1390		dev_err(&port->portdev->vdev->dev, "Error allocating cdev\n");
1391		err = -ENOMEM;
1392		goto free_port;
1393	}
1394	port->cdev->ops = &port_fops;
1395
1396	devt = MKDEV(portdev->chr_major, id);
1397	err = cdev_add(port->cdev, devt, 1);
1398	if (err < 0) {
1399		dev_err(&port->portdev->vdev->dev,
1400			"Error %d adding cdev for port %u\n", err, id);
1401		goto free_cdev;
1402	}
1403	port->dev = device_create(&port_class, &port->portdev->vdev->dev,
1404				  devt, port, "vport%up%u",
1405				  port->portdev->vdev->index, id);
1406	if (IS_ERR(port->dev)) {
1407		err = PTR_ERR(port->dev);
1408		dev_err(&port->portdev->vdev->dev,
1409			"Error %d creating device for port %u\n",
1410			err, id);
1411		goto free_cdev;
1412	}
1413
1414	spin_lock_init(&port->inbuf_lock);
1415	spin_lock_init(&port->outvq_lock);
1416	init_waitqueue_head(&port->waitqueue);
1417
1418	/* We can safely ignore ENOSPC because it means
1419	 * the queue already has buffers. Buffers are removed
1420	 * only by virtcons_remove(), not by unplug_port()
1421	 */
1422	err = fill_queue(port->in_vq, &port->inbuf_lock);
1423	if (err < 0 && err != -ENOSPC) {
1424		dev_err(port->dev, "Error allocating inbufs\n");
1425		goto free_device;
1426	}
1427
1428	if (is_rproc_serial(port->portdev->vdev))
1429		/*
1430		 * For rproc_serial assume remote processor is connected.
1431		 * rproc_serial does not want the console port, only
1432		 * the generic port implementation.
1433		 */
1434		port->host_connected = true;
1435	else if (!use_multiport(port->portdev)) {
1436		/*
1437		 * If we're not using multiport support,
1438		 * this has to be a console port.
1439		 */
1440		err = init_port_console(port);
1441		if (err)
1442			goto free_inbufs;
1443	}
1444
1445	spin_lock_irq(&portdev->ports_lock);
1446	list_add_tail(&port->list, &port->portdev->ports);
1447	spin_unlock_irq(&portdev->ports_lock);
1448
1449	/*
1450	 * Tell the Host we're set so that it can send us various
1451	 * configuration parameters for this port (eg, port name,
1452	 * caching, whether this is a console port, etc.)
1453	 */
1454	send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1455
1456	/*
1457	 * Finally, create the debugfs file that we can use to
1458	 * inspect a port's state at any time
1459	 */
1460	snprintf(debugfs_name, sizeof(debugfs_name), "vport%up%u",
1461		 port->portdev->vdev->index, id);
1462	port->debugfs_file = debugfs_create_file(debugfs_name, 0444,
1463						 pdrvdata.debugfs_dir,
1464						 port, &port_debugfs_fops);
1465	return 0;
1466
1467free_inbufs:
1468free_device:
1469	device_destroy(&port_class, port->dev->devt);
1470free_cdev:
1471	cdev_del(port->cdev);
1472free_port:
1473	kfree(port);
1474fail:
1475	/* The host might want to notify management sw about port add failure */
1476	__send_control_msg(portdev, id, VIRTIO_CONSOLE_PORT_READY, 0);
1477	return err;
1478}
1479
1480/* No users remain, remove all port-specific data. */
1481static void remove_port(struct kref *kref)
1482{
1483	struct port *port;
1484
1485	port = container_of(kref, struct port, kref);
1486
1487	kfree(port);
1488}
1489
1490static void remove_port_data(struct port *port)
1491{
1492	spin_lock_irq(&port->inbuf_lock);
1493	/* Remove unused data this port might have received. */
1494	discard_port_data(port);
1495	spin_unlock_irq(&port->inbuf_lock);
1496
1497	spin_lock_irq(&port->outvq_lock);
1498	reclaim_consumed_buffers(port);
1499	spin_unlock_irq(&port->outvq_lock);
1500}
1501
1502/*
1503 * Port got unplugged.  Remove port from portdev's list and drop the
1504 * kref reference.  If no userspace has this port opened, it will
1505 * result in immediate removal the port.
1506 */
1507static void unplug_port(struct port *port)
1508{
1509	spin_lock_irq(&port->portdev->ports_lock);
1510	list_del(&port->list);
1511	spin_unlock_irq(&port->portdev->ports_lock);
1512
1513	spin_lock_irq(&port->inbuf_lock);
1514	if (port->guest_connected) {
1515		/* Let the app know the port is going down. */
1516		send_sigio_to_port(port);
1517
1518		/* Do this after sigio is actually sent */
1519		port->guest_connected = false;
1520		port->host_connected = false;
1521
1522		wake_up_interruptible(&port->waitqueue);
1523	}
1524	spin_unlock_irq(&port->inbuf_lock);
1525
1526	if (is_console_port(port)) {
1527		spin_lock_irq(&pdrvdata_lock);
1528		list_del(&port->cons.list);
1529		spin_unlock_irq(&pdrvdata_lock);
1530		hvc_remove(port->cons.hvc);
1531		ida_free(&vtermno_ida, port->cons.vtermno);
1532	}
1533
1534	remove_port_data(port);
1535
1536	/*
1537	 * We should just assume the device itself has gone off --
1538	 * else a close on an open port later will try to send out a
1539	 * control message.
1540	 */
1541	port->portdev = NULL;
1542
1543	sysfs_remove_group(&port->dev->kobj, &port_attribute_group);
1544	device_destroy(&port_class, port->dev->devt);
1545	cdev_del(port->cdev);
1546
1547	debugfs_remove(port->debugfs_file);
1548	kfree(port->name);
1549
1550	/*
1551	 * Locks around here are not necessary - a port can't be
1552	 * opened after we removed the port struct from ports_list
1553	 * above.
1554	 */
1555	kref_put(&port->kref, remove_port);
1556}
1557
1558/* Any private messages that the Host and Guest want to share */
1559static void handle_control_message(struct virtio_device *vdev,
1560				   struct ports_device *portdev,
1561				   struct port_buffer *buf)
1562{
1563	struct virtio_console_control *cpkt;
1564	struct port *port;
1565	size_t name_size;
1566	int err;
1567
1568	cpkt = (struct virtio_console_control *)(buf->buf + buf->offset);
1569
1570	port = find_port_by_id(portdev, virtio32_to_cpu(vdev, cpkt->id));
1571	if (!port &&
1572	    cpkt->event != cpu_to_virtio16(vdev, VIRTIO_CONSOLE_PORT_ADD)) {
1573		/* No valid header at start of buffer.  Drop it. */
1574		dev_dbg(&portdev->vdev->dev,
1575			"Invalid index %u in control packet\n", cpkt->id);
1576		return;
1577	}
1578
1579	switch (virtio16_to_cpu(vdev, cpkt->event)) {
1580	case VIRTIO_CONSOLE_PORT_ADD:
1581		if (port) {
1582			dev_dbg(&portdev->vdev->dev,
1583				"Port %u already added\n", port->id);
1584			send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1585			break;
1586		}
1587		if (virtio32_to_cpu(vdev, cpkt->id) >=
1588		    portdev->max_nr_ports) {
1589			dev_warn(&portdev->vdev->dev,
1590				"Request for adding port with "
1591				"out-of-bound id %u, max. supported id: %u\n",
1592				cpkt->id, portdev->max_nr_ports - 1);
1593			break;
1594		}
1595		add_port(portdev, virtio32_to_cpu(vdev, cpkt->id));
1596		break;
1597	case VIRTIO_CONSOLE_PORT_REMOVE:
1598		unplug_port(port);
1599		break;
1600	case VIRTIO_CONSOLE_CONSOLE_PORT:
1601		if (!cpkt->value)
1602			break;
1603		if (is_console_port(port))
1604			break;
1605
1606		init_port_console(port);
1607		complete(&early_console_added);
1608		/*
1609		 * Could remove the port here in case init fails - but
1610		 * have to notify the host first.
1611		 */
1612		break;
1613	case VIRTIO_CONSOLE_RESIZE: {
1614		struct {
1615			__u16 rows;
1616			__u16 cols;
1617		} size;
1618
1619		if (!is_console_port(port))
1620			break;
1621
1622		memcpy(&size, buf->buf + buf->offset + sizeof(*cpkt),
1623		       sizeof(size));
1624		set_console_size(port, size.rows, size.cols);
1625
1626		port->cons.hvc->irq_requested = 1;
1627		resize_console(port);
1628		break;
1629	}
1630	case VIRTIO_CONSOLE_PORT_OPEN:
1631		port->host_connected = virtio16_to_cpu(vdev, cpkt->value);
1632		wake_up_interruptible(&port->waitqueue);
1633		/*
1634		 * If the host port got closed and the host had any
1635		 * unconsumed buffers, we'll be able to reclaim them
1636		 * now.
1637		 */
1638		spin_lock_irq(&port->outvq_lock);
1639		reclaim_consumed_buffers(port);
1640		spin_unlock_irq(&port->outvq_lock);
1641
1642		/*
1643		 * If the guest is connected, it'll be interested in
1644		 * knowing the host connection state changed.
1645		 */
1646		spin_lock_irq(&port->inbuf_lock);
1647		send_sigio_to_port(port);
1648		spin_unlock_irq(&port->inbuf_lock);
1649		break;
1650	case VIRTIO_CONSOLE_PORT_NAME:
1651		/*
1652		 * If we woke up after hibernation, we can get this
1653		 * again.  Skip it in that case.
1654		 */
1655		if (port->name)
1656			break;
1657
1658		/*
1659		 * Skip the size of the header and the cpkt to get the size
1660		 * of the name that was sent
1661		 */
1662		name_size = buf->len - buf->offset - sizeof(*cpkt) + 1;
1663
1664		port->name = kmalloc(name_size, GFP_KERNEL);
1665		if (!port->name) {
1666			dev_err(port->dev,
1667				"Not enough space to store port name\n");
1668			break;
1669		}
1670		strscpy(port->name, buf->buf + buf->offset + sizeof(*cpkt),
1671			name_size);
1672
1673		/*
1674		 * Since we only have one sysfs attribute, 'name',
1675		 * create it only if we have a name for the port.
1676		 */
1677		err = sysfs_create_group(&port->dev->kobj,
1678					 &port_attribute_group);
1679		if (err) {
1680			dev_err(port->dev,
1681				"Error %d creating sysfs device attributes\n",
1682				err);
1683		} else {
1684			/*
1685			 * Generate a udev event so that appropriate
1686			 * symlinks can be created based on udev
1687			 * rules.
1688			 */
1689			kobject_uevent(&port->dev->kobj, KOBJ_CHANGE);
1690		}
1691		break;
1692	}
1693}
1694
1695static void control_work_handler(struct work_struct *work)
1696{
1697	struct ports_device *portdev;
1698	struct virtqueue *vq;
1699	struct port_buffer *buf;
1700	unsigned int len;
1701
1702	portdev = container_of(work, struct ports_device, control_work);
1703	vq = portdev->c_ivq;
1704
1705	spin_lock(&portdev->c_ivq_lock);
1706	while ((buf = virtqueue_get_buf(vq, &len))) {
1707		spin_unlock(&portdev->c_ivq_lock);
1708
1709		buf->len = min_t(size_t, len, buf->size);
1710		buf->offset = 0;
1711
1712		handle_control_message(vq->vdev, portdev, buf);
1713
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);
1719		}
1720	}
1721	spin_unlock(&portdev->c_ivq_lock);
1722}
1723
1724static void flush_bufs(struct virtqueue *vq, bool can_sleep)
1725{
1726	struct port_buffer *buf;
1727	unsigned int len;
1728
1729	while ((buf = virtqueue_get_buf(vq, &len)))
1730		free_buf(buf, can_sleep);
1731}
1732
1733static void out_intr(struct virtqueue *vq)
1734{
1735	struct port *port;
1736
1737	port = find_port_by_vq(vq->vdev->priv, vq);
1738	if (!port) {
1739		flush_bufs(vq, false);
1740		return;
1741	}
1742
1743	wake_up_interruptible(&port->waitqueue);
1744}
1745
1746static void in_intr(struct virtqueue *vq)
1747{
1748	struct port *port;
1749	unsigned long flags;
1750
1751	port = find_port_by_vq(vq->vdev->priv, vq);
1752	if (!port) {
1753		flush_bufs(vq, false);
1754		return;
1755	}
1756
1757	spin_lock_irqsave(&port->inbuf_lock, flags);
1758	port->inbuf = get_inbuf(port);
1759
1760	/*
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.
1768	 *
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.
1775	 */
1776
1777	if (!port->guest_connected && !is_rproc_serial(port->portdev->vdev))
1778		discard_port_data(port);
1779
1780	/* Send a SIGIO indicating new data in case the process asked for it */
1781	send_sigio_to_port(port);
1782
1783	spin_unlock_irqrestore(&port->inbuf_lock, flags);
1784
1785	wake_up_interruptible(&port->waitqueue);
1786
1787	if (is_console_port(port) && hvc_poll(port->cons.hvc))
1788		hvc_kick();
1789}
1790
1791static void control_intr(struct virtqueue *vq)
1792{
1793	struct ports_device *portdev;
1794
1795	portdev = vq->vdev->priv;
1796	schedule_work(&portdev->control_work);
1797}
1798
1799static void config_intr(struct virtio_device *vdev)
1800{
1801	struct ports_device *portdev;
1802
1803	portdev = vdev->priv;
1804
1805	if (!use_multiport(portdev))
1806		schedule_work(&portdev->config_work);
1807}
1808
1809static void config_work_handler(struct work_struct *work)
1810{
1811	struct ports_device *portdev;
1812
1813	portdev = container_of(work, struct ports_device, config_work);
1814	if (!use_multiport(portdev)) {
1815		struct virtio_device *vdev;
1816		struct port *port;
1817		u16 rows, cols;
1818
1819		vdev = portdev->vdev;
1820		virtio_cread(vdev, struct virtio_console_config, cols, &cols);
1821		virtio_cread(vdev, struct virtio_console_config, rows, &rows);
1822
1823		port = find_port_by_id(portdev, 0);
1824		set_console_size(port, rows, cols);
1825
1826		/*
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
1831		 * done per-port.
1832		 */
1833		resize_console(port);
1834	}
1835}
1836
1837static int init_vqs(struct ports_device *portdev)
1838{
1839	vq_callback_t **io_callbacks;
1840	char **io_names;
1841	struct virtqueue **vqs;
1842	u32 i, j, nr_ports, nr_queues;
1843	int err;
1844
1845	nr_ports = portdev->max_nr_ports;
1846	nr_queues = use_multiport(portdev) ? (nr_ports + 1) * 2 : 2;
1847
1848	vqs = kmalloc_array(nr_queues, sizeof(struct virtqueue *), GFP_KERNEL);
1849	io_callbacks = kmalloc_array(nr_queues, sizeof(vq_callback_t *),
1850				     GFP_KERNEL);
1851	io_names = kmalloc_array(nr_queues, sizeof(char *), GFP_KERNEL);
1852	portdev->in_vqs = kmalloc_array(nr_ports, sizeof(struct virtqueue *),
1853					GFP_KERNEL);
1854	portdev->out_vqs = kmalloc_array(nr_ports, sizeof(struct virtqueue *),
1855					 GFP_KERNEL);
1856	if (!vqs || !io_callbacks || !io_names || !portdev->in_vqs ||
1857	    !portdev->out_vqs) {
1858		err = -ENOMEM;
1859		goto free;
1860	}
1861
1862	/*
1863	 * For backward compat (newer host but older guest), the host
1864	 * spawns a console port first and also inits the vqs for port
1865	 * 0 before others.
1866	 */
1867	j = 0;
1868	io_callbacks[j] = in_intr;
1869	io_callbacks[j + 1] = out_intr;
1870	io_names[j] = "input";
1871	io_names[j + 1] = "output";
1872	j += 2;
1873
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";
1879
1880		for (i = 1; i < nr_ports; i++) {
1881			j += 2;
1882			io_callbacks[j] = in_intr;
1883			io_callbacks[j + 1] = out_intr;
1884			io_names[j] = "input";
1885			io_names[j + 1] = "output";
1886		}
1887	}
1888	/* Find the queues. */
1889	err = virtio_find_vqs(portdev->vdev, nr_queues, vqs,
1890			      io_callbacks,
1891			      (const char **)io_names, NULL);
1892	if (err)
1893		goto free;
1894
1895	j = 0;
1896	portdev->in_vqs[0] = vqs[0];
1897	portdev->out_vqs[0] = vqs[1];
1898	j += 2;
1899	if (use_multiport(portdev)) {
1900		portdev->c_ivq = vqs[j];
1901		portdev->c_ovq = vqs[j + 1];
1902
1903		for (i = 1; i < nr_ports; i++) {
1904			j += 2;
1905			portdev->in_vqs[i] = vqs[j];
1906			portdev->out_vqs[i] = vqs[j + 1];
1907		}
1908	}
1909	kfree(io_names);
1910	kfree(io_callbacks);
1911	kfree(vqs);
1912
1913	return 0;
1914
1915free:
1916	kfree(portdev->out_vqs);
1917	kfree(portdev->in_vqs);
1918	kfree(io_names);
1919	kfree(io_callbacks);
1920	kfree(vqs);
1921
1922	return err;
1923}
1924
1925static const struct file_operations portdev_fops = {
1926	.owner = THIS_MODULE,
1927};
1928
1929static void remove_vqs(struct ports_device *portdev)
1930{
1931	struct virtqueue *vq;
1932
1933	virtio_device_for_each_vq(portdev->vdev, vq) {
1934		struct port_buffer *buf;
1935
1936		flush_bufs(vq, true);
1937		while ((buf = virtqueue_detach_unused_buf(vq)))
1938			free_buf(buf, true);
1939		cond_resched();
1940	}
1941	portdev->vdev->config->del_vqs(portdev->vdev);
1942	kfree(portdev->in_vqs);
1943	kfree(portdev->out_vqs);
1944}
1945
1946static void virtcons_remove(struct virtio_device *vdev)
1947{
1948	struct ports_device *portdev;
1949	struct port *port, *port2;
1950
1951	portdev = vdev->priv;
1952
1953	spin_lock_irq(&pdrvdata_lock);
1954	list_del(&portdev->list);
1955	spin_unlock_irq(&pdrvdata_lock);
1956
1957	/* Device is going away, exit any polling for buffers */
1958	virtio_break_device(vdev);
1959	if (use_multiport(portdev))
1960		flush_work(&portdev->control_work);
1961	else
1962		flush_work(&portdev->config_work);
1963
1964	/* Disable interrupts for vqs */
1965	virtio_reset_device(vdev);
1966	/* Finish up work that's lined up */
1967	if (use_multiport(portdev))
1968		cancel_work_sync(&portdev->control_work);
1969	else
1970		cancel_work_sync(&portdev->config_work);
1971
1972	list_for_each_entry_safe(port, port2, &portdev->ports, list)
1973		unplug_port(port);
1974
1975	unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1976
1977	/*
1978	 * When yanking out a device, we immediately lose the
1979	 * (device-side) queues.  So there's no point in keeping the
1980	 * guest side around till we drop our final reference.  This
1981	 * also means that any ports which are in an open state will
1982	 * have to just stop using the port, as the vqs are going
1983	 * away.
1984	 */
1985	remove_vqs(portdev);
1986	kfree(portdev);
1987}
1988
1989/*
1990 * Once we're further in boot, we get probed like any other virtio
1991 * device.
1992 *
1993 * If the host also supports multiple console ports, we check the
1994 * config space to see how many ports the host has spawned.  We
1995 * initialize each port found.
1996 */
1997static int virtcons_probe(struct virtio_device *vdev)
1998{
1999	struct ports_device *portdev;
2000	int err;
2001	bool multiport;
2002	bool early = early_put_chars != NULL;
2003
2004	/* We only need a config space if features are offered */
2005	if (!vdev->config->get &&
2006	    (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE)
2007	     || virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT))) {
2008		dev_err(&vdev->dev, "%s failure: config access disabled\n",
2009			__func__);
2010		return -EINVAL;
2011	}
2012
2013	/* Ensure to read early_put_chars now */
2014	barrier();
2015
2016	portdev = kmalloc(sizeof(*portdev), GFP_KERNEL);
2017	if (!portdev) {
2018		err = -ENOMEM;
2019		goto fail;
2020	}
2021
2022	/* Attach this portdev to this virtio_device, and vice-versa. */
2023	portdev->vdev = vdev;
2024	vdev->priv = portdev;
2025
2026	portdev->chr_major = register_chrdev(0, "virtio-portsdev",
2027					     &portdev_fops);
2028	if (portdev->chr_major < 0) {
2029		dev_err(&vdev->dev,
2030			"Error %d registering chrdev for device %u\n",
2031			portdev->chr_major, vdev->index);
2032		err = portdev->chr_major;
2033		goto free;
2034	}
2035
2036	multiport = false;
2037	portdev->max_nr_ports = 1;
2038
2039	/* Don't test MULTIPORT at all if we're rproc: not a valid feature! */
2040	if (!is_rproc_serial(vdev) &&
2041	    virtio_cread_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT,
2042				 struct virtio_console_config, max_nr_ports,
2043				 &portdev->max_nr_ports) == 0) {
2044		if (portdev->max_nr_ports == 0 ||
2045		    portdev->max_nr_ports > VIRTCONS_MAX_PORTS) {
2046			dev_err(&vdev->dev,
2047				"Invalidate max_nr_ports %d",
2048				portdev->max_nr_ports);
2049			err = -EINVAL;
2050			goto free;
2051		}
2052		multiport = true;
2053	}
2054
2055	err = init_vqs(portdev);
2056	if (err < 0) {
2057		dev_err(&vdev->dev, "Error %d initializing vqs\n", err);
2058		goto free_chrdev;
2059	}
2060
2061	spin_lock_init(&portdev->ports_lock);
2062	INIT_LIST_HEAD(&portdev->ports);
2063	INIT_LIST_HEAD(&portdev->list);
2064
2065	virtio_device_ready(portdev->vdev);
2066
2067	INIT_WORK(&portdev->config_work, &config_work_handler);
2068	INIT_WORK(&portdev->control_work, &control_work_handler);
2069
2070	if (multiport) {
2071		spin_lock_init(&portdev->c_ivq_lock);
2072		spin_lock_init(&portdev->c_ovq_lock);
2073
2074		err = fill_queue(portdev->c_ivq, &portdev->c_ivq_lock);
2075		if (err < 0) {
2076			dev_err(&vdev->dev,
2077				"Error allocating buffers for control queue\n");
2078			/*
2079			 * The host might want to notify mgmt sw about device
2080			 * add failure.
2081			 */
2082			__send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
2083					   VIRTIO_CONSOLE_DEVICE_READY, 0);
2084			/* Device was functional: we need full cleanup. */
2085			virtcons_remove(vdev);
2086			return err;
2087		}
2088	} else {
2089		/*
2090		 * For backward compatibility: Create a console port
2091		 * if we're running on older host.
2092		 */
2093		add_port(portdev, 0);
2094	}
2095
2096	spin_lock_irq(&pdrvdata_lock);
2097	list_add_tail(&portdev->list, &pdrvdata.portdevs);
2098	spin_unlock_irq(&pdrvdata_lock);
2099
2100	__send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
2101			   VIRTIO_CONSOLE_DEVICE_READY, 1);
2102
2103	/*
2104	 * If there was an early virtio console, assume that there are no
2105	 * other consoles. We need to wait until the hvc_alloc matches the
2106	 * hvc_instantiate, otherwise tty_open will complain, resulting in
2107	 * a "Warning: unable to open an initial console" boot failure.
2108	 * Without multiport this is done in add_port above. With multiport
2109	 * this might take some host<->guest communication - thus we have to
2110	 * wait.
2111	 */
2112	if (multiport && early)
2113		wait_for_completion(&early_console_added);
2114
2115	return 0;
2116
2117free_chrdev:
2118	unregister_chrdev(portdev->chr_major, "virtio-portsdev");
2119free:
2120	kfree(portdev);
2121fail:
2122	return err;
2123}
2124
2125static const struct virtio_device_id id_table[] = {
2126	{ VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID },
2127	{ 0 },
2128};
2129MODULE_DEVICE_TABLE(virtio, id_table);
2130
2131static const unsigned int features[] = {
2132	VIRTIO_CONSOLE_F_SIZE,
2133	VIRTIO_CONSOLE_F_MULTIPORT,
2134};
2135
2136static const struct virtio_device_id rproc_serial_id_table[] = {
2137#if IS_ENABLED(CONFIG_REMOTEPROC)
2138	{ VIRTIO_ID_RPROC_SERIAL, VIRTIO_DEV_ANY_ID },
2139#endif
2140	{ 0 },
2141};
2142MODULE_DEVICE_TABLE(virtio, rproc_serial_id_table);
2143
2144static const unsigned int rproc_serial_features[] = {
2145};
2146
2147#ifdef CONFIG_PM_SLEEP
2148static int virtcons_freeze(struct virtio_device *vdev)
2149{
2150	struct ports_device *portdev;
2151	struct port *port;
2152
2153	portdev = vdev->priv;
2154
2155	virtio_reset_device(vdev);
2156
2157	if (use_multiport(portdev))
2158		virtqueue_disable_cb(portdev->c_ivq);
2159	cancel_work_sync(&portdev->control_work);
2160	cancel_work_sync(&portdev->config_work);
2161	/*
2162	 * Once more: if control_work_handler() was running, it would
2163	 * enable the cb as the last step.
2164	 */
2165	if (use_multiport(portdev))
2166		virtqueue_disable_cb(portdev->c_ivq);
2167
2168	list_for_each_entry(port, &portdev->ports, list) {
2169		virtqueue_disable_cb(port->in_vq);
2170		virtqueue_disable_cb(port->out_vq);
2171		/*
2172		 * We'll ask the host later if the new invocation has
2173		 * the port opened or closed.
2174		 */
2175		port->host_connected = false;
2176		remove_port_data(port);
2177	}
2178	remove_vqs(portdev);
2179
2180	return 0;
2181}
2182
2183static int virtcons_restore(struct virtio_device *vdev)
2184{
2185	struct ports_device *portdev;
2186	struct port *port;
2187	int ret;
2188
2189	portdev = vdev->priv;
2190
2191	ret = init_vqs(portdev);
2192	if (ret)
2193		return ret;
2194
2195	virtio_device_ready(portdev->vdev);
2196
2197	if (use_multiport(portdev))
2198		fill_queue(portdev->c_ivq, &portdev->c_ivq_lock);
2199
2200	list_for_each_entry(port, &portdev->ports, list) {
2201		port->in_vq = portdev->in_vqs[port->id];
2202		port->out_vq = portdev->out_vqs[port->id];
2203
2204		fill_queue(port->in_vq, &port->inbuf_lock);
2205
2206		/* Get port open/close status on the host */
2207		send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
2208
2209		/*
2210		 * If a port was open at the time of suspending, we
2211		 * have to let the host know that it's still open.
2212		 */
2213		if (port->guest_connected)
2214			send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
2215	}
2216	return 0;
2217}
2218#endif
2219
2220static struct virtio_driver virtio_console = {
2221	.feature_table = features,
2222	.feature_table_size = ARRAY_SIZE(features),
2223	.driver.name =	KBUILD_MODNAME,
2224	.driver.owner =	THIS_MODULE,
2225	.id_table =	id_table,
2226	.probe =	virtcons_probe,
2227	.remove =	virtcons_remove,
2228	.config_changed = config_intr,
2229#ifdef CONFIG_PM_SLEEP
2230	.freeze =	virtcons_freeze,
2231	.restore =	virtcons_restore,
2232#endif
2233};
2234
2235static struct virtio_driver virtio_rproc_serial = {
2236	.feature_table = rproc_serial_features,
2237	.feature_table_size = ARRAY_SIZE(rproc_serial_features),
2238	.driver.name =	"virtio_rproc_serial",
2239	.driver.owner =	THIS_MODULE,
2240	.id_table =	rproc_serial_id_table,
2241	.probe =	virtcons_probe,
2242	.remove =	virtcons_remove,
2243};
2244
2245static int __init virtio_console_init(void)
2246{
2247	int err;
2248
2249	err = class_register(&port_class);
2250	if (err)
2251		return err;
2252
2253	pdrvdata.debugfs_dir = debugfs_create_dir("virtio-ports", NULL);
2254	INIT_LIST_HEAD(&pdrvdata.consoles);
2255	INIT_LIST_HEAD(&pdrvdata.portdevs);
2256
2257	err = register_virtio_driver(&virtio_console);
2258	if (err < 0) {
2259		pr_err("Error %d registering virtio driver\n", err);
2260		goto free;
2261	}
2262	err = register_virtio_driver(&virtio_rproc_serial);
2263	if (err < 0) {
2264		pr_err("Error %d registering virtio rproc serial driver\n",
2265		       err);
2266		goto unregister;
2267	}
2268	return 0;
2269unregister:
2270	unregister_virtio_driver(&virtio_console);
2271free:
2272	debugfs_remove_recursive(pdrvdata.debugfs_dir);
2273	class_unregister(&port_class);
2274	return err;
2275}
2276
2277static void __exit virtio_console_fini(void)
2278{
2279	reclaim_dma_bufs();
2280
2281	unregister_virtio_driver(&virtio_console);
2282	unregister_virtio_driver(&virtio_rproc_serial);
2283
2284	class_unregister(&port_class);
2285	debugfs_remove_recursive(pdrvdata.debugfs_dir);
2286}
2287module_init(virtio_console_init);
2288module_exit(virtio_console_fini);
2289
2290MODULE_DESCRIPTION("Virtio console driver");
2291MODULE_LICENSE("GPL");
2292