b70fe96c1ccd5aff9ad52f641eb7456e646271bf
[firefly-linux-kernel-4.4.55.git] / drivers / char / virtio_console.c
1 /*
2  * Copyright (C) 2006, 2007, 2009 Rusty Russell, IBM Corporation
3  * Copyright (C) 2009, 2010 Red Hat, Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19 #include <linux/cdev.h>
20 #include <linux/debugfs.h>
21 #include <linux/device.h>
22 #include <linux/err.h>
23 #include <linux/fs.h>
24 #include <linux/init.h>
25 #include <linux/list.h>
26 #include <linux/poll.h>
27 #include <linux/sched.h>
28 #include <linux/slab.h>
29 #include <linux/spinlock.h>
30 #include <linux/virtio.h>
31 #include <linux/virtio_console.h>
32 #include <linux/wait.h>
33 #include <linux/workqueue.h>
34 #include "hvc_console.h"
35
36 /*
37  * This is a global struct for storing common data for all the devices
38  * this driver handles.
39  *
40  * Mainly, it has a linked list for all the consoles in one place so
41  * that callbacks from hvc for get_chars(), put_chars() work properly
42  * across multiple devices and multiple ports per device.
43  */
44 struct ports_driver_data {
45         /* Used for registering chardevs */
46         struct class *class;
47
48         /* Used for exporting per-port information to debugfs */
49         struct dentry *debugfs_dir;
50
51         /* List of all the devices we're handling */
52         struct list_head portdevs;
53
54         /* Number of devices this driver is handling */
55         unsigned int index;
56
57         /*
58          * This is used to keep track of the number of hvc consoles
59          * spawned by this driver.  This number is given as the first
60          * argument to hvc_alloc().  To correctly map an initial
61          * console spawned via hvc_instantiate to the console being
62          * hooked up via hvc_alloc, we need to pass the same vtermno.
63          *
64          * We also just assume the first console being initialised was
65          * the first one that got used as the initial console.
66          */
67         unsigned int next_vtermno;
68
69         /* All the console devices handled by this driver */
70         struct list_head consoles;
71 };
72 static struct ports_driver_data pdrvdata;
73
74 DEFINE_SPINLOCK(pdrvdata_lock);
75
76 /* This struct holds information that's relevant only for console ports */
77 struct console {
78         /* We'll place all consoles in a list in the pdrvdata struct */
79         struct list_head list;
80
81         /* The hvc device associated with this console port */
82         struct hvc_struct *hvc;
83
84         /* The size of the console */
85         struct winsize ws;
86
87         /*
88          * This number identifies the number that we used to register
89          * with hvc in hvc_instantiate() and hvc_alloc(); this is the
90          * number passed on by the hvc callbacks to us to
91          * differentiate between the other console ports handled by
92          * this driver
93          */
94         u32 vtermno;
95 };
96
97 struct port_buffer {
98         char *buf;
99
100         /* size of the buffer in *buf above */
101         size_t size;
102
103         /* used length of the buffer */
104         size_t len;
105         /* offset in the buf from which to consume data */
106         size_t offset;
107 };
108
109 /*
110  * This is a per-device struct that stores data common to all the
111  * ports for that device (vdev->priv).
112  */
113 struct ports_device {
114         /* Next portdev in the list, head is in the pdrvdata struct */
115         struct list_head list;
116
117         /*
118          * Workqueue handlers where we process deferred work after
119          * notification
120          */
121         struct work_struct control_work;
122
123         struct list_head ports;
124
125         /* To protect the list of ports */
126         spinlock_t ports_lock;
127
128         /* To protect the vq operations for the control channel */
129         spinlock_t cvq_lock;
130
131         /* The current config space is stored here */
132         struct virtio_console_config config;
133
134         /* The virtio device we're associated with */
135         struct virtio_device *vdev;
136
137         /*
138          * A couple of virtqueues for the control channel: one for
139          * guest->host transfers, one for host->guest transfers
140          */
141         struct virtqueue *c_ivq, *c_ovq;
142
143         /* Array of per-port IO virtqueues */
144         struct virtqueue **in_vqs, **out_vqs;
145
146         /* Used for numbering devices for sysfs and debugfs */
147         unsigned int drv_index;
148
149         /* Major number for this device.  Ports will be created as minors. */
150         int chr_major;
151 };
152
153 /* This struct holds the per-port data */
154 struct port {
155         /* Next port in the list, head is in the ports_device */
156         struct list_head list;
157
158         /* Pointer to the parent virtio_console device */
159         struct ports_device *portdev;
160
161         /* The current buffer from which data has to be fed to readers */
162         struct port_buffer *inbuf;
163
164         /*
165          * To protect the operations on the in_vq associated with this
166          * port.  Has to be a spinlock because it can be called from
167          * interrupt context (get_char()).
168          */
169         spinlock_t inbuf_lock;
170
171         /* Protect the operations on the out_vq. */
172         spinlock_t outvq_lock;
173
174         /* The IO vqs for this port */
175         struct virtqueue *in_vq, *out_vq;
176
177         /* File in the debugfs directory that exposes this port's information */
178         struct dentry *debugfs_file;
179
180         /*
181          * The entries in this struct will be valid if this port is
182          * hooked up to an hvc console
183          */
184         struct console cons;
185
186         /* Each port associates with a separate char device */
187         struct cdev cdev;
188         struct device *dev;
189
190         /* A waitqueue for poll() or blocking read operations */
191         wait_queue_head_t waitqueue;
192
193         /* The 'name' of the port that we expose via sysfs properties */
194         char *name;
195
196         /* The 'id' to identify the port with the Host */
197         u32 id;
198
199         bool outvq_full;
200
201         /* Is the host device open */
202         bool host_connected;
203
204         /* We should allow only one process to open a port */
205         bool guest_connected;
206 };
207
208 /* This is the very early arch-specified put chars function. */
209 static int (*early_put_chars)(u32, const char *, int);
210
211 static struct port *find_port_by_vtermno(u32 vtermno)
212 {
213         struct port *port;
214         struct console *cons;
215         unsigned long flags;
216
217         spin_lock_irqsave(&pdrvdata_lock, flags);
218         list_for_each_entry(cons, &pdrvdata.consoles, list) {
219                 if (cons->vtermno == vtermno) {
220                         port = container_of(cons, struct port, cons);
221                         goto out;
222                 }
223         }
224         port = NULL;
225 out:
226         spin_unlock_irqrestore(&pdrvdata_lock, flags);
227         return port;
228 }
229
230 static struct port *find_port_by_id(struct ports_device *portdev, u32 id)
231 {
232         struct port *port;
233         unsigned long flags;
234
235         spin_lock_irqsave(&portdev->ports_lock, flags);
236         list_for_each_entry(port, &portdev->ports, list)
237                 if (port->id == id)
238                         goto out;
239         port = NULL;
240 out:
241         spin_unlock_irqrestore(&portdev->ports_lock, flags);
242
243         return port;
244 }
245
246 static struct port *find_port_by_vq(struct ports_device *portdev,
247                                     struct virtqueue *vq)
248 {
249         struct port *port;
250         unsigned long flags;
251
252         spin_lock_irqsave(&portdev->ports_lock, flags);
253         list_for_each_entry(port, &portdev->ports, list)
254                 if (port->in_vq == vq || port->out_vq == vq)
255                         goto out;
256         port = NULL;
257 out:
258         spin_unlock_irqrestore(&portdev->ports_lock, flags);
259         return port;
260 }
261
262 static bool is_console_port(struct port *port)
263 {
264         if (port->cons.hvc)
265                 return true;
266         return false;
267 }
268
269 static inline bool use_multiport(struct ports_device *portdev)
270 {
271         /*
272          * This condition can be true when put_chars is called from
273          * early_init
274          */
275         if (!portdev->vdev)
276                 return 0;
277         return portdev->vdev->features[0] & (1 << VIRTIO_CONSOLE_F_MULTIPORT);
278 }
279
280 static void free_buf(struct port_buffer *buf)
281 {
282         kfree(buf->buf);
283         kfree(buf);
284 }
285
286 static struct port_buffer *alloc_buf(size_t buf_size)
287 {
288         struct port_buffer *buf;
289
290         buf = kmalloc(sizeof(*buf), GFP_KERNEL);
291         if (!buf)
292                 goto fail;
293         buf->buf = kzalloc(buf_size, GFP_KERNEL);
294         if (!buf->buf)
295                 goto free_buf;
296         buf->len = 0;
297         buf->offset = 0;
298         buf->size = buf_size;
299         return buf;
300
301 free_buf:
302         kfree(buf);
303 fail:
304         return NULL;
305 }
306
307 /* Callers should take appropriate locks */
308 static void *get_inbuf(struct port *port)
309 {
310         struct port_buffer *buf;
311         struct virtqueue *vq;
312         unsigned int len;
313
314         vq = port->in_vq;
315         buf = virtqueue_get_buf(vq, &len);
316         if (buf) {
317                 buf->len = len;
318                 buf->offset = 0;
319         }
320         return buf;
321 }
322
323 /*
324  * Create a scatter-gather list representing our input buffer and put
325  * it in the queue.
326  *
327  * Callers should take appropriate locks.
328  */
329 static int add_inbuf(struct virtqueue *vq, struct port_buffer *buf)
330 {
331         struct scatterlist sg[1];
332         int ret;
333
334         sg_init_one(sg, buf->buf, buf->size);
335
336         ret = virtqueue_add_buf(vq, sg, 0, 1, buf);
337         virtqueue_kick(vq);
338         return ret;
339 }
340
341 /* Discard any unread data this port has. Callers lockers. */
342 static void discard_port_data(struct port *port)
343 {
344         struct port_buffer *buf;
345         struct virtqueue *vq;
346         unsigned int len;
347         int ret;
348
349         vq = port->in_vq;
350         if (port->inbuf)
351                 buf = port->inbuf;
352         else
353                 buf = virtqueue_get_buf(vq, &len);
354
355         ret = 0;
356         while (buf) {
357                 if (add_inbuf(vq, buf) < 0) {
358                         ret++;
359                         free_buf(buf);
360                 }
361                 buf = virtqueue_get_buf(vq, &len);
362         }
363         port->inbuf = NULL;
364         if (ret)
365                 dev_warn(port->dev, "Errors adding %d buffers back to vq\n",
366                          ret);
367 }
368
369 static bool port_has_data(struct port *port)
370 {
371         unsigned long flags;
372         bool ret;
373
374         spin_lock_irqsave(&port->inbuf_lock, flags);
375         if (port->inbuf) {
376                 ret = true;
377                 goto out;
378         }
379         port->inbuf = get_inbuf(port);
380         if (port->inbuf) {
381                 ret = true;
382                 goto out;
383         }
384         ret = false;
385 out:
386         spin_unlock_irqrestore(&port->inbuf_lock, flags);
387         return ret;
388 }
389
390 static ssize_t __send_control_msg(struct ports_device *portdev, u32 port_id,
391                                   unsigned int event, unsigned int value)
392 {
393         struct scatterlist sg[1];
394         struct virtio_console_control cpkt;
395         struct virtqueue *vq;
396         unsigned int len;
397
398         if (!use_multiport(portdev))
399                 return 0;
400
401         cpkt.id = port_id;
402         cpkt.event = event;
403         cpkt.value = value;
404
405         vq = portdev->c_ovq;
406
407         sg_init_one(sg, &cpkt, sizeof(cpkt));
408         if (virtqueue_add_buf(vq, sg, 1, 0, &cpkt) >= 0) {
409                 virtqueue_kick(vq);
410                 while (!virtqueue_get_buf(vq, &len))
411                         cpu_relax();
412         }
413         return 0;
414 }
415
416 static ssize_t send_control_msg(struct port *port, unsigned int event,
417                                 unsigned int value)
418 {
419         /* Did the port get unplugged before userspace closed it? */
420         if (port->portdev)
421                 return __send_control_msg(port->portdev, port->id, event, value);
422         return 0;
423 }
424
425 /* Callers must take the port->outvq_lock */
426 static void reclaim_consumed_buffers(struct port *port)
427 {
428         void *buf;
429         unsigned int len;
430
431         while ((buf = virtqueue_get_buf(port->out_vq, &len))) {
432                 kfree(buf);
433                 port->outvq_full = false;
434         }
435 }
436
437 static ssize_t send_buf(struct port *port, void *in_buf, size_t in_count,
438                         bool nonblock)
439 {
440         struct scatterlist sg[1];
441         struct virtqueue *out_vq;
442         ssize_t ret;
443         unsigned long flags;
444         unsigned int len;
445
446         out_vq = port->out_vq;
447
448         spin_lock_irqsave(&port->outvq_lock, flags);
449
450         reclaim_consumed_buffers(port);
451
452         sg_init_one(sg, in_buf, in_count);
453         ret = virtqueue_add_buf(out_vq, sg, 1, 0, in_buf);
454
455         /* Tell Host to go! */
456         virtqueue_kick(out_vq);
457
458         if (ret < 0) {
459                 in_count = 0;
460                 goto done;
461         }
462
463         if (ret == 0)
464                 port->outvq_full = true;
465
466         if (nonblock)
467                 goto done;
468
469         /*
470          * Wait till the host acknowledges it pushed out the data we
471          * sent.  This is done for data from the hvc_console; the tty
472          * operations are performed with spinlocks held so we can't
473          * sleep here.  An alternative would be to copy the data to a
474          * buffer and relax the spinning requirement.  The downside is
475          * we need to kmalloc a GFP_ATOMIC buffer each time the
476          * console driver writes something out.
477          */
478         while (!virtqueue_get_buf(out_vq, &len))
479                 cpu_relax();
480 done:
481         spin_unlock_irqrestore(&port->outvq_lock, flags);
482         /*
483          * We're expected to return the amount of data we wrote -- all
484          * of it
485          */
486         return in_count;
487 }
488
489 /*
490  * Give out the data that's requested from the buffer that we have
491  * queued up.
492  */
493 static ssize_t fill_readbuf(struct port *port, char *out_buf, size_t out_count,
494                             bool to_user)
495 {
496         struct port_buffer *buf;
497         unsigned long flags;
498
499         if (!out_count || !port_has_data(port))
500                 return 0;
501
502         buf = port->inbuf;
503         out_count = min(out_count, buf->len - buf->offset);
504
505         if (to_user) {
506                 ssize_t ret;
507
508                 ret = copy_to_user(out_buf, buf->buf + buf->offset, out_count);
509                 if (ret)
510                         return -EFAULT;
511         } else {
512                 memcpy(out_buf, buf->buf + buf->offset, out_count);
513         }
514
515         buf->offset += out_count;
516
517         if (buf->offset == buf->len) {
518                 /*
519                  * We're done using all the data in this buffer.
520                  * Re-queue so that the Host can send us more data.
521                  */
522                 spin_lock_irqsave(&port->inbuf_lock, flags);
523                 port->inbuf = NULL;
524
525                 if (add_inbuf(port->in_vq, buf) < 0)
526                         dev_warn(port->dev, "failed add_buf\n");
527
528                 spin_unlock_irqrestore(&port->inbuf_lock, flags);
529         }
530         /* Return the number of bytes actually copied */
531         return out_count;
532 }
533
534 /* The condition that must be true for polling to end */
535 static bool will_read_block(struct port *port)
536 {
537         if (!port->guest_connected) {
538                 /* Port got hot-unplugged. Let's exit. */
539                 return false;
540         }
541         return !port_has_data(port) && port->host_connected;
542 }
543
544 static bool will_write_block(struct port *port)
545 {
546         bool ret;
547
548         if (!port->guest_connected) {
549                 /* Port got hot-unplugged. Let's exit. */
550                 return false;
551         }
552         if (!port->host_connected)
553                 return true;
554
555         spin_lock_irq(&port->outvq_lock);
556         /*
557          * Check if the Host has consumed any buffers since we last
558          * sent data (this is only applicable for nonblocking ports).
559          */
560         reclaim_consumed_buffers(port);
561         ret = port->outvq_full;
562         spin_unlock_irq(&port->outvq_lock);
563
564         return ret;
565 }
566
567 static ssize_t port_fops_read(struct file *filp, char __user *ubuf,
568                               size_t count, loff_t *offp)
569 {
570         struct port *port;
571         ssize_t ret;
572
573         port = filp->private_data;
574
575         if (!port_has_data(port)) {
576                 /*
577                  * If nothing's connected on the host just return 0 in
578                  * case of list_empty; this tells the userspace app
579                  * that there's no connection
580                  */
581                 if (!port->host_connected)
582                         return 0;
583                 if (filp->f_flags & O_NONBLOCK)
584                         return -EAGAIN;
585
586                 ret = wait_event_interruptible(port->waitqueue,
587                                                !will_read_block(port));
588                 if (ret < 0)
589                         return ret;
590         }
591         /* Port got hot-unplugged. */
592         if (!port->guest_connected)
593                 return -ENODEV;
594         /*
595          * We could've received a disconnection message while we were
596          * waiting for more data.
597          *
598          * This check is not clubbed in the if() statement above as we
599          * might receive some data as well as the host could get
600          * disconnected after we got woken up from our wait.  So we
601          * really want to give off whatever data we have and only then
602          * check for host_connected.
603          */
604         if (!port_has_data(port) && !port->host_connected)
605                 return 0;
606
607         return fill_readbuf(port, ubuf, count, true);
608 }
609
610 static ssize_t port_fops_write(struct file *filp, const char __user *ubuf,
611                                size_t count, loff_t *offp)
612 {
613         struct port *port;
614         char *buf;
615         ssize_t ret;
616         bool nonblock;
617
618         /* Userspace could be out to fool us */
619         if (!count)
620                 return 0;
621
622         port = filp->private_data;
623
624         nonblock = filp->f_flags & O_NONBLOCK;
625
626         if (will_write_block(port)) {
627                 if (nonblock)
628                         return -EAGAIN;
629
630                 ret = wait_event_interruptible(port->waitqueue,
631                                                !will_write_block(port));
632                 if (ret < 0)
633                         return ret;
634         }
635         /* Port got hot-unplugged. */
636         if (!port->guest_connected)
637                 return -ENODEV;
638
639         count = min((size_t)(32 * 1024), count);
640
641         buf = kmalloc(count, GFP_KERNEL);
642         if (!buf)
643                 return -ENOMEM;
644
645         ret = copy_from_user(buf, ubuf, count);
646         if (ret) {
647                 ret = -EFAULT;
648                 goto free_buf;
649         }
650
651         /*
652          * We now ask send_buf() to not spin for generic ports -- we
653          * can re-use the same code path that non-blocking file
654          * descriptors take for blocking file descriptors since the
655          * wait is already done and we're certain the write will go
656          * through to the host.
657          */
658         nonblock = true;
659         ret = send_buf(port, buf, count, nonblock);
660
661         if (nonblock && ret > 0)
662                 goto out;
663
664 free_buf:
665         kfree(buf);
666 out:
667         return ret;
668 }
669
670 static unsigned int port_fops_poll(struct file *filp, poll_table *wait)
671 {
672         struct port *port;
673         unsigned int ret;
674
675         port = filp->private_data;
676         poll_wait(filp, &port->waitqueue, wait);
677
678         if (!port->guest_connected) {
679                 /* Port got unplugged */
680                 return POLLHUP;
681         }
682         ret = 0;
683         if (!will_read_block(port))
684                 ret |= POLLIN | POLLRDNORM;
685         if (!will_write_block(port))
686                 ret |= POLLOUT;
687         if (!port->host_connected)
688                 ret |= POLLHUP;
689
690         return ret;
691 }
692
693 static int port_fops_release(struct inode *inode, struct file *filp)
694 {
695         struct port *port;
696
697         port = filp->private_data;
698
699         /* Notify host of port being closed */
700         send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
701
702         spin_lock_irq(&port->inbuf_lock);
703         port->guest_connected = false;
704
705         discard_port_data(port);
706
707         spin_unlock_irq(&port->inbuf_lock);
708
709         spin_lock_irq(&port->outvq_lock);
710         reclaim_consumed_buffers(port);
711         spin_unlock_irq(&port->outvq_lock);
712
713         return 0;
714 }
715
716 static int port_fops_open(struct inode *inode, struct file *filp)
717 {
718         struct cdev *cdev = inode->i_cdev;
719         struct port *port;
720         int ret;
721
722         port = container_of(cdev, struct port, cdev);
723         filp->private_data = port;
724
725         /*
726          * Don't allow opening of console port devices -- that's done
727          * via /dev/hvc
728          */
729         if (is_console_port(port)) {
730                 ret = -ENXIO;
731                 goto out;
732         }
733
734         /* Allow only one process to open a particular port at a time */
735         spin_lock_irq(&port->inbuf_lock);
736         if (port->guest_connected) {
737                 spin_unlock_irq(&port->inbuf_lock);
738                 ret = -EMFILE;
739                 goto out;
740         }
741
742         port->guest_connected = true;
743         spin_unlock_irq(&port->inbuf_lock);
744
745         spin_lock_irq(&port->outvq_lock);
746         /*
747          * There might be a chance that we missed reclaiming a few
748          * buffers in the window of the port getting previously closed
749          * and opening now.
750          */
751         reclaim_consumed_buffers(port);
752         spin_unlock_irq(&port->outvq_lock);
753
754         /* Notify host of port being opened */
755         send_control_msg(filp->private_data, VIRTIO_CONSOLE_PORT_OPEN, 1);
756
757         return 0;
758 out:
759         return ret;
760 }
761
762 /*
763  * The file operations that we support: programs in the guest can open
764  * a console device, read from it, write to it, poll for data and
765  * close it.  The devices are at
766  *   /dev/vport<device number>p<port number>
767  */
768 static const struct file_operations port_fops = {
769         .owner = THIS_MODULE,
770         .open  = port_fops_open,
771         .read  = port_fops_read,
772         .write = port_fops_write,
773         .poll  = port_fops_poll,
774         .release = port_fops_release,
775 };
776
777 /*
778  * The put_chars() callback is pretty straightforward.
779  *
780  * We turn the characters into a scatter-gather list, add it to the
781  * output queue and then kick the Host.  Then we sit here waiting for
782  * it to finish: inefficient in theory, but in practice
783  * implementations will do it immediately (lguest's Launcher does).
784  */
785 static int put_chars(u32 vtermno, const char *buf, int count)
786 {
787         struct port *port;
788
789         if (unlikely(early_put_chars))
790                 return early_put_chars(vtermno, buf, count);
791
792         port = find_port_by_vtermno(vtermno);
793         if (!port)
794                 return -EPIPE;
795
796         return send_buf(port, (void *)buf, count, false);
797 }
798
799 /*
800  * get_chars() is the callback from the hvc_console infrastructure
801  * when an interrupt is received.
802  *
803  * We call out to fill_readbuf that gets us the required data from the
804  * buffers that are queued up.
805  */
806 static int get_chars(u32 vtermno, char *buf, int count)
807 {
808         struct port *port;
809
810         /* If we've not set up the port yet, we have no input to give. */
811         if (unlikely(early_put_chars))
812                 return 0;
813
814         port = find_port_by_vtermno(vtermno);
815         if (!port)
816                 return -EPIPE;
817
818         /* If we don't have an input queue yet, we can't get input. */
819         BUG_ON(!port->in_vq);
820
821         return fill_readbuf(port, buf, count, false);
822 }
823
824 static void resize_console(struct port *port)
825 {
826         struct virtio_device *vdev;
827
828         /* The port could have been hot-unplugged */
829         if (!port || !is_console_port(port))
830                 return;
831
832         vdev = port->portdev->vdev;
833         if (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE))
834                 hvc_resize(port->cons.hvc, port->cons.ws);
835 }
836
837 /* We set the configuration at this point, since we now have a tty */
838 static int notifier_add_vio(struct hvc_struct *hp, int data)
839 {
840         struct port *port;
841
842         port = find_port_by_vtermno(hp->vtermno);
843         if (!port)
844                 return -EINVAL;
845
846         hp->irq_requested = 1;
847         resize_console(port);
848
849         return 0;
850 }
851
852 static void notifier_del_vio(struct hvc_struct *hp, int data)
853 {
854         hp->irq_requested = 0;
855 }
856
857 /* The operations for console ports. */
858 static const struct hv_ops hv_ops = {
859         .get_chars = get_chars,
860         .put_chars = put_chars,
861         .notifier_add = notifier_add_vio,
862         .notifier_del = notifier_del_vio,
863         .notifier_hangup = notifier_del_vio,
864 };
865
866 /*
867  * Console drivers are initialized very early so boot messages can go
868  * out, so we do things slightly differently from the generic virtio
869  * initialization of the net and block drivers.
870  *
871  * At this stage, the console is output-only.  It's too early to set
872  * up a virtqueue, so we let the drivers do some boutique early-output
873  * thing.
874  */
875 int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int))
876 {
877         early_put_chars = put_chars;
878         return hvc_instantiate(0, 0, &hv_ops);
879 }
880
881 int init_port_console(struct port *port)
882 {
883         int ret;
884
885         /*
886          * The Host's telling us this port is a console port.  Hook it
887          * up with an hvc console.
888          *
889          * To set up and manage our virtual console, we call
890          * hvc_alloc().
891          *
892          * The first argument of hvc_alloc() is the virtual console
893          * number.  The second argument is the parameter for the
894          * notification mechanism (like irq number).  We currently
895          * leave this as zero, virtqueues have implicit notifications.
896          *
897          * The third argument is a "struct hv_ops" containing the
898          * put_chars() get_chars(), notifier_add() and notifier_del()
899          * pointers.  The final argument is the output buffer size: we
900          * can do any size, so we put PAGE_SIZE here.
901          */
902         port->cons.vtermno = pdrvdata.next_vtermno;
903
904         port->cons.hvc = hvc_alloc(port->cons.vtermno, 0, &hv_ops, PAGE_SIZE);
905         if (IS_ERR(port->cons.hvc)) {
906                 ret = PTR_ERR(port->cons.hvc);
907                 dev_err(port->dev,
908                         "error %d allocating hvc for port\n", ret);
909                 port->cons.hvc = NULL;
910                 return ret;
911         }
912         spin_lock_irq(&pdrvdata_lock);
913         pdrvdata.next_vtermno++;
914         list_add_tail(&port->cons.list, &pdrvdata.consoles);
915         spin_unlock_irq(&pdrvdata_lock);
916         port->guest_connected = true;
917
918         /*
919          * Start using the new console output if this is the first
920          * console to come up.
921          */
922         if (early_put_chars)
923                 early_put_chars = NULL;
924
925         /* Notify host of port being opened */
926         send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
927
928         return 0;
929 }
930
931 static ssize_t show_port_name(struct device *dev,
932                               struct device_attribute *attr, char *buffer)
933 {
934         struct port *port;
935
936         port = dev_get_drvdata(dev);
937
938         return sprintf(buffer, "%s\n", port->name);
939 }
940
941 static DEVICE_ATTR(name, S_IRUGO, show_port_name, NULL);
942
943 static struct attribute *port_sysfs_entries[] = {
944         &dev_attr_name.attr,
945         NULL
946 };
947
948 static struct attribute_group port_attribute_group = {
949         .name = NULL,           /* put in device directory */
950         .attrs = port_sysfs_entries,
951 };
952
953 static int debugfs_open(struct inode *inode, struct file *filp)
954 {
955         filp->private_data = inode->i_private;
956         return 0;
957 }
958
959 static ssize_t debugfs_read(struct file *filp, char __user *ubuf,
960                             size_t count, loff_t *offp)
961 {
962         struct port *port;
963         char *buf;
964         ssize_t ret, out_offset, out_count;
965
966         out_count = 1024;
967         buf = kmalloc(out_count, GFP_KERNEL);
968         if (!buf)
969                 return -ENOMEM;
970
971         port = filp->private_data;
972         out_offset = 0;
973         out_offset += snprintf(buf + out_offset, out_count,
974                                "name: %s\n", port->name ? port->name : "");
975         out_offset += snprintf(buf + out_offset, out_count - out_offset,
976                                "guest_connected: %d\n", port->guest_connected);
977         out_offset += snprintf(buf + out_offset, out_count - out_offset,
978                                "host_connected: %d\n", port->host_connected);
979         out_offset += snprintf(buf + out_offset, out_count - out_offset,
980                                "outvq_full: %d\n", port->outvq_full);
981         out_offset += snprintf(buf + out_offset, out_count - out_offset,
982                                "is_console: %s\n",
983                                is_console_port(port) ? "yes" : "no");
984         out_offset += snprintf(buf + out_offset, out_count - out_offset,
985                                "console_vtermno: %u\n", port->cons.vtermno);
986
987         ret = simple_read_from_buffer(ubuf, count, offp, buf, out_offset);
988         kfree(buf);
989         return ret;
990 }
991
992 static const struct file_operations port_debugfs_ops = {
993         .owner = THIS_MODULE,
994         .open  = debugfs_open,
995         .read  = debugfs_read,
996 };
997
998 static void set_console_size(struct port *port, u16 rows, u16 cols)
999 {
1000         if (!port || !is_console_port(port))
1001                 return;
1002
1003         port->cons.ws.ws_row = rows;
1004         port->cons.ws.ws_col = cols;
1005 }
1006
1007 static unsigned int fill_queue(struct virtqueue *vq, spinlock_t *lock)
1008 {
1009         struct port_buffer *buf;
1010         unsigned int nr_added_bufs;
1011         int ret;
1012
1013         nr_added_bufs = 0;
1014         do {
1015                 buf = alloc_buf(PAGE_SIZE);
1016                 if (!buf)
1017                         break;
1018
1019                 spin_lock_irq(lock);
1020                 ret = add_inbuf(vq, buf);
1021                 if (ret < 0) {
1022                         spin_unlock_irq(lock);
1023                         free_buf(buf);
1024                         break;
1025                 }
1026                 nr_added_bufs++;
1027                 spin_unlock_irq(lock);
1028         } while (ret > 0);
1029
1030         return nr_added_bufs;
1031 }
1032
1033 static int add_port(struct ports_device *portdev, u32 id)
1034 {
1035         char debugfs_name[16];
1036         struct port *port;
1037         struct port_buffer *buf;
1038         dev_t devt;
1039         unsigned int nr_added_bufs;
1040         int err;
1041
1042         port = kmalloc(sizeof(*port), GFP_KERNEL);
1043         if (!port) {
1044                 err = -ENOMEM;
1045                 goto fail;
1046         }
1047
1048         port->portdev = portdev;
1049         port->id = id;
1050
1051         port->name = NULL;
1052         port->inbuf = NULL;
1053         port->cons.hvc = NULL;
1054
1055         port->cons.ws.ws_row = port->cons.ws.ws_col = 0;
1056
1057         port->host_connected = port->guest_connected = false;
1058
1059         port->outvq_full = false;
1060
1061         port->in_vq = portdev->in_vqs[port->id];
1062         port->out_vq = portdev->out_vqs[port->id];
1063
1064         cdev_init(&port->cdev, &port_fops);
1065
1066         devt = MKDEV(portdev->chr_major, id);
1067         err = cdev_add(&port->cdev, devt, 1);
1068         if (err < 0) {
1069                 dev_err(&port->portdev->vdev->dev,
1070                         "Error %d adding cdev for port %u\n", err, id);
1071                 goto free_port;
1072         }
1073         port->dev = device_create(pdrvdata.class, &port->portdev->vdev->dev,
1074                                   devt, port, "vport%up%u",
1075                                   port->portdev->drv_index, id);
1076         if (IS_ERR(port->dev)) {
1077                 err = PTR_ERR(port->dev);
1078                 dev_err(&port->portdev->vdev->dev,
1079                         "Error %d creating device for port %u\n",
1080                         err, id);
1081                 goto free_cdev;
1082         }
1083
1084         spin_lock_init(&port->inbuf_lock);
1085         spin_lock_init(&port->outvq_lock);
1086         init_waitqueue_head(&port->waitqueue);
1087
1088         /* Fill the in_vq with buffers so the host can send us data. */
1089         nr_added_bufs = fill_queue(port->in_vq, &port->inbuf_lock);
1090         if (!nr_added_bufs) {
1091                 dev_err(port->dev, "Error allocating inbufs\n");
1092                 err = -ENOMEM;
1093                 goto free_device;
1094         }
1095
1096         /*
1097          * If we're not using multiport support, this has to be a console port
1098          */
1099         if (!use_multiport(port->portdev)) {
1100                 err = init_port_console(port);
1101                 if (err)
1102                         goto free_inbufs;
1103         }
1104
1105         spin_lock_irq(&portdev->ports_lock);
1106         list_add_tail(&port->list, &port->portdev->ports);
1107         spin_unlock_irq(&portdev->ports_lock);
1108
1109         /*
1110          * Tell the Host we're set so that it can send us various
1111          * configuration parameters for this port (eg, port name,
1112          * caching, whether this is a console port, etc.)
1113          */
1114         send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1115
1116         if (pdrvdata.debugfs_dir) {
1117                 /*
1118                  * Finally, create the debugfs file that we can use to
1119                  * inspect a port's state at any time
1120                  */
1121                 sprintf(debugfs_name, "vport%up%u",
1122                         port->portdev->drv_index, id);
1123                 port->debugfs_file = debugfs_create_file(debugfs_name, 0444,
1124                                                          pdrvdata.debugfs_dir,
1125                                                          port,
1126                                                          &port_debugfs_ops);
1127         }
1128         return 0;
1129
1130 free_inbufs:
1131         while ((buf = virtqueue_detach_unused_buf(port->in_vq)))
1132                 free_buf(buf);
1133 free_device:
1134         device_destroy(pdrvdata.class, port->dev->devt);
1135 free_cdev:
1136         cdev_del(&port->cdev);
1137 free_port:
1138         kfree(port);
1139 fail:
1140         /* The host might want to notify management sw about port add failure */
1141         __send_control_msg(portdev, id, VIRTIO_CONSOLE_PORT_READY, 0);
1142         return err;
1143 }
1144
1145 /* Remove all port-specific data. */
1146 static void remove_port(struct port *port)
1147 {
1148         struct port_buffer *buf;
1149
1150         if (port->guest_connected) {
1151                 port->guest_connected = false;
1152                 port->host_connected = false;
1153                 wake_up_interruptible(&port->waitqueue);
1154                 send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
1155         }
1156
1157         spin_lock_irq(&port->portdev->ports_lock);
1158         list_del(&port->list);
1159         spin_unlock_irq(&port->portdev->ports_lock);
1160
1161         if (is_console_port(port)) {
1162                 spin_lock_irq(&pdrvdata_lock);
1163                 list_del(&port->cons.list);
1164                 spin_unlock_irq(&pdrvdata_lock);
1165 #if 0
1166                 /*
1167                  * hvc_remove() not called as removing one hvc port
1168                  * results in other hvc ports getting frozen.
1169                  *
1170                  * Once this is resolved in hvc, this functionality
1171                  * will be enabled.  Till that is done, the -EPIPE
1172                  * return from get_chars() above will help
1173                  * hvc_console.c to clean up on ports we remove here.
1174                  */
1175                 hvc_remove(port->cons.hvc);
1176 #endif
1177         }
1178         sysfs_remove_group(&port->dev->kobj, &port_attribute_group);
1179         device_destroy(pdrvdata.class, port->dev->devt);
1180         cdev_del(&port->cdev);
1181
1182         /* Remove unused data this port might have received. */
1183         discard_port_data(port);
1184
1185         reclaim_consumed_buffers(port);
1186
1187         /* Remove buffers we queued up for the Host to send us data in. */
1188         while ((buf = virtqueue_detach_unused_buf(port->in_vq)))
1189                 free_buf(buf);
1190
1191         kfree(port->name);
1192
1193         debugfs_remove(port->debugfs_file);
1194
1195         kfree(port);
1196 }
1197
1198 /* Any private messages that the Host and Guest want to share */
1199 static void handle_control_message(struct ports_device *portdev,
1200                                    struct port_buffer *buf)
1201 {
1202         struct virtio_console_control *cpkt;
1203         struct port *port;
1204         size_t name_size;
1205         int err;
1206
1207         cpkt = (struct virtio_console_control *)(buf->buf + buf->offset);
1208
1209         port = find_port_by_id(portdev, cpkt->id);
1210         if (!port && cpkt->event != VIRTIO_CONSOLE_PORT_ADD) {
1211                 /* No valid header at start of buffer.  Drop it. */
1212                 dev_dbg(&portdev->vdev->dev,
1213                         "Invalid index %u in control packet\n", cpkt->id);
1214                 return;
1215         }
1216
1217         switch (cpkt->event) {
1218         case VIRTIO_CONSOLE_PORT_ADD:
1219                 if (port) {
1220                         dev_dbg(&portdev->vdev->dev,
1221                                 "Port %u already added\n", port->id);
1222                         send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1223                         break;
1224                 }
1225                 if (cpkt->id >= portdev->config.max_nr_ports) {
1226                         dev_warn(&portdev->vdev->dev,
1227                                 "Request for adding port with out-of-bound id %u, max. supported id: %u\n",
1228                                 cpkt->id, portdev->config.max_nr_ports - 1);
1229                         break;
1230                 }
1231                 add_port(portdev, cpkt->id);
1232                 break;
1233         case VIRTIO_CONSOLE_PORT_REMOVE:
1234                 remove_port(port);
1235                 break;
1236         case VIRTIO_CONSOLE_CONSOLE_PORT:
1237                 if (!cpkt->value)
1238                         break;
1239                 if (is_console_port(port))
1240                         break;
1241
1242                 init_port_console(port);
1243                 /*
1244                  * Could remove the port here in case init fails - but
1245                  * have to notify the host first.
1246                  */
1247                 break;
1248         case VIRTIO_CONSOLE_RESIZE: {
1249                 struct {
1250                         __u16 rows;
1251                         __u16 cols;
1252                 } size;
1253
1254                 if (!is_console_port(port))
1255                         break;
1256
1257                 memcpy(&size, buf->buf + buf->offset + sizeof(*cpkt),
1258                        sizeof(size));
1259                 set_console_size(port, size.rows, size.cols);
1260
1261                 port->cons.hvc->irq_requested = 1;
1262                 resize_console(port);
1263                 break;
1264         }
1265         case VIRTIO_CONSOLE_PORT_OPEN:
1266                 port->host_connected = cpkt->value;
1267                 wake_up_interruptible(&port->waitqueue);
1268                 /*
1269                  * If the host port got closed and the host had any
1270                  * unconsumed buffers, we'll be able to reclaim them
1271                  * now.
1272                  */
1273                 spin_lock_irq(&port->outvq_lock);
1274                 reclaim_consumed_buffers(port);
1275                 spin_unlock_irq(&port->outvq_lock);
1276                 break;
1277         case VIRTIO_CONSOLE_PORT_NAME:
1278                 /*
1279                  * Skip the size of the header and the cpkt to get the size
1280                  * of the name that was sent
1281                  */
1282                 name_size = buf->len - buf->offset - sizeof(*cpkt) + 1;
1283
1284                 port->name = kmalloc(name_size, GFP_KERNEL);
1285                 if (!port->name) {
1286                         dev_err(port->dev,
1287                                 "Not enough space to store port name\n");
1288                         break;
1289                 }
1290                 strncpy(port->name, buf->buf + buf->offset + sizeof(*cpkt),
1291                         name_size - 1);
1292                 port->name[name_size - 1] = 0;
1293
1294                 /*
1295                  * Since we only have one sysfs attribute, 'name',
1296                  * create it only if we have a name for the port.
1297                  */
1298                 err = sysfs_create_group(&port->dev->kobj,
1299                                          &port_attribute_group);
1300                 if (err) {
1301                         dev_err(port->dev,
1302                                 "Error %d creating sysfs device attributes\n",
1303                                 err);
1304                 } else {
1305                         /*
1306                          * Generate a udev event so that appropriate
1307                          * symlinks can be created based on udev
1308                          * rules.
1309                          */
1310                         kobject_uevent(&port->dev->kobj, KOBJ_CHANGE);
1311                 }
1312                 break;
1313         }
1314 }
1315
1316 static void control_work_handler(struct work_struct *work)
1317 {
1318         struct ports_device *portdev;
1319         struct virtqueue *vq;
1320         struct port_buffer *buf;
1321         unsigned int len;
1322
1323         portdev = container_of(work, struct ports_device, control_work);
1324         vq = portdev->c_ivq;
1325
1326         spin_lock(&portdev->cvq_lock);
1327         while ((buf = virtqueue_get_buf(vq, &len))) {
1328                 spin_unlock(&portdev->cvq_lock);
1329
1330                 buf->len = len;
1331                 buf->offset = 0;
1332
1333                 handle_control_message(portdev, buf);
1334
1335                 spin_lock(&portdev->cvq_lock);
1336                 if (add_inbuf(portdev->c_ivq, buf) < 0) {
1337                         dev_warn(&portdev->vdev->dev,
1338                                  "Error adding buffer to queue\n");
1339                         free_buf(buf);
1340                 }
1341         }
1342         spin_unlock(&portdev->cvq_lock);
1343 }
1344
1345 static void in_intr(struct virtqueue *vq)
1346 {
1347         struct port *port;
1348         unsigned long flags;
1349
1350         port = find_port_by_vq(vq->vdev->priv, vq);
1351         if (!port)
1352                 return;
1353
1354         spin_lock_irqsave(&port->inbuf_lock, flags);
1355         if (!port->inbuf)
1356                 port->inbuf = get_inbuf(port);
1357
1358         /*
1359          * Don't queue up data when port is closed.  This condition
1360          * can be reached when a console port is not yet connected (no
1361          * tty is spawned) and the host sends out data to console
1362          * ports.  For generic serial ports, the host won't
1363          * (shouldn't) send data till the guest is connected.
1364          */
1365         if (!port->guest_connected)
1366                 discard_port_data(port);
1367
1368         spin_unlock_irqrestore(&port->inbuf_lock, flags);
1369
1370         wake_up_interruptible(&port->waitqueue);
1371
1372         if (is_console_port(port) && hvc_poll(port->cons.hvc))
1373                 hvc_kick();
1374 }
1375
1376 static void control_intr(struct virtqueue *vq)
1377 {
1378         struct ports_device *portdev;
1379
1380         portdev = vq->vdev->priv;
1381         schedule_work(&portdev->control_work);
1382 }
1383
1384 static void config_intr(struct virtio_device *vdev)
1385 {
1386         struct ports_device *portdev;
1387
1388         portdev = vdev->priv;
1389
1390         if (!use_multiport(portdev)) {
1391                 struct port *port;
1392                 u16 rows, cols;
1393
1394                 vdev->config->get(vdev,
1395                                   offsetof(struct virtio_console_config, cols),
1396                                   &cols, sizeof(u16));
1397                 vdev->config->get(vdev,
1398                                   offsetof(struct virtio_console_config, rows),
1399                                   &rows, sizeof(u16));
1400
1401                 port = find_port_by_id(portdev, 0);
1402                 set_console_size(port, rows, cols);
1403
1404                 /*
1405                  * We'll use this way of resizing only for legacy
1406                  * support.  For newer userspace
1407                  * (VIRTIO_CONSOLE_F_MULTPORT+), use control messages
1408                  * to indicate console size changes so that it can be
1409                  * done per-port.
1410                  */
1411                 resize_console(port);
1412         }
1413 }
1414
1415 static int init_vqs(struct ports_device *portdev)
1416 {
1417         vq_callback_t **io_callbacks;
1418         char **io_names;
1419         struct virtqueue **vqs;
1420         u32 i, j, nr_ports, nr_queues;
1421         int err;
1422
1423         nr_ports = portdev->config.max_nr_ports;
1424         nr_queues = use_multiport(portdev) ? (nr_ports + 1) * 2 : 2;
1425
1426         vqs = kmalloc(nr_queues * sizeof(struct virtqueue *), GFP_KERNEL);
1427         if (!vqs) {
1428                 err = -ENOMEM;
1429                 goto fail;
1430         }
1431         io_callbacks = kmalloc(nr_queues * sizeof(vq_callback_t *), GFP_KERNEL);
1432         if (!io_callbacks) {
1433                 err = -ENOMEM;
1434                 goto free_vqs;
1435         }
1436         io_names = kmalloc(nr_queues * sizeof(char *), GFP_KERNEL);
1437         if (!io_names) {
1438                 err = -ENOMEM;
1439                 goto free_callbacks;
1440         }
1441         portdev->in_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
1442                                   GFP_KERNEL);
1443         if (!portdev->in_vqs) {
1444                 err = -ENOMEM;
1445                 goto free_names;
1446         }
1447         portdev->out_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
1448                                    GFP_KERNEL);
1449         if (!portdev->out_vqs) {
1450                 err = -ENOMEM;
1451                 goto free_invqs;
1452         }
1453
1454         /*
1455          * For backward compat (newer host but older guest), the host
1456          * spawns a console port first and also inits the vqs for port
1457          * 0 before others.
1458          */
1459         j = 0;
1460         io_callbacks[j] = in_intr;
1461         io_callbacks[j + 1] = NULL;
1462         io_names[j] = "input";
1463         io_names[j + 1] = "output";
1464         j += 2;
1465
1466         if (use_multiport(portdev)) {
1467                 io_callbacks[j] = control_intr;
1468                 io_callbacks[j + 1] = NULL;
1469                 io_names[j] = "control-i";
1470                 io_names[j + 1] = "control-o";
1471
1472                 for (i = 1; i < nr_ports; i++) {
1473                         j += 2;
1474                         io_callbacks[j] = in_intr;
1475                         io_callbacks[j + 1] = NULL;
1476                         io_names[j] = "input";
1477                         io_names[j + 1] = "output";
1478                 }
1479         }
1480         /* Find the queues. */
1481         err = portdev->vdev->config->find_vqs(portdev->vdev, nr_queues, vqs,
1482                                               io_callbacks,
1483                                               (const char **)io_names);
1484         if (err)
1485                 goto free_outvqs;
1486
1487         j = 0;
1488         portdev->in_vqs[0] = vqs[0];
1489         portdev->out_vqs[0] = vqs[1];
1490         j += 2;
1491         if (use_multiport(portdev)) {
1492                 portdev->c_ivq = vqs[j];
1493                 portdev->c_ovq = vqs[j + 1];
1494
1495                 for (i = 1; i < nr_ports; i++) {
1496                         j += 2;
1497                         portdev->in_vqs[i] = vqs[j];
1498                         portdev->out_vqs[i] = vqs[j + 1];
1499                 }
1500         }
1501         kfree(io_callbacks);
1502         kfree(io_names);
1503         kfree(vqs);
1504
1505         return 0;
1506
1507 free_names:
1508         kfree(io_names);
1509 free_callbacks:
1510         kfree(io_callbacks);
1511 free_outvqs:
1512         kfree(portdev->out_vqs);
1513 free_invqs:
1514         kfree(portdev->in_vqs);
1515 free_vqs:
1516         kfree(vqs);
1517 fail:
1518         return err;
1519 }
1520
1521 static const struct file_operations portdev_fops = {
1522         .owner = THIS_MODULE,
1523 };
1524
1525 /*
1526  * Once we're further in boot, we get probed like any other virtio
1527  * device.
1528  *
1529  * If the host also supports multiple console ports, we check the
1530  * config space to see how many ports the host has spawned.  We
1531  * initialize each port found.
1532  */
1533 static int __devinit virtcons_probe(struct virtio_device *vdev)
1534 {
1535         struct ports_device *portdev;
1536         int err;
1537         bool multiport;
1538
1539         portdev = kmalloc(sizeof(*portdev), GFP_KERNEL);
1540         if (!portdev) {
1541                 err = -ENOMEM;
1542                 goto fail;
1543         }
1544
1545         /* Attach this portdev to this virtio_device, and vice-versa. */
1546         portdev->vdev = vdev;
1547         vdev->priv = portdev;
1548
1549         spin_lock_irq(&pdrvdata_lock);
1550         portdev->drv_index = pdrvdata.index++;
1551         spin_unlock_irq(&pdrvdata_lock);
1552
1553         portdev->chr_major = register_chrdev(0, "virtio-portsdev",
1554                                              &portdev_fops);
1555         if (portdev->chr_major < 0) {
1556                 dev_err(&vdev->dev,
1557                         "Error %d registering chrdev for device %u\n",
1558                         portdev->chr_major, portdev->drv_index);
1559                 err = portdev->chr_major;
1560                 goto free;
1561         }
1562
1563         multiport = false;
1564         portdev->config.max_nr_ports = 1;
1565         if (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT)) {
1566                 multiport = true;
1567                 vdev->features[0] |= 1 << VIRTIO_CONSOLE_F_MULTIPORT;
1568
1569                 vdev->config->get(vdev, offsetof(struct virtio_console_config,
1570                                                  max_nr_ports),
1571                                   &portdev->config.max_nr_ports,
1572                                   sizeof(portdev->config.max_nr_ports));
1573         }
1574
1575         /* Let the Host know we support multiple ports.*/
1576         vdev->config->finalize_features(vdev);
1577
1578         err = init_vqs(portdev);
1579         if (err < 0) {
1580                 dev_err(&vdev->dev, "Error %d initializing vqs\n", err);
1581                 goto free_chrdev;
1582         }
1583
1584         spin_lock_init(&portdev->ports_lock);
1585         INIT_LIST_HEAD(&portdev->ports);
1586
1587         if (multiport) {
1588                 unsigned int nr_added_bufs;
1589
1590                 spin_lock_init(&portdev->cvq_lock);
1591                 INIT_WORK(&portdev->control_work, &control_work_handler);
1592
1593                 nr_added_bufs = fill_queue(portdev->c_ivq, &portdev->cvq_lock);
1594                 if (!nr_added_bufs) {
1595                         dev_err(&vdev->dev,
1596                                 "Error allocating buffers for control queue\n");
1597                         err = -ENOMEM;
1598                         goto free_vqs;
1599                 }
1600         } else {
1601                 /*
1602                  * For backward compatibility: Create a console port
1603                  * if we're running on older host.
1604                  */
1605                 add_port(portdev, 0);
1606         }
1607
1608         spin_lock_irq(&pdrvdata_lock);
1609         list_add_tail(&portdev->list, &pdrvdata.portdevs);
1610         spin_unlock_irq(&pdrvdata_lock);
1611
1612         __send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
1613                            VIRTIO_CONSOLE_DEVICE_READY, 1);
1614         return 0;
1615
1616 free_vqs:
1617         /* The host might want to notify mgmt sw about device add failure */
1618         __send_control_msg(portdev, VIRTIO_CONSOLE_BAD_ID,
1619                            VIRTIO_CONSOLE_DEVICE_READY, 0);
1620         vdev->config->del_vqs(vdev);
1621         kfree(portdev->in_vqs);
1622         kfree(portdev->out_vqs);
1623 free_chrdev:
1624         unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1625 free:
1626         kfree(portdev);
1627 fail:
1628         return err;
1629 }
1630
1631 static void virtcons_remove(struct virtio_device *vdev)
1632 {
1633         struct ports_device *portdev;
1634         struct port *port, *port2;
1635
1636         portdev = vdev->priv;
1637
1638         spin_lock_irq(&pdrvdata_lock);
1639         list_del(&portdev->list);
1640         spin_unlock_irq(&pdrvdata_lock);
1641
1642         /* Disable interrupts for vqs */
1643         vdev->config->reset(vdev);
1644         /* Finish up work that's lined up */
1645         cancel_work_sync(&portdev->control_work);
1646
1647         list_for_each_entry_safe(port, port2, &portdev->ports, list)
1648                 remove_port(port);
1649
1650         unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1651
1652         if (use_multiport(portdev)) {
1653                 struct port_buffer *buf;
1654                 unsigned int len;
1655
1656                 while ((buf = virtqueue_get_buf(portdev->c_ivq, &len)))
1657                         free_buf(buf);
1658
1659                 while ((buf = virtqueue_detach_unused_buf(portdev->c_ivq)))
1660                         free_buf(buf);
1661         }
1662
1663         vdev->config->del_vqs(vdev);
1664         kfree(portdev->in_vqs);
1665         kfree(portdev->out_vqs);
1666
1667         kfree(portdev);
1668 }
1669
1670 static struct virtio_device_id id_table[] = {
1671         { VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID },
1672         { 0 },
1673 };
1674
1675 static unsigned int features[] = {
1676         VIRTIO_CONSOLE_F_SIZE,
1677         VIRTIO_CONSOLE_F_MULTIPORT,
1678 };
1679
1680 static struct virtio_driver virtio_console = {
1681         .feature_table = features,
1682         .feature_table_size = ARRAY_SIZE(features),
1683         .driver.name =  KBUILD_MODNAME,
1684         .driver.owner = THIS_MODULE,
1685         .id_table =     id_table,
1686         .probe =        virtcons_probe,
1687         .remove =       virtcons_remove,
1688         .config_changed = config_intr,
1689 };
1690
1691 static int __init init(void)
1692 {
1693         int err;
1694
1695         pdrvdata.class = class_create(THIS_MODULE, "virtio-ports");
1696         if (IS_ERR(pdrvdata.class)) {
1697                 err = PTR_ERR(pdrvdata.class);
1698                 pr_err("Error %d creating virtio-ports class\n", err);
1699                 return err;
1700         }
1701
1702         pdrvdata.debugfs_dir = debugfs_create_dir("virtio-ports", NULL);
1703         if (!pdrvdata.debugfs_dir) {
1704                 pr_warning("Error %ld creating debugfs dir for virtio-ports\n",
1705                            PTR_ERR(pdrvdata.debugfs_dir));
1706         }
1707         INIT_LIST_HEAD(&pdrvdata.consoles);
1708         INIT_LIST_HEAD(&pdrvdata.portdevs);
1709
1710         return register_virtio_driver(&virtio_console);
1711 }
1712
1713 static void __exit fini(void)
1714 {
1715         unregister_virtio_driver(&virtio_console);
1716
1717         class_destroy(pdrvdata.class);
1718         if (pdrvdata.debugfs_dir)
1719                 debugfs_remove_recursive(pdrvdata.debugfs_dir);
1720 }
1721 module_init(init);
1722 module_exit(fini);
1723
1724 MODULE_DEVICE_TABLE(virtio, id_table);
1725 MODULE_DESCRIPTION("Virtio console driver");
1726 MODULE_LICENSE("GPL");