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