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