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