Merge tag 'v1.2.0' into tizen-arm
[sdk/emulator/qemu.git] / hw / virtio-serial-bus.c
1 /*
2  * A bus for connecting virtio serial and console ports
3  *
4  * Copyright (C) 2009, 2010 Red Hat, Inc.
5  *
6  * Author(s):
7  *  Amit Shah <amit.shah@redhat.com>
8  *
9  * Some earlier parts are:
10  *  Copyright IBM, Corp. 2008
11  * authored by
12  *  Christian Ehrhardt <ehrhardt@linux.vnet.ibm.com>
13  *
14  * This work is licensed under the terms of the GNU GPL, version 2.  See
15  * the COPYING file in the top-level directory.
16  *
17  * Contributions after 2012-01-13 are licensed under the terms of the
18  * GNU GPL, version 2 or (at your option) any later version.
19  */
20
21 #include "iov.h"
22 #include "monitor.h"
23 #include "qemu-queue.h"
24 #include "sysbus.h"
25 #include "trace.h"
26 #include "virtio-serial.h"
27 #include "virtio-transport.h"
28
29 /* The virtio-serial bus on top of which the ports will ride as devices */
30 struct VirtIOSerialBus {
31     BusState qbus;
32
33     /* This is the parent device that provides the bus for ports. */
34     VirtIOSerial *vser;
35
36     /* The maximum number of ports that can ride on top of this bus */
37     uint32_t max_nr_ports;
38 };
39
40 struct VirtIOSerial {
41     VirtIODevice vdev;
42
43     VirtQueue *c_ivq, *c_ovq;
44     /* Arrays of ivqs and ovqs: one per port */
45     VirtQueue **ivqs, **ovqs;
46
47     VirtIOSerialBus bus;
48
49     DeviceState *qdev;
50
51     QTAILQ_HEAD(, VirtIOSerialPort) ports;
52
53     /* bitmap for identifying active ports */
54     uint32_t *ports_map;
55
56     struct virtio_console_config config;
57 };
58
59 static VirtIOSerialPort *find_port_by_id(VirtIOSerial *vser, uint32_t id)
60 {
61     VirtIOSerialPort *port;
62
63     if (id == VIRTIO_CONSOLE_BAD_ID) {
64         return NULL;
65     }
66
67     QTAILQ_FOREACH(port, &vser->ports, next) {
68         if (port->id == id)
69             return port;
70     }
71     return NULL;
72 }
73
74 static VirtIOSerialPort *find_port_by_vq(VirtIOSerial *vser, VirtQueue *vq)
75 {
76     VirtIOSerialPort *port;
77
78     QTAILQ_FOREACH(port, &vser->ports, next) {
79         if (port->ivq == vq || port->ovq == vq)
80             return port;
81     }
82     return NULL;
83 }
84
85 static bool use_multiport(VirtIOSerial *vser)
86 {
87     return vser->vdev.guest_features & (1 << VIRTIO_CONSOLE_F_MULTIPORT);
88 }
89
90 static size_t write_to_port(VirtIOSerialPort *port,
91                             const uint8_t *buf, size_t size)
92 {
93     VirtQueueElement elem;
94     VirtQueue *vq;
95     size_t offset;
96
97     vq = port->ivq;
98     if (!virtio_queue_ready(vq)) {
99         return 0;
100     }
101
102     offset = 0;
103     while (offset < size) {
104         size_t len;
105
106         if (!virtqueue_pop(vq, &elem)) {
107             break;
108         }
109
110         len = iov_from_buf(elem.in_sg, elem.in_num, 0,
111                            buf + offset, size - offset);
112         offset += len;
113
114         virtqueue_push(vq, &elem, len);
115     }
116
117     virtio_notify(&port->vser->vdev, vq);
118     return offset;
119 }
120
121 static void discard_vq_data(VirtQueue *vq, VirtIODevice *vdev)
122 {
123     VirtQueueElement elem;
124
125     if (!virtio_queue_ready(vq)) {
126         return;
127     }
128     while (virtqueue_pop(vq, &elem)) {
129         virtqueue_push(vq, &elem, 0);
130     }
131     virtio_notify(vdev, vq);
132 }
133
134 static void do_flush_queued_data(VirtIOSerialPort *port, VirtQueue *vq,
135                                  VirtIODevice *vdev)
136 {
137     VirtIOSerialPortClass *vsc;
138
139     assert(port);
140     assert(virtio_queue_ready(vq));
141
142     vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
143
144     while (!port->throttled) {
145         unsigned int i;
146
147         /* Pop an elem only if we haven't left off a previous one mid-way */
148         if (!port->elem.out_num) {
149             if (!virtqueue_pop(vq, &port->elem)) {
150                 break;
151             }
152             port->iov_idx = 0;
153             port->iov_offset = 0;
154         }
155
156         for (i = port->iov_idx; i < port->elem.out_num; i++) {
157             size_t buf_size;
158             ssize_t ret;
159
160             buf_size = port->elem.out_sg[i].iov_len - port->iov_offset;
161             ret = vsc->have_data(port,
162                                   port->elem.out_sg[i].iov_base
163                                   + port->iov_offset,
164                                   buf_size);
165             if (ret < 0 && ret != -EAGAIN) {
166                 /* We don't handle any other type of errors here */
167                 abort();
168             }
169             if (ret == -EAGAIN || (ret >= 0 && ret < buf_size)) {
170                 /*
171                  * this is a temporary check until chardevs can signal to
172                  * frontends that they are writable again. This prevents
173                  * the console from going into throttled mode (forever)
174                  * if virtio-console is connected to a pty without a
175                  * listener. Otherwise the guest spins forever.
176                  * We can revert this if
177                  * 1: chardevs can notify frondends
178                  * 2: the guest driver does not spin in these cases
179                  */
180                 if (!vsc->is_console) {
181                     virtio_serial_throttle_port(port, true);
182                 }
183                 port->iov_idx = i;
184                 if (ret > 0) {
185                     port->iov_offset += ret;
186                 }
187                 break;
188             }
189             port->iov_offset = 0;
190         }
191         if (port->throttled) {
192             break;
193         }
194         virtqueue_push(vq, &port->elem, 0);
195         port->elem.out_num = 0;
196     }
197     virtio_notify(vdev, vq);
198 }
199
200 static void flush_queued_data(VirtIOSerialPort *port)
201 {
202     assert(port);
203
204     if (!virtio_queue_ready(port->ovq)) {
205         return;
206     }
207     do_flush_queued_data(port, port->ovq, &port->vser->vdev);
208 }
209
210 static size_t send_control_msg(VirtIOSerialPort *port, void *buf, size_t len)
211 {
212     VirtQueueElement elem;
213     VirtQueue *vq;
214     struct virtio_console_control *cpkt;
215
216     vq = port->vser->c_ivq;
217     if (!virtio_queue_ready(vq)) {
218         return 0;
219     }
220     if (!virtqueue_pop(vq, &elem)) {
221         return 0;
222     }
223
224     cpkt = (struct virtio_console_control *)buf;
225     stl_p(&cpkt->id, port->id);
226     memcpy(elem.in_sg[0].iov_base, buf, len);
227
228     virtqueue_push(vq, &elem, len);
229     virtio_notify(&port->vser->vdev, vq);
230     return len;
231 }
232
233 static size_t send_control_event(VirtIOSerialPort *port, uint16_t event,
234                                  uint16_t value)
235 {
236     struct virtio_console_control cpkt;
237
238     stw_p(&cpkt.event, event);
239     stw_p(&cpkt.value, value);
240
241     trace_virtio_serial_send_control_event(port->id, event, value);
242     return send_control_msg(port, &cpkt, sizeof(cpkt));
243 }
244
245 /* Functions for use inside qemu to open and read from/write to ports */
246 int virtio_serial_open(VirtIOSerialPort *port)
247 {
248     /* Don't allow opening an already-open port */
249     if (port->host_connected) {
250         return 0;
251     }
252     /* Send port open notification to the guest */
253     port->host_connected = true;
254     send_control_event(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
255
256     return 0;
257 }
258
259 int virtio_serial_close(VirtIOSerialPort *port)
260 {
261     port->host_connected = false;
262     /*
263      * If there's any data the guest sent which the app didn't
264      * consume, reset the throttling flag and discard the data.
265      */
266     port->throttled = false;
267     discard_vq_data(port->ovq, &port->vser->vdev);
268
269     send_control_event(port, VIRTIO_CONSOLE_PORT_OPEN, 0);
270
271     return 0;
272 }
273
274 /* Individual ports/apps call this function to write to the guest. */
275 ssize_t virtio_serial_write(VirtIOSerialPort *port, const uint8_t *buf,
276                             size_t size)
277 {
278     if (!port || !port->host_connected || !port->guest_connected) {
279         return 0;
280     }
281     return write_to_port(port, buf, size);
282 }
283
284 /*
285  * Readiness of the guest to accept data on a port.
286  * Returns max. data the guest can receive
287  */
288 size_t virtio_serial_guest_ready(VirtIOSerialPort *port)
289 {
290     VirtQueue *vq = port->ivq;
291
292     if (!virtio_queue_ready(vq) ||
293         !(port->vser->vdev.status & VIRTIO_CONFIG_S_DRIVER_OK) ||
294         virtio_queue_empty(vq)) {
295         return 0;
296     }
297     if (use_multiport(port->vser) && !port->guest_connected) {
298         return 0;
299     }
300
301     if (virtqueue_avail_bytes(vq, 4096, 0)) {
302         return 4096;
303     }
304     if (virtqueue_avail_bytes(vq, 1, 0)) {
305         return 1;
306     }
307     return 0;
308 }
309
310 static void flush_queued_data_bh(void *opaque)
311 {
312     VirtIOSerialPort *port = opaque;
313
314     flush_queued_data(port);
315 }
316
317 void virtio_serial_throttle_port(VirtIOSerialPort *port, bool throttle)
318 {
319     if (!port) {
320         return;
321     }
322
323     trace_virtio_serial_throttle_port(port->id, throttle);
324     port->throttled = throttle;
325     if (throttle) {
326         return;
327     }
328     qemu_bh_schedule(port->bh);
329 }
330
331 /* Guest wants to notify us of some event */
332 static void handle_control_message(VirtIOSerial *vser, void *buf, size_t len)
333 {
334     struct VirtIOSerialPort *port;
335     VirtIOSerialPortClass *vsc;
336     struct virtio_console_control cpkt, *gcpkt;
337     uint8_t *buffer;
338     size_t buffer_len;
339
340     gcpkt = buf;
341
342     if (len < sizeof(cpkt)) {
343         /* The guest sent an invalid control packet */
344         return;
345     }
346
347     cpkt.event = lduw_p(&gcpkt->event);
348     cpkt.value = lduw_p(&gcpkt->value);
349
350     trace_virtio_serial_handle_control_message(cpkt.event, cpkt.value);
351
352     if (cpkt.event == VIRTIO_CONSOLE_DEVICE_READY) {
353         if (!cpkt.value) {
354             error_report("virtio-serial-bus: Guest failure in adding device %s",
355                          vser->bus.qbus.name);
356             return;
357         }
358         /*
359          * The device is up, we can now tell the device about all the
360          * ports we have here.
361          */
362         QTAILQ_FOREACH(port, &vser->ports, next) {
363             send_control_event(port, VIRTIO_CONSOLE_PORT_ADD, 1);
364         }
365         return;
366     }
367
368     port = find_port_by_id(vser, ldl_p(&gcpkt->id));
369     if (!port) {
370         error_report("virtio-serial-bus: Unexpected port id %u for device %s",
371                      ldl_p(&gcpkt->id), vser->bus.qbus.name);
372         return;
373     }
374
375     trace_virtio_serial_handle_control_message_port(port->id);
376
377     vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
378
379     switch(cpkt.event) {
380     case VIRTIO_CONSOLE_PORT_READY:
381         if (!cpkt.value) {
382             error_report("virtio-serial-bus: Guest failure in adding port %u for device %s",
383                          port->id, vser->bus.qbus.name);
384             break;
385         }
386         /*
387          * Now that we know the guest asked for the port name, we're
388          * sure the guest has initialised whatever state is necessary
389          * for this port. Now's a good time to let the guest know if
390          * this port is a console port so that the guest can hook it
391          * up to hvc.
392          */
393         if (vsc->is_console) {
394             send_control_event(port, VIRTIO_CONSOLE_CONSOLE_PORT, 1);
395         }
396
397         if (port->name) {
398             stw_p(&cpkt.event, VIRTIO_CONSOLE_PORT_NAME);
399             stw_p(&cpkt.value, 1);
400
401             buffer_len = sizeof(cpkt) + strlen(port->name) + 1;
402             buffer = g_malloc(buffer_len);
403
404             memcpy(buffer, &cpkt, sizeof(cpkt));
405             memcpy(buffer + sizeof(cpkt), port->name, strlen(port->name));
406             buffer[buffer_len - 1] = 0;
407
408             send_control_msg(port, buffer, buffer_len);
409             g_free(buffer);
410         }
411
412         if (port->host_connected) {
413             send_control_event(port, VIRTIO_CONSOLE_PORT_OPEN, 1);
414         }
415
416         /*
417          * When the guest has asked us for this information it means
418          * the guest is all setup and has its virtqueues
419          * initialised. If some app is interested in knowing about
420          * this event, let it know.
421          */
422         if (vsc->guest_ready) {
423             vsc->guest_ready(port);
424         }
425         break;
426
427     case VIRTIO_CONSOLE_PORT_OPEN:
428         port->guest_connected = cpkt.value;
429         if (cpkt.value && vsc->guest_open) {
430             /* Send the guest opened notification if an app is interested */
431             vsc->guest_open(port);
432         }
433
434         if (!cpkt.value && vsc->guest_close) {
435             /* Send the guest closed notification if an app is interested */
436             vsc->guest_close(port);
437         }
438         break;
439     }
440 }
441
442 static void control_in(VirtIODevice *vdev, VirtQueue *vq)
443 {
444 }
445
446 static void control_out(VirtIODevice *vdev, VirtQueue *vq)
447 {
448     VirtQueueElement elem;
449     VirtIOSerial *vser;
450     uint8_t *buf;
451     size_t len;
452
453     vser = DO_UPCAST(VirtIOSerial, vdev, vdev);
454
455     len = 0;
456     buf = NULL;
457     while (virtqueue_pop(vq, &elem)) {
458         size_t cur_len;
459
460         cur_len = iov_size(elem.out_sg, elem.out_num);
461         /*
462          * Allocate a new buf only if we didn't have one previously or
463          * if the size of the buf differs
464          */
465         if (cur_len > len) {
466             g_free(buf);
467
468             buf = g_malloc(cur_len);
469             len = cur_len;
470         }
471         iov_to_buf(elem.out_sg, elem.out_num, 0, buf, cur_len);
472
473         handle_control_message(vser, buf, cur_len);
474         virtqueue_push(vq, &elem, 0);
475     }
476     g_free(buf);
477     virtio_notify(vdev, vq);
478 }
479
480 /* Guest wrote something to some port. */
481 static void handle_output(VirtIODevice *vdev, VirtQueue *vq)
482 {
483     VirtIOSerial *vser;
484     VirtIOSerialPort *port;
485
486     vser = DO_UPCAST(VirtIOSerial, vdev, vdev);
487     port = find_port_by_vq(vser, vq);
488
489     if (!port || !port->host_connected) {
490         discard_vq_data(vq, vdev);
491         return;
492     }
493
494     if (!port->throttled) {
495         do_flush_queued_data(port, vq, vdev);
496         return;
497     }
498 }
499
500 static void handle_input(VirtIODevice *vdev, VirtQueue *vq)
501 {
502 }
503
504 static uint32_t get_features(VirtIODevice *vdev, uint32_t features)
505 {
506     VirtIOSerial *vser;
507
508     vser = DO_UPCAST(VirtIOSerial, vdev, vdev);
509
510     if (vser->bus.max_nr_ports > 1) {
511         features |= (1 << VIRTIO_CONSOLE_F_MULTIPORT);
512     }
513     return features;
514 }
515
516 /* Guest requested config info */
517 static void get_config(VirtIODevice *vdev, uint8_t *config_data)
518 {
519     VirtIOSerial *vser;
520
521     vser = DO_UPCAST(VirtIOSerial, vdev, vdev);
522     memcpy(config_data, &vser->config, sizeof(struct virtio_console_config));
523 }
524
525 static void set_config(VirtIODevice *vdev, const uint8_t *config_data)
526 {
527     struct virtio_console_config config;
528
529     memcpy(&config, config_data, sizeof(config));
530 }
531
532 static void guest_reset(VirtIOSerial *vser)
533 {
534     VirtIOSerialPort *port;
535     VirtIOSerialPortClass *vsc;
536
537     QTAILQ_FOREACH(port, &vser->ports, next) {
538         vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
539         if (port->guest_connected) {
540             port->guest_connected = false;
541
542             if (vsc->guest_close)
543                 vsc->guest_close(port);
544         }
545     }
546 }
547
548 static void set_status(VirtIODevice *vdev, uint8_t status)
549 {
550     VirtIOSerial *vser;
551     VirtIOSerialPort *port;
552
553     vser = DO_UPCAST(VirtIOSerial, vdev, vdev);
554     port = find_port_by_id(vser, 0);
555
556     if (port && !use_multiport(port->vser)
557         && (status & VIRTIO_CONFIG_S_DRIVER_OK)) {
558         /*
559          * Non-multiport guests won't be able to tell us guest
560          * open/close status.  Such guests can only have a port at id
561          * 0, so set guest_connected for such ports as soon as guest
562          * is up.
563          */
564         port->guest_connected = true;
565     }
566     if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
567         guest_reset(vser);
568     }
569 }
570
571 static void vser_reset(VirtIODevice *vdev)
572 {
573     VirtIOSerial *vser;
574
575     vser = DO_UPCAST(VirtIOSerial, vdev, vdev);
576     guest_reset(vser);
577 }
578
579 static void virtio_serial_save(QEMUFile *f, void *opaque)
580 {
581     VirtIOSerial *s = opaque;
582     VirtIOSerialPort *port;
583     uint32_t nr_active_ports;
584     unsigned int i, max_nr_ports;
585
586     /* The virtio device */
587     virtio_save(&s->vdev, f);
588
589     /* The config space */
590     qemu_put_be16s(f, &s->config.cols);
591     qemu_put_be16s(f, &s->config.rows);
592
593     qemu_put_be32s(f, &s->config.max_nr_ports);
594
595     /* The ports map */
596     max_nr_ports = tswap32(s->config.max_nr_ports);
597     for (i = 0; i < (max_nr_ports + 31) / 32; i++) {
598         qemu_put_be32s(f, &s->ports_map[i]);
599     }
600
601     /* Ports */
602
603     nr_active_ports = 0;
604     QTAILQ_FOREACH(port, &s->ports, next) {
605         nr_active_ports++;
606     }
607
608     qemu_put_be32s(f, &nr_active_ports);
609
610     /*
611      * Items in struct VirtIOSerialPort.
612      */
613     QTAILQ_FOREACH(port, &s->ports, next) {
614         uint32_t elem_popped;
615
616         qemu_put_be32s(f, &port->id);
617         qemu_put_byte(f, port->guest_connected);
618         qemu_put_byte(f, port->host_connected);
619
620         elem_popped = 0;
621         if (port->elem.out_num) {
622             elem_popped = 1;
623         }
624         qemu_put_be32s(f, &elem_popped);
625         if (elem_popped) {
626             qemu_put_be32s(f, &port->iov_idx);
627             qemu_put_be64s(f, &port->iov_offset);
628
629             qemu_put_buffer(f, (unsigned char *)&port->elem,
630                             sizeof(port->elem));
631         }
632     }
633 }
634
635 static int virtio_serial_load(QEMUFile *f, void *opaque, int version_id)
636 {
637     VirtIOSerial *s = opaque;
638     VirtIOSerialPort *port;
639     uint32_t max_nr_ports, nr_active_ports, ports_map;
640     unsigned int i;
641     int ret;
642
643     if (version_id > 3) {
644         return -EINVAL;
645     }
646
647     /* The virtio device */
648     ret = virtio_load(&s->vdev, f);
649     if (ret) {
650         return ret;
651     }
652
653     if (version_id < 2) {
654         return 0;
655     }
656
657     /* The config space */
658     qemu_get_be16s(f, &s->config.cols);
659     qemu_get_be16s(f, &s->config.rows);
660
661     qemu_get_be32s(f, &max_nr_ports);
662     tswap32s(&max_nr_ports);
663     if (max_nr_ports > tswap32(s->config.max_nr_ports)) {
664         /* Source could have had more ports than us. Fail migration. */
665         return -EINVAL;
666     }
667
668     for (i = 0; i < (max_nr_ports + 31) / 32; i++) {
669         qemu_get_be32s(f, &ports_map);
670
671         if (ports_map != s->ports_map[i]) {
672             /*
673              * Ports active on source and destination don't
674              * match. Fail migration.
675              */
676             return -EINVAL;
677         }
678     }
679
680     qemu_get_be32s(f, &nr_active_ports);
681
682     /* Items in struct VirtIOSerialPort */
683     for (i = 0; i < nr_active_ports; i++) {
684         uint32_t id;
685         bool host_connected;
686
687         id = qemu_get_be32(f);
688         port = find_port_by_id(s, id);
689         if (!port) {
690             return -EINVAL;
691         }
692
693         port->guest_connected = qemu_get_byte(f);
694         host_connected = qemu_get_byte(f);
695         if (host_connected != port->host_connected) {
696             /*
697              * We have to let the guest know of the host connection
698              * status change
699              */
700             send_control_event(port, VIRTIO_CONSOLE_PORT_OPEN,
701                                port->host_connected);
702         }
703
704         if (version_id > 2) {
705             uint32_t elem_popped;
706
707             qemu_get_be32s(f, &elem_popped);
708             if (elem_popped) {
709                 qemu_get_be32s(f, &port->iov_idx);
710                 qemu_get_be64s(f, &port->iov_offset);
711
712                 qemu_get_buffer(f, (unsigned char *)&port->elem,
713                                 sizeof(port->elem));
714                 virtqueue_map_sg(port->elem.in_sg, port->elem.in_addr,
715                                  port->elem.in_num, 1);
716                 virtqueue_map_sg(port->elem.out_sg, port->elem.out_addr,
717                                  port->elem.out_num, 1);
718
719                 /*
720                  *  Port was throttled on source machine.  Let's
721                  *  unthrottle it here so data starts flowing again.
722                  */
723                 virtio_serial_throttle_port(port, false);
724             }
725         }
726     }
727     return 0;
728 }
729
730 static void virtser_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent);
731
732 static Property virtser_props[] = {
733     DEFINE_PROP_UINT32("nr", VirtIOSerialPort, id, VIRTIO_CONSOLE_BAD_ID),
734     DEFINE_PROP_STRING("name", VirtIOSerialPort, name),
735     DEFINE_PROP_END_OF_LIST()
736 };
737
738 #define TYPE_VIRTIO_SERIAL_BUS "virtio-serial-bus"
739 #define VIRTIO_SERIAL_BUS(obj) \
740       OBJECT_CHECK(VirtIOSerialBus, (obj), TYPE_VIRTIO_SERIAL_BUS)
741
742 static void virtser_bus_class_init(ObjectClass *klass, void *data)
743 {
744     BusClass *k = BUS_CLASS(klass);
745     k->print_dev = virtser_bus_dev_print;
746 }
747
748 static const TypeInfo virtser_bus_info = {
749     .name = TYPE_VIRTIO_SERIAL_BUS,
750     .parent = TYPE_BUS,
751     .instance_size = sizeof(VirtIOSerialBus),
752     .class_init = virtser_bus_class_init,
753 };
754
755 static void virtser_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent)
756 {
757     VirtIOSerialPort *port = DO_UPCAST(VirtIOSerialPort, dev, qdev);
758
759     monitor_printf(mon, "%*sport %d, guest %s, host %s, throttle %s\n",
760                    indent, "", port->id,
761                    port->guest_connected ? "on" : "off",
762                    port->host_connected ? "on" : "off",
763                    port->throttled ? "on" : "off");
764 }
765
766 /* This function is only used if a port id is not provided by the user */
767 static uint32_t find_free_port_id(VirtIOSerial *vser)
768 {
769     unsigned int i, max_nr_ports;
770
771     max_nr_ports = tswap32(vser->config.max_nr_ports);
772     for (i = 0; i < (max_nr_ports + 31) / 32; i++) {
773         uint32_t map, bit;
774
775         map = vser->ports_map[i];
776         bit = ffs(~map);
777         if (bit) {
778             return (bit - 1) + i * 32;
779         }
780     }
781     return VIRTIO_CONSOLE_BAD_ID;
782 }
783
784 static void mark_port_added(VirtIOSerial *vser, uint32_t port_id)
785 {
786     unsigned int i;
787
788     i = port_id / 32;
789     vser->ports_map[i] |= 1U << (port_id % 32);
790 }
791
792 static void add_port(VirtIOSerial *vser, uint32_t port_id)
793 {
794     mark_port_added(vser, port_id);
795
796     send_control_event(find_port_by_id(vser, port_id),
797                        VIRTIO_CONSOLE_PORT_ADD, 1);
798 }
799
800 static void remove_port(VirtIOSerial *vser, uint32_t port_id)
801 {
802     VirtIOSerialPort *port;
803     unsigned int i;
804
805     i = port_id / 32;
806     vser->ports_map[i] &= ~(1U << (port_id % 32));
807
808     port = find_port_by_id(vser, port_id);
809     /* Flush out any unconsumed buffers first */
810     discard_vq_data(port->ovq, &port->vser->vdev);
811
812     send_control_event(port, VIRTIO_CONSOLE_PORT_REMOVE, 1);
813 }
814
815 static int virtser_port_qdev_init(DeviceState *qdev)
816 {
817     VirtIOSerialPort *port = DO_UPCAST(VirtIOSerialPort, dev, qdev);
818     VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
819     VirtIOSerialBus *bus = DO_UPCAST(VirtIOSerialBus, qbus, qdev->parent_bus);
820     int ret, max_nr_ports;
821     bool plugging_port0;
822
823     port->vser = bus->vser;
824     port->bh = qemu_bh_new(flush_queued_data_bh, port);
825
826     assert(vsc->have_data);
827
828     /*
829      * Is the first console port we're seeing? If so, put it up at
830      * location 0. This is done for backward compatibility (old
831      * kernel, new qemu).
832      */
833     plugging_port0 = vsc->is_console && !find_port_by_id(port->vser, 0);
834
835     if (find_port_by_id(port->vser, port->id)) {
836         error_report("virtio-serial-bus: A port already exists at id %u",
837                      port->id);
838         return -1;
839     }
840
841     if (port->id == VIRTIO_CONSOLE_BAD_ID) {
842         if (plugging_port0) {
843             port->id = 0;
844         } else {
845             port->id = find_free_port_id(port->vser);
846             if (port->id == VIRTIO_CONSOLE_BAD_ID) {
847                 error_report("virtio-serial-bus: Maximum port limit for this device reached");
848                 return -1;
849             }
850         }
851     }
852
853     max_nr_ports = tswap32(port->vser->config.max_nr_ports);
854     if (port->id >= max_nr_ports) {
855         error_report("virtio-serial-bus: Out-of-range port id specified, max. allowed: %u",
856                      max_nr_ports - 1);
857         return -1;
858     }
859
860     ret = vsc->init(port);
861     if (ret) {
862         return ret;
863     }
864
865     port->elem.out_num = 0;
866
867     QTAILQ_INSERT_TAIL(&port->vser->ports, port, next);
868     port->ivq = port->vser->ivqs[port->id];
869     port->ovq = port->vser->ovqs[port->id];
870
871     add_port(port->vser, port->id);
872
873     /* Send an update to the guest about this new port added */
874     virtio_notify_config(&port->vser->vdev);
875
876     return ret;
877 }
878
879 static int virtser_port_qdev_exit(DeviceState *qdev)
880 {
881     VirtIOSerialPort *port = DO_UPCAST(VirtIOSerialPort, dev, qdev);
882     VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
883     VirtIOSerial *vser = port->vser;
884
885     qemu_bh_delete(port->bh);
886     remove_port(port->vser, port->id);
887
888     QTAILQ_REMOVE(&vser->ports, port, next);
889
890     if (vsc->exit) {
891         vsc->exit(port);
892     }
893     return 0;
894 }
895
896 VirtIODevice *virtio_serial_init(DeviceState *dev, virtio_serial_conf *conf)
897 {
898     VirtIOSerial *vser;
899     VirtIODevice *vdev;
900     uint32_t i, max_supported_ports;
901
902     if (!conf->max_virtserial_ports)
903         return NULL;
904
905     /* Each port takes 2 queues, and one pair is for the control queue */
906     max_supported_ports = VIRTIO_PCI_QUEUE_MAX / 2 - 1;
907
908     if (conf->max_virtserial_ports > max_supported_ports) {
909         error_report("maximum ports supported: %u", max_supported_ports);
910         return NULL;
911     }
912
913     vdev = virtio_common_init("virtio-serial", VIRTIO_ID_CONSOLE,
914                               sizeof(struct virtio_console_config),
915                               sizeof(VirtIOSerial));
916
917     vser = DO_UPCAST(VirtIOSerial, vdev, vdev);
918
919     /* Spawn a new virtio-serial bus on which the ports will ride as devices */
920     qbus_create_inplace(&vser->bus.qbus, TYPE_VIRTIO_SERIAL_BUS, dev, NULL);
921     vser->bus.qbus.allow_hotplug = 1;
922     vser->bus.vser = vser;
923     QTAILQ_INIT(&vser->ports);
924
925     vser->bus.max_nr_ports = conf->max_virtserial_ports;
926     vser->ivqs = g_malloc(conf->max_virtserial_ports * sizeof(VirtQueue *));
927     vser->ovqs = g_malloc(conf->max_virtserial_ports * sizeof(VirtQueue *));
928
929     /* Add a queue for host to guest transfers for port 0 (backward compat) */
930     vser->ivqs[0] = virtio_add_queue(vdev, 128, handle_input);
931     /* Add a queue for guest to host transfers for port 0 (backward compat) */
932     vser->ovqs[0] = virtio_add_queue(vdev, 128, handle_output);
933
934     /* TODO: host to guest notifications can get dropped
935      * if the queue fills up. Implement queueing in host,
936      * this might also make it possible to reduce the control
937      * queue size: as guest preposts buffers there,
938      * this will save 4Kbyte of guest memory per entry. */
939
940     /* control queue: host to guest */
941     vser->c_ivq = virtio_add_queue(vdev, 32, control_in);
942     /* control queue: guest to host */
943     vser->c_ovq = virtio_add_queue(vdev, 32, control_out);
944
945     for (i = 1; i < vser->bus.max_nr_ports; i++) {
946         /* Add a per-port queue for host to guest transfers */
947         vser->ivqs[i] = virtio_add_queue(vdev, 128, handle_input);
948         /* Add a per-per queue for guest to host transfers */
949         vser->ovqs[i] = virtio_add_queue(vdev, 128, handle_output);
950     }
951
952     vser->config.max_nr_ports = tswap32(conf->max_virtserial_ports);
953     vser->ports_map = g_malloc0(((conf->max_virtserial_ports + 31) / 32)
954         * sizeof(vser->ports_map[0]));
955     /*
956      * Reserve location 0 for a console port for backward compat
957      * (old kernel, new qemu)
958      */
959     mark_port_added(vser, 0);
960
961     vser->vdev.get_features = get_features;
962     vser->vdev.get_config = get_config;
963     vser->vdev.set_config = set_config;
964     vser->vdev.set_status = set_status;
965     vser->vdev.reset = vser_reset;
966
967     vser->qdev = dev;
968
969     /*
970      * Register for the savevm section with the virtio-console name
971      * to preserve backward compat
972      */
973     register_savevm(dev, "virtio-console", -1, 3, virtio_serial_save,
974                     virtio_serial_load, vser);
975
976     return vdev;
977 }
978
979 void virtio_serial_exit(VirtIODevice *vdev)
980 {
981     VirtIOSerial *vser = DO_UPCAST(VirtIOSerial, vdev, vdev);
982
983     unregister_savevm(vser->qdev, "virtio-console", vser);
984
985     g_free(vser->ivqs);
986     g_free(vser->ovqs);
987     g_free(vser->ports_map);
988
989     virtio_cleanup(vdev);
990 }
991
992 static void virtio_serial_port_class_init(ObjectClass *klass, void *data)
993 {
994     DeviceClass *k = DEVICE_CLASS(klass);
995     k->init = virtser_port_qdev_init;
996     k->bus_type = TYPE_VIRTIO_SERIAL_BUS;
997     k->exit = virtser_port_qdev_exit;
998     k->unplug = qdev_simple_unplug_cb;
999     k->props = virtser_props;
1000 }
1001
1002 static TypeInfo virtio_serial_port_type_info = {
1003     .name = TYPE_VIRTIO_SERIAL_PORT,
1004     .parent = TYPE_DEVICE,
1005     .instance_size = sizeof(VirtIOSerialPort),
1006     .abstract = true,
1007     .class_size = sizeof(VirtIOSerialPortClass),
1008     .class_init = virtio_serial_port_class_init,
1009 };
1010
1011 static void virtio_serial_register_types(void)
1012 {
1013     type_register_static(&virtser_bus_info);
1014     type_register_static(&virtio_serial_port_type_info);
1015 }
1016
1017 type_init(virtio_serial_register_types)
1018
1019 /******************** VirtIOSer Device **********************/
1020
1021 static int virtio_serialdev_init(DeviceState *dev)
1022 {
1023     VirtIODevice *vdev;
1024     VirtIOSerState *s = VIRTIO_SERIAL_FROM_QDEV(dev);
1025     vdev = virtio_serial_init(dev, &s->serial);
1026     if (!vdev) {
1027         return -1;
1028     }
1029
1030     assert(s->trl != NULL);
1031
1032     return virtio_call_backend_init_cb(dev, s->trl, vdev);
1033 }
1034
1035 static Property virtio_serial_properties[] = {
1036     DEFINE_PROP_UINT32("max_ports", VirtIOSerState,
1037                        serial.max_virtserial_ports, 31),
1038     DEFINE_PROP_END_OF_LIST(),
1039 };
1040
1041 static void virtio_serial_class_init(ObjectClass *klass, void *data)
1042 {
1043     DeviceClass *dc = DEVICE_CLASS(klass);
1044     dc->init = virtio_serialdev_init;
1045     dc->props = virtio_serial_properties;
1046 }
1047
1048 static TypeInfo virtio_serial_info = {
1049     .name = "virtio-serial",
1050     .parent = TYPE_DEVICE,
1051     .instance_size = sizeof(VirtIOSerState),
1052     .class_init = virtio_serial_class_init,
1053 };
1054
1055 static void virtio_ser_register_types(void)
1056 {
1057     type_register_static(&virtio_serial_info);
1058 }
1059
1060 type_init(virtio_ser_register_types)