virtio: console: Remove cached data on port close
[safe/jmp/linux-2.6] / 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/device.h>
21 #include <linux/err.h>
22 #include <linux/fs.h>
23 #include <linux/init.h>
24 #include <linux/list.h>
25 #include <linux/poll.h>
26 #include <linux/sched.h>
27 #include <linux/spinlock.h>
28 #include <linux/virtio.h>
29 #include <linux/virtio_console.h>
30 #include <linux/wait.h>
31 #include <linux/workqueue.h>
32 #include "hvc_console.h"
33
34 /*
35  * This is a global struct for storing common data for all the devices
36  * this driver handles.
37  *
38  * Mainly, it has a linked list for all the consoles in one place so
39  * that callbacks from hvc for get_chars(), put_chars() work properly
40  * across multiple devices and multiple ports per device.
41  */
42 struct ports_driver_data {
43         /* Used for registering chardevs */
44         struct class *class;
45
46         /* Number of devices this driver is handling */
47         unsigned int index;
48
49         /*
50          * This is used to keep track of the number of hvc consoles
51          * spawned by this driver.  This number is given as the first
52          * argument to hvc_alloc().  To correctly map an initial
53          * console spawned via hvc_instantiate to the console being
54          * hooked up via hvc_alloc, we need to pass the same vtermno.
55          *
56          * We also just assume the first console being initialised was
57          * the first one that got used as the initial console.
58          */
59         unsigned int next_vtermno;
60
61         /* All the console devices handled by this driver */
62         struct list_head consoles;
63 };
64 static struct ports_driver_data pdrvdata;
65
66 DEFINE_SPINLOCK(pdrvdata_lock);
67
68 /* This struct holds information that's relevant only for console ports */
69 struct console {
70         /* We'll place all consoles in a list in the pdrvdata struct */
71         struct list_head list;
72
73         /* The hvc device associated with this console port */
74         struct hvc_struct *hvc;
75
76         /*
77          * This number identifies the number that we used to register
78          * with hvc in hvc_instantiate() and hvc_alloc(); this is the
79          * number passed on by the hvc callbacks to us to
80          * differentiate between the other console ports handled by
81          * this driver
82          */
83         u32 vtermno;
84 };
85
86 struct port_buffer {
87         char *buf;
88
89         /* size of the buffer in *buf above */
90         size_t size;
91
92         /* used length of the buffer */
93         size_t len;
94         /* offset in the buf from which to consume data */
95         size_t offset;
96 };
97
98 /*
99  * This is a per-device struct that stores data common to all the
100  * ports for that device (vdev->priv).
101  */
102 struct ports_device {
103         /*
104          * Workqueue handlers where we process deferred work after
105          * notification
106          */
107         struct work_struct control_work;
108
109         struct list_head ports;
110
111         /* To protect the list of ports */
112         spinlock_t ports_lock;
113
114         /* To protect the vq operations for the control channel */
115         spinlock_t cvq_lock;
116
117         /* The current config space is stored here */
118         struct virtio_console_config config;
119
120         /* The virtio device we're associated with */
121         struct virtio_device *vdev;
122
123         /*
124          * A couple of virtqueues for the control channel: one for
125          * guest->host transfers, one for host->guest transfers
126          */
127         struct virtqueue *c_ivq, *c_ovq;
128
129         /* Array of per-port IO virtqueues */
130         struct virtqueue **in_vqs, **out_vqs;
131
132         /* Used for numbering devices for sysfs and debugfs */
133         unsigned int drv_index;
134
135         /* Major number for this device.  Ports will be created as minors. */
136         int chr_major;
137 };
138
139 /* This struct holds the per-port data */
140 struct port {
141         /* Next port in the list, head is in the ports_device */
142         struct list_head list;
143
144         /* Pointer to the parent virtio_console device */
145         struct ports_device *portdev;
146
147         /* The current buffer from which data has to be fed to readers */
148         struct port_buffer *inbuf;
149
150         /*
151          * To protect the operations on the in_vq associated with this
152          * port.  Has to be a spinlock because it can be called from
153          * interrupt context (get_char()).
154          */
155         spinlock_t inbuf_lock;
156
157         /* The IO vqs for this port */
158         struct virtqueue *in_vq, *out_vq;
159
160         /*
161          * The entries in this struct will be valid if this port is
162          * hooked up to an hvc console
163          */
164         struct console cons;
165
166         /* Each port associates with a separate char device */
167         struct cdev cdev;
168         struct device *dev;
169
170         /* A waitqueue for poll() or blocking read operations */
171         wait_queue_head_t waitqueue;
172
173         /* The 'name' of the port that we expose via sysfs properties */
174         char *name;
175
176         /* The 'id' to identify the port with the Host */
177         u32 id;
178
179         /* Is the host device open */
180         bool host_connected;
181
182         /* We should allow only one process to open a port */
183         bool guest_connected;
184 };
185
186 /* This is the very early arch-specified put chars function. */
187 static int (*early_put_chars)(u32, const char *, int);
188
189 static struct port *find_port_by_vtermno(u32 vtermno)
190 {
191         struct port *port;
192         struct console *cons;
193         unsigned long flags;
194
195         spin_lock_irqsave(&pdrvdata_lock, flags);
196         list_for_each_entry(cons, &pdrvdata.consoles, list) {
197                 if (cons->vtermno == vtermno) {
198                         port = container_of(cons, struct port, cons);
199                         goto out;
200                 }
201         }
202         port = NULL;
203 out:
204         spin_unlock_irqrestore(&pdrvdata_lock, flags);
205         return port;
206 }
207
208 static struct port *find_port_by_id(struct ports_device *portdev, u32 id)
209 {
210         struct port *port;
211         unsigned long flags;
212
213         spin_lock_irqsave(&portdev->ports_lock, flags);
214         list_for_each_entry(port, &portdev->ports, list)
215                 if (port->id == id)
216                         goto out;
217         port = NULL;
218 out:
219         spin_unlock_irqrestore(&portdev->ports_lock, flags);
220
221         return port;
222 }
223
224 static struct port *find_port_by_vq(struct ports_device *portdev,
225                                     struct virtqueue *vq)
226 {
227         struct port *port;
228         unsigned long flags;
229
230         spin_lock_irqsave(&portdev->ports_lock, flags);
231         list_for_each_entry(port, &portdev->ports, list)
232                 if (port->in_vq == vq || port->out_vq == vq)
233                         goto out;
234         port = NULL;
235 out:
236         spin_unlock_irqrestore(&portdev->ports_lock, flags);
237         return port;
238 }
239
240 static bool is_console_port(struct port *port)
241 {
242         if (port->cons.hvc)
243                 return true;
244         return false;
245 }
246
247 static inline bool use_multiport(struct ports_device *portdev)
248 {
249         /*
250          * This condition can be true when put_chars is called from
251          * early_init
252          */
253         if (!portdev->vdev)
254                 return 0;
255         return portdev->vdev->features[0] & (1 << VIRTIO_CONSOLE_F_MULTIPORT);
256 }
257
258 static void free_buf(struct port_buffer *buf)
259 {
260         kfree(buf->buf);
261         kfree(buf);
262 }
263
264 static struct port_buffer *alloc_buf(size_t buf_size)
265 {
266         struct port_buffer *buf;
267
268         buf = kmalloc(sizeof(*buf), GFP_KERNEL);
269         if (!buf)
270                 goto fail;
271         buf->buf = kzalloc(buf_size, GFP_KERNEL);
272         if (!buf->buf)
273                 goto free_buf;
274         buf->len = 0;
275         buf->offset = 0;
276         buf->size = buf_size;
277         return buf;
278
279 free_buf:
280         kfree(buf);
281 fail:
282         return NULL;
283 }
284
285 /* Callers should take appropriate locks */
286 static void *get_inbuf(struct port *port)
287 {
288         struct port_buffer *buf;
289         struct virtqueue *vq;
290         unsigned int len;
291
292         vq = port->in_vq;
293         buf = vq->vq_ops->get_buf(vq, &len);
294         if (buf) {
295                 buf->len = len;
296                 buf->offset = 0;
297         }
298         return buf;
299 }
300
301 /*
302  * Create a scatter-gather list representing our input buffer and put
303  * it in the queue.
304  *
305  * Callers should take appropriate locks.
306  */
307 static int add_inbuf(struct virtqueue *vq, struct port_buffer *buf)
308 {
309         struct scatterlist sg[1];
310         int ret;
311
312         sg_init_one(sg, buf->buf, buf->size);
313
314         ret = vq->vq_ops->add_buf(vq, sg, 0, 1, buf);
315         vq->vq_ops->kick(vq);
316         return ret;
317 }
318
319 /* Discard any unread data this port has. Callers lockers. */
320 static void discard_port_data(struct port *port)
321 {
322         struct port_buffer *buf;
323         struct virtqueue *vq;
324         unsigned int len;
325
326         vq = port->in_vq;
327         if (port->inbuf)
328                 buf = port->inbuf;
329         else
330                 buf = vq->vq_ops->get_buf(vq, &len);
331
332         if (!buf)
333                 return;
334
335         if (add_inbuf(vq, buf) < 0) {
336                 buf->len = buf->offset = 0;
337                 dev_warn(port->dev, "Error adding buffer back to vq\n");
338                 return;
339         }
340
341         port->inbuf = NULL;
342 }
343
344 static bool port_has_data(struct port *port)
345 {
346         unsigned long flags;
347         bool ret;
348
349         ret = false;
350         spin_lock_irqsave(&port->inbuf_lock, flags);
351         if (port->inbuf)
352                 ret = true;
353         spin_unlock_irqrestore(&port->inbuf_lock, flags);
354
355         return ret;
356 }
357
358 static ssize_t send_control_msg(struct port *port, unsigned int event,
359                                 unsigned int value)
360 {
361         struct scatterlist sg[1];
362         struct virtio_console_control cpkt;
363         struct virtqueue *vq;
364         int len;
365
366         if (!use_multiport(port->portdev))
367                 return 0;
368
369         cpkt.id = port->id;
370         cpkt.event = event;
371         cpkt.value = value;
372
373         vq = port->portdev->c_ovq;
374
375         sg_init_one(sg, &cpkt, sizeof(cpkt));
376         if (vq->vq_ops->add_buf(vq, sg, 1, 0, &cpkt) >= 0) {
377                 vq->vq_ops->kick(vq);
378                 while (!vq->vq_ops->get_buf(vq, &len))
379                         cpu_relax();
380         }
381         return 0;
382 }
383
384 static ssize_t send_buf(struct port *port, void *in_buf, size_t in_count)
385 {
386         struct scatterlist sg[1];
387         struct virtqueue *out_vq;
388         ssize_t ret;
389         unsigned int len;
390
391         out_vq = port->out_vq;
392
393         sg_init_one(sg, in_buf, in_count);
394         ret = out_vq->vq_ops->add_buf(out_vq, sg, 1, 0, in_buf);
395
396         /* Tell Host to go! */
397         out_vq->vq_ops->kick(out_vq);
398
399         if (ret < 0) {
400                 len = 0;
401                 goto fail;
402         }
403
404         /*
405          * Wait till the host acknowledges it pushed out the data we
406          * sent. Also ensure we return to userspace the number of
407          * bytes that were successfully consumed by the host.
408          */
409         while (!out_vq->vq_ops->get_buf(out_vq, &len))
410                 cpu_relax();
411 fail:
412         /* We're expected to return the amount of data we wrote */
413         return len;
414 }
415
416 /*
417  * Give out the data that's requested from the buffer that we have
418  * queued up.
419  */
420 static ssize_t fill_readbuf(struct port *port, char *out_buf, size_t out_count,
421                             bool to_user)
422 {
423         struct port_buffer *buf;
424         unsigned long flags;
425
426         if (!out_count || !port_has_data(port))
427                 return 0;
428
429         buf = port->inbuf;
430         out_count = min(out_count, buf->len - buf->offset);
431
432         if (to_user) {
433                 ssize_t ret;
434
435                 ret = copy_to_user(out_buf, buf->buf + buf->offset, out_count);
436                 if (ret)
437                         return -EFAULT;
438         } else {
439                 memcpy(out_buf, buf->buf + buf->offset, out_count);
440         }
441
442         buf->offset += out_count;
443
444         if (buf->offset == buf->len) {
445                 /*
446                  * We're done using all the data in this buffer.
447                  * Re-queue so that the Host can send us more data.
448                  */
449                 spin_lock_irqsave(&port->inbuf_lock, flags);
450                 port->inbuf = NULL;
451
452                 if (add_inbuf(port->in_vq, buf) < 0)
453                         dev_warn(port->dev, "failed add_buf\n");
454
455                 spin_unlock_irqrestore(&port->inbuf_lock, flags);
456         }
457         /* Return the number of bytes actually copied */
458         return out_count;
459 }
460
461 /* The condition that must be true for polling to end */
462 static bool wait_is_over(struct port *port)
463 {
464         return port_has_data(port) || !port->host_connected;
465 }
466
467 static ssize_t port_fops_read(struct file *filp, char __user *ubuf,
468                               size_t count, loff_t *offp)
469 {
470         struct port *port;
471         ssize_t ret;
472
473         port = filp->private_data;
474
475         if (!port_has_data(port)) {
476                 /*
477                  * If nothing's connected on the host just return 0 in
478                  * case of list_empty; this tells the userspace app
479                  * that there's no connection
480                  */
481                 if (!port->host_connected)
482                         return 0;
483                 if (filp->f_flags & O_NONBLOCK)
484                         return -EAGAIN;
485
486                 ret = wait_event_interruptible(port->waitqueue,
487                                                wait_is_over(port));
488                 if (ret < 0)
489                         return ret;
490         }
491         /*
492          * We could've received a disconnection message while we were
493          * waiting for more data.
494          *
495          * This check is not clubbed in the if() statement above as we
496          * might receive some data as well as the host could get
497          * disconnected after we got woken up from our wait.  So we
498          * really want to give off whatever data we have and only then
499          * check for host_connected.
500          */
501         if (!port_has_data(port) && !port->host_connected)
502                 return 0;
503
504         return fill_readbuf(port, ubuf, count, true);
505 }
506
507 static ssize_t port_fops_write(struct file *filp, const char __user *ubuf,
508                                size_t count, loff_t *offp)
509 {
510         struct port *port;
511         char *buf;
512         ssize_t ret;
513
514         port = filp->private_data;
515
516         count = min((size_t)(32 * 1024), count);
517
518         buf = kmalloc(count, GFP_KERNEL);
519         if (!buf)
520                 return -ENOMEM;
521
522         ret = copy_from_user(buf, ubuf, count);
523         if (ret) {
524                 ret = -EFAULT;
525                 goto free_buf;
526         }
527
528         ret = send_buf(port, buf, count);
529 free_buf:
530         kfree(buf);
531         return ret;
532 }
533
534 static unsigned int port_fops_poll(struct file *filp, poll_table *wait)
535 {
536         struct port *port;
537         unsigned int ret;
538
539         port = filp->private_data;
540         poll_wait(filp, &port->waitqueue, wait);
541
542         ret = 0;
543         if (port->inbuf)
544                 ret |= POLLIN | POLLRDNORM;
545         if (port->host_connected)
546                 ret |= POLLOUT;
547         if (!port->host_connected)
548                 ret |= POLLHUP;
549
550         return ret;
551 }
552
553 static int port_fops_release(struct inode *inode, struct file *filp)
554 {
555         struct port *port;
556
557         port = filp->private_data;
558
559         /* Notify host of port being closed */
560         send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
561
562         spin_lock_irq(&port->inbuf_lock);
563         port->guest_connected = false;
564
565         discard_port_data(port);
566
567         spin_unlock_irq(&port->inbuf_lock);
568
569         return 0;
570 }
571
572 static int port_fops_open(struct inode *inode, struct file *filp)
573 {
574         struct cdev *cdev = inode->i_cdev;
575         struct port *port;
576
577         port = container_of(cdev, struct port, cdev);
578         filp->private_data = port;
579
580         /*
581          * Don't allow opening of console port devices -- that's done
582          * via /dev/hvc
583          */
584         if (is_console_port(port))
585                 return -ENXIO;
586
587         /* Allow only one process to open a particular port at a time */
588         spin_lock_irq(&port->inbuf_lock);
589         if (port->guest_connected) {
590                 spin_unlock_irq(&port->inbuf_lock);
591                 return -EMFILE;
592         }
593
594         port->guest_connected = true;
595         spin_unlock_irq(&port->inbuf_lock);
596
597         /* Notify host of port being opened */
598         send_control_msg(filp->private_data, VIRTIO_CONSOLE_PORT_OPEN, 1);
599
600         return 0;
601 }
602
603 /*
604  * The file operations that we support: programs in the guest can open
605  * a console device, read from it, write to it, poll for data and
606  * close it.  The devices are at
607  *   /dev/vport<device number>p<port number>
608  */
609 static const struct file_operations port_fops = {
610         .owner = THIS_MODULE,
611         .open  = port_fops_open,
612         .read  = port_fops_read,
613         .write = port_fops_write,
614         .poll  = port_fops_poll,
615         .release = port_fops_release,
616 };
617
618 /*
619  * The put_chars() callback is pretty straightforward.
620  *
621  * We turn the characters into a scatter-gather list, add it to the
622  * output queue and then kick the Host.  Then we sit here waiting for
623  * it to finish: inefficient in theory, but in practice
624  * implementations will do it immediately (lguest's Launcher does).
625  */
626 static int put_chars(u32 vtermno, const char *buf, int count)
627 {
628         struct port *port;
629
630         port = find_port_by_vtermno(vtermno);
631         if (!port)
632                 return 0;
633
634         if (unlikely(early_put_chars))
635                 return early_put_chars(vtermno, buf, count);
636
637         return send_buf(port, (void *)buf, count);
638 }
639
640 /*
641  * get_chars() is the callback from the hvc_console infrastructure
642  * when an interrupt is received.
643  *
644  * We call out to fill_readbuf that gets us the required data from the
645  * buffers that are queued up.
646  */
647 static int get_chars(u32 vtermno, char *buf, int count)
648 {
649         struct port *port;
650
651         port = find_port_by_vtermno(vtermno);
652         if (!port)
653                 return 0;
654
655         /* If we don't have an input queue yet, we can't get input. */
656         BUG_ON(!port->in_vq);
657
658         return fill_readbuf(port, buf, count, false);
659 }
660
661 static void resize_console(struct port *port)
662 {
663         struct virtio_device *vdev;
664         struct winsize ws;
665
666         vdev = port->portdev->vdev;
667         if (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_SIZE)) {
668                 vdev->config->get(vdev,
669                                   offsetof(struct virtio_console_config, cols),
670                                   &ws.ws_col, sizeof(u16));
671                 vdev->config->get(vdev,
672                                   offsetof(struct virtio_console_config, rows),
673                                   &ws.ws_row, sizeof(u16));
674                 hvc_resize(port->cons.hvc, ws);
675         }
676 }
677
678 static void virtcons_apply_config(struct virtio_device *vdev)
679 {
680         resize_console(find_port_by_vtermno(0));
681 }
682
683 /* We set the configuration at this point, since we now have a tty */
684 static int notifier_add_vio(struct hvc_struct *hp, int data)
685 {
686         struct port *port;
687
688         port = find_port_by_vtermno(hp->vtermno);
689         if (!port)
690                 return -EINVAL;
691
692         hp->irq_requested = 1;
693         resize_console(port);
694
695         return 0;
696 }
697
698 static void notifier_del_vio(struct hvc_struct *hp, int data)
699 {
700         hp->irq_requested = 0;
701 }
702
703 /* The operations for console ports. */
704 static const struct hv_ops hv_ops = {
705         .get_chars = get_chars,
706         .put_chars = put_chars,
707         .notifier_add = notifier_add_vio,
708         .notifier_del = notifier_del_vio,
709         .notifier_hangup = notifier_del_vio,
710 };
711
712 /*
713  * Console drivers are initialized very early so boot messages can go
714  * out, so we do things slightly differently from the generic virtio
715  * initialization of the net and block drivers.
716  *
717  * At this stage, the console is output-only.  It's too early to set
718  * up a virtqueue, so we let the drivers do some boutique early-output
719  * thing.
720  */
721 int __init virtio_cons_early_init(int (*put_chars)(u32, const char *, int))
722 {
723         early_put_chars = put_chars;
724         return hvc_instantiate(0, 0, &hv_ops);
725 }
726
727 int init_port_console(struct port *port)
728 {
729         int ret;
730
731         /*
732          * The Host's telling us this port is a console port.  Hook it
733          * up with an hvc console.
734          *
735          * To set up and manage our virtual console, we call
736          * hvc_alloc().
737          *
738          * The first argument of hvc_alloc() is the virtual console
739          * number.  The second argument is the parameter for the
740          * notification mechanism (like irq number).  We currently
741          * leave this as zero, virtqueues have implicit notifications.
742          *
743          * The third argument is a "struct hv_ops" containing the
744          * put_chars() get_chars(), notifier_add() and notifier_del()
745          * pointers.  The final argument is the output buffer size: we
746          * can do any size, so we put PAGE_SIZE here.
747          */
748         port->cons.vtermno = pdrvdata.next_vtermno;
749
750         port->cons.hvc = hvc_alloc(port->cons.vtermno, 0, &hv_ops, PAGE_SIZE);
751         if (IS_ERR(port->cons.hvc)) {
752                 ret = PTR_ERR(port->cons.hvc);
753                 port->cons.hvc = NULL;
754                 return ret;
755         }
756         spin_lock_irq(&pdrvdata_lock);
757         pdrvdata.next_vtermno++;
758         list_add_tail(&port->cons.list, &pdrvdata.consoles);
759         spin_unlock_irq(&pdrvdata_lock);
760         port->guest_connected = true;
761
762         /* Notify host of port being opened */
763         send_control_msg(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
764
765         return 0;
766 }
767
768 static ssize_t show_port_name(struct device *dev,
769                               struct device_attribute *attr, char *buffer)
770 {
771         struct port *port;
772
773         port = dev_get_drvdata(dev);
774
775         return sprintf(buffer, "%s\n", port->name);
776 }
777
778 static DEVICE_ATTR(name, S_IRUGO, show_port_name, NULL);
779
780 static struct attribute *port_sysfs_entries[] = {
781         &dev_attr_name.attr,
782         NULL
783 };
784
785 static struct attribute_group port_attribute_group = {
786         .name = NULL,           /* put in device directory */
787         .attrs = port_sysfs_entries,
788 };
789
790 /* Any private messages that the Host and Guest want to share */
791 static void handle_control_message(struct ports_device *portdev,
792                                    struct port_buffer *buf)
793 {
794         struct virtio_console_control *cpkt;
795         struct port *port;
796         size_t name_size;
797         int err;
798
799         cpkt = (struct virtio_console_control *)(buf->buf + buf->offset);
800
801         port = find_port_by_id(portdev, cpkt->id);
802         if (!port) {
803                 /* No valid header at start of buffer.  Drop it. */
804                 dev_dbg(&portdev->vdev->dev,
805                         "Invalid index %u in control packet\n", cpkt->id);
806                 return;
807         }
808
809         switch (cpkt->event) {
810         case VIRTIO_CONSOLE_CONSOLE_PORT:
811                 if (!cpkt->value)
812                         break;
813                 if (is_console_port(port))
814                         break;
815
816                 init_port_console(port);
817                 /*
818                  * Could remove the port here in case init fails - but
819                  * have to notify the host first.
820                  */
821                 break;
822         case VIRTIO_CONSOLE_RESIZE:
823                 if (!is_console_port(port))
824                         break;
825                 port->cons.hvc->irq_requested = 1;
826                 resize_console(port);
827                 break;
828         case VIRTIO_CONSOLE_PORT_OPEN:
829                 port->host_connected = cpkt->value;
830                 wake_up_interruptible(&port->waitqueue);
831                 break;
832         case VIRTIO_CONSOLE_PORT_NAME:
833                 /*
834                  * Skip the size of the header and the cpkt to get the size
835                  * of the name that was sent
836                  */
837                 name_size = buf->len - buf->offset - sizeof(*cpkt) + 1;
838
839                 port->name = kmalloc(name_size, GFP_KERNEL);
840                 if (!port->name) {
841                         dev_err(port->dev,
842                                 "Not enough space to store port name\n");
843                         break;
844                 }
845                 strncpy(port->name, buf->buf + buf->offset + sizeof(*cpkt),
846                         name_size - 1);
847                 port->name[name_size - 1] = 0;
848
849                 /*
850                  * Since we only have one sysfs attribute, 'name',
851                  * create it only if we have a name for the port.
852                  */
853                 err = sysfs_create_group(&port->dev->kobj,
854                                          &port_attribute_group);
855                 if (err)
856                         dev_err(port->dev,
857                                 "Error %d creating sysfs device attributes\n",
858                                 err);
859
860                 break;
861         }
862 }
863
864 static void control_work_handler(struct work_struct *work)
865 {
866         struct ports_device *portdev;
867         struct virtqueue *vq;
868         struct port_buffer *buf;
869         unsigned int len;
870
871         portdev = container_of(work, struct ports_device, control_work);
872         vq = portdev->c_ivq;
873
874         spin_lock(&portdev->cvq_lock);
875         while ((buf = vq->vq_ops->get_buf(vq, &len))) {
876                 spin_unlock(&portdev->cvq_lock);
877
878                 buf->len = len;
879                 buf->offset = 0;
880
881                 handle_control_message(portdev, buf);
882
883                 spin_lock(&portdev->cvq_lock);
884                 if (add_inbuf(portdev->c_ivq, buf) < 0) {
885                         dev_warn(&portdev->vdev->dev,
886                                  "Error adding buffer to queue\n");
887                         free_buf(buf);
888                 }
889         }
890         spin_unlock(&portdev->cvq_lock);
891 }
892
893 static void in_intr(struct virtqueue *vq)
894 {
895         struct port *port;
896         unsigned long flags;
897
898         port = find_port_by_vq(vq->vdev->priv, vq);
899         if (!port)
900                 return;
901
902         spin_lock_irqsave(&port->inbuf_lock, flags);
903         port->inbuf = get_inbuf(port);
904
905         /*
906          * Don't queue up data when port is closed.  This condition
907          * can be reached when a console port is not yet connected (no
908          * tty is spawned) and the host sends out data to console
909          * ports.  For generic serial ports, the host won't
910          * (shouldn't) send data till the guest is connected.
911          */
912         if (!port->guest_connected)
913                 discard_port_data(port);
914
915         spin_unlock_irqrestore(&port->inbuf_lock, flags);
916
917         wake_up_interruptible(&port->waitqueue);
918
919         if (is_console_port(port) && hvc_poll(port->cons.hvc))
920                 hvc_kick();
921 }
922
923 static void control_intr(struct virtqueue *vq)
924 {
925         struct ports_device *portdev;
926
927         portdev = vq->vdev->priv;
928         schedule_work(&portdev->control_work);
929 }
930
931 static void fill_queue(struct virtqueue *vq, spinlock_t *lock)
932 {
933         struct port_buffer *buf;
934         int ret;
935
936         do {
937                 buf = alloc_buf(PAGE_SIZE);
938                 if (!buf)
939                         break;
940
941                 spin_lock_irq(lock);
942                 ret = add_inbuf(vq, buf);
943                 if (ret < 0) {
944                         spin_unlock_irq(lock);
945                         free_buf(buf);
946                         break;
947                 }
948                 spin_unlock_irq(lock);
949         } while (ret > 0);
950 }
951
952 static int add_port(struct ports_device *portdev, u32 id)
953 {
954         struct port *port;
955         struct port_buffer *inbuf;
956         dev_t devt;
957         int err;
958
959         port = kmalloc(sizeof(*port), GFP_KERNEL);
960         if (!port) {
961                 err = -ENOMEM;
962                 goto fail;
963         }
964
965         port->portdev = portdev;
966         port->id = id;
967
968         port->name = NULL;
969         port->inbuf = NULL;
970         port->cons.hvc = NULL;
971
972         port->host_connected = port->guest_connected = false;
973
974         port->in_vq = portdev->in_vqs[port->id];
975         port->out_vq = portdev->out_vqs[port->id];
976
977         cdev_init(&port->cdev, &port_fops);
978
979         devt = MKDEV(portdev->chr_major, id);
980         err = cdev_add(&port->cdev, devt, 1);
981         if (err < 0) {
982                 dev_err(&port->portdev->vdev->dev,
983                         "Error %d adding cdev for port %u\n", err, id);
984                 goto free_port;
985         }
986         port->dev = device_create(pdrvdata.class, &port->portdev->vdev->dev,
987                                   devt, port, "vport%up%u",
988                                   port->portdev->drv_index, id);
989         if (IS_ERR(port->dev)) {
990                 err = PTR_ERR(port->dev);
991                 dev_err(&port->portdev->vdev->dev,
992                         "Error %d creating device for port %u\n",
993                         err, id);
994                 goto free_cdev;
995         }
996
997         spin_lock_init(&port->inbuf_lock);
998         init_waitqueue_head(&port->waitqueue);
999
1000         inbuf = alloc_buf(PAGE_SIZE);
1001         if (!inbuf) {
1002                 err = -ENOMEM;
1003                 goto free_device;
1004         }
1005
1006         /* Register the input buffer the first time. */
1007         add_inbuf(port->in_vq, inbuf);
1008
1009         /*
1010          * If we're not using multiport support, this has to be a console port
1011          */
1012         if (!use_multiport(port->portdev)) {
1013                 err = init_port_console(port);
1014                 if (err)
1015                         goto free_inbuf;
1016         }
1017
1018         spin_lock_irq(&portdev->ports_lock);
1019         list_add_tail(&port->list, &port->portdev->ports);
1020         spin_unlock_irq(&portdev->ports_lock);
1021
1022         /*
1023          * Tell the Host we're set so that it can send us various
1024          * configuration parameters for this port (eg, port name,
1025          * caching, whether this is a console port, etc.)
1026          */
1027         send_control_msg(port, VIRTIO_CONSOLE_PORT_READY, 1);
1028
1029         return 0;
1030
1031 free_inbuf:
1032         free_buf(inbuf);
1033 free_device:
1034         device_destroy(pdrvdata.class, port->dev->devt);
1035 free_cdev:
1036         cdev_del(&port->cdev);
1037 free_port:
1038         kfree(port);
1039 fail:
1040         return err;
1041 }
1042
1043 static int init_vqs(struct ports_device *portdev)
1044 {
1045         vq_callback_t **io_callbacks;
1046         char **io_names;
1047         struct virtqueue **vqs;
1048         u32 i, j, nr_ports, nr_queues;
1049         int err;
1050
1051         nr_ports = portdev->config.max_nr_ports;
1052         nr_queues = use_multiport(portdev) ? (nr_ports + 1) * 2 : 2;
1053
1054         vqs = kmalloc(nr_queues * sizeof(struct virtqueue *), GFP_KERNEL);
1055         if (!vqs) {
1056                 err = -ENOMEM;
1057                 goto fail;
1058         }
1059         io_callbacks = kmalloc(nr_queues * sizeof(vq_callback_t *), GFP_KERNEL);
1060         if (!io_callbacks) {
1061                 err = -ENOMEM;
1062                 goto free_vqs;
1063         }
1064         io_names = kmalloc(nr_queues * sizeof(char *), GFP_KERNEL);
1065         if (!io_names) {
1066                 err = -ENOMEM;
1067                 goto free_callbacks;
1068         }
1069         portdev->in_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
1070                                   GFP_KERNEL);
1071         if (!portdev->in_vqs) {
1072                 err = -ENOMEM;
1073                 goto free_names;
1074         }
1075         portdev->out_vqs = kmalloc(nr_ports * sizeof(struct virtqueue *),
1076                                    GFP_KERNEL);
1077         if (!portdev->out_vqs) {
1078                 err = -ENOMEM;
1079                 goto free_invqs;
1080         }
1081
1082         /*
1083          * For backward compat (newer host but older guest), the host
1084          * spawns a console port first and also inits the vqs for port
1085          * 0 before others.
1086          */
1087         j = 0;
1088         io_callbacks[j] = in_intr;
1089         io_callbacks[j + 1] = NULL;
1090         io_names[j] = "input";
1091         io_names[j + 1] = "output";
1092         j += 2;
1093
1094         if (use_multiport(portdev)) {
1095                 io_callbacks[j] = control_intr;
1096                 io_callbacks[j + 1] = NULL;
1097                 io_names[j] = "control-i";
1098                 io_names[j + 1] = "control-o";
1099
1100                 for (i = 1; i < nr_ports; i++) {
1101                         j += 2;
1102                         io_callbacks[j] = in_intr;
1103                         io_callbacks[j + 1] = NULL;
1104                         io_names[j] = "input";
1105                         io_names[j + 1] = "output";
1106                 }
1107         }
1108         /* Find the queues. */
1109         err = portdev->vdev->config->find_vqs(portdev->vdev, nr_queues, vqs,
1110                                               io_callbacks,
1111                                               (const char **)io_names);
1112         if (err)
1113                 goto free_outvqs;
1114
1115         j = 0;
1116         portdev->in_vqs[0] = vqs[0];
1117         portdev->out_vqs[0] = vqs[1];
1118         j += 2;
1119         if (use_multiport(portdev)) {
1120                 portdev->c_ivq = vqs[j];
1121                 portdev->c_ovq = vqs[j + 1];
1122
1123                 for (i = 1; i < nr_ports; i++) {
1124                         j += 2;
1125                         portdev->in_vqs[i] = vqs[j];
1126                         portdev->out_vqs[i] = vqs[j + 1];
1127                 }
1128         }
1129         kfree(io_callbacks);
1130         kfree(io_names);
1131         kfree(vqs);
1132
1133         return 0;
1134
1135 free_names:
1136         kfree(io_names);
1137 free_callbacks:
1138         kfree(io_callbacks);
1139 free_outvqs:
1140         kfree(portdev->out_vqs);
1141 free_invqs:
1142         kfree(portdev->in_vqs);
1143 free_vqs:
1144         kfree(vqs);
1145 fail:
1146         return err;
1147 }
1148
1149 static const struct file_operations portdev_fops = {
1150         .owner = THIS_MODULE,
1151 };
1152
1153 /*
1154  * Once we're further in boot, we get probed like any other virtio
1155  * device.
1156  *
1157  * If the host also supports multiple console ports, we check the
1158  * config space to see how many ports the host has spawned.  We
1159  * initialize each port found.
1160  */
1161 static int __devinit virtcons_probe(struct virtio_device *vdev)
1162 {
1163         struct ports_device *portdev;
1164         u32 i;
1165         int err;
1166         bool multiport;
1167
1168         portdev = kmalloc(sizeof(*portdev), GFP_KERNEL);
1169         if (!portdev) {
1170                 err = -ENOMEM;
1171                 goto fail;
1172         }
1173
1174         /* Attach this portdev to this virtio_device, and vice-versa. */
1175         portdev->vdev = vdev;
1176         vdev->priv = portdev;
1177
1178         spin_lock_irq(&pdrvdata_lock);
1179         portdev->drv_index = pdrvdata.index++;
1180         spin_unlock_irq(&pdrvdata_lock);
1181
1182         portdev->chr_major = register_chrdev(0, "virtio-portsdev",
1183                                              &portdev_fops);
1184         if (portdev->chr_major < 0) {
1185                 dev_err(&vdev->dev,
1186                         "Error %d registering chrdev for device %u\n",
1187                         portdev->chr_major, portdev->drv_index);
1188                 err = portdev->chr_major;
1189                 goto free;
1190         }
1191
1192         multiport = false;
1193         portdev->config.nr_ports = 1;
1194         portdev->config.max_nr_ports = 1;
1195         if (virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT)) {
1196                 multiport = true;
1197                 vdev->features[0] |= 1 << VIRTIO_CONSOLE_F_MULTIPORT;
1198
1199                 vdev->config->get(vdev, offsetof(struct virtio_console_config,
1200                                                  nr_ports),
1201                                   &portdev->config.nr_ports,
1202                                   sizeof(portdev->config.nr_ports));
1203                 vdev->config->get(vdev, offsetof(struct virtio_console_config,
1204                                                  max_nr_ports),
1205                                   &portdev->config.max_nr_ports,
1206                                   sizeof(portdev->config.max_nr_ports));
1207                 if (portdev->config.nr_ports > portdev->config.max_nr_ports) {
1208                         dev_warn(&vdev->dev,
1209                                  "More ports (%u) specified than allowed (%u). Will init %u ports.",
1210                                  portdev->config.nr_ports,
1211                                  portdev->config.max_nr_ports,
1212                                  portdev->config.max_nr_ports);
1213
1214                         portdev->config.nr_ports = portdev->config.max_nr_ports;
1215                 }
1216         }
1217
1218         /* Let the Host know we support multiple ports.*/
1219         vdev->config->finalize_features(vdev);
1220
1221         err = init_vqs(portdev);
1222         if (err < 0) {
1223                 dev_err(&vdev->dev, "Error %d initializing vqs\n", err);
1224                 goto free_chrdev;
1225         }
1226
1227         spin_lock_init(&portdev->ports_lock);
1228         INIT_LIST_HEAD(&portdev->ports);
1229
1230         if (multiport) {
1231                 spin_lock_init(&portdev->cvq_lock);
1232                 INIT_WORK(&portdev->control_work, &control_work_handler);
1233
1234                 fill_queue(portdev->c_ivq, &portdev->cvq_lock);
1235         }
1236
1237         for (i = 0; i < portdev->config.nr_ports; i++)
1238                 add_port(portdev, i);
1239
1240         /* Start using the new console output. */
1241         early_put_chars = NULL;
1242         return 0;
1243
1244 free_chrdev:
1245         unregister_chrdev(portdev->chr_major, "virtio-portsdev");
1246 free:
1247         kfree(portdev);
1248 fail:
1249         return err;
1250 }
1251
1252 static struct virtio_device_id id_table[] = {
1253         { VIRTIO_ID_CONSOLE, VIRTIO_DEV_ANY_ID },
1254         { 0 },
1255 };
1256
1257 static unsigned int features[] = {
1258         VIRTIO_CONSOLE_F_SIZE,
1259         VIRTIO_CONSOLE_F_MULTIPORT,
1260 };
1261
1262 static struct virtio_driver virtio_console = {
1263         .feature_table = features,
1264         .feature_table_size = ARRAY_SIZE(features),
1265         .driver.name =  KBUILD_MODNAME,
1266         .driver.owner = THIS_MODULE,
1267         .id_table =     id_table,
1268         .probe =        virtcons_probe,
1269         .config_changed = virtcons_apply_config,
1270 };
1271
1272 static int __init init(void)
1273 {
1274         int err;
1275
1276         pdrvdata.class = class_create(THIS_MODULE, "virtio-ports");
1277         if (IS_ERR(pdrvdata.class)) {
1278                 err = PTR_ERR(pdrvdata.class);
1279                 pr_err("Error %d creating virtio-ports class\n", err);
1280                 return err;
1281         }
1282         INIT_LIST_HEAD(&pdrvdata.consoles);
1283
1284         return register_virtio_driver(&virtio_console);
1285 }
1286 module_init(init);
1287
1288 MODULE_DEVICE_TABLE(virtio, id_table);
1289 MODULE_DESCRIPTION("Virtio console driver");
1290 MODULE_LICENSE("GPL");