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