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