xref: /openbmc/qemu/hw/char/virtio-serial-bus.c (revision 500eb6db)
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 "qemu/osdep.h"
22 #include "qapi/error.h"
23 #include "qemu/iov.h"
24 #include "qemu/module.h"
25 #include "monitor/monitor.h"
26 #include "qemu/error-report.h"
27 #include "qemu/queue.h"
28 #include "hw/sysbus.h"
29 #include "trace.h"
30 #include "hw/virtio/virtio-serial.h"
31 #include "hw/virtio/virtio-access.h"
32 
33 static struct VirtIOSerialDevices {
34     QLIST_HEAD(, VirtIOSerial) devices;
35 } vserdevices;
36 
37 static VirtIOSerialPort *find_port_by_id(VirtIOSerial *vser, uint32_t id)
38 {
39     VirtIOSerialPort *port;
40 
41     if (id == VIRTIO_CONSOLE_BAD_ID) {
42         return NULL;
43     }
44 
45     QTAILQ_FOREACH(port, &vser->ports, next) {
46         if (port->id == id)
47             return port;
48     }
49     return NULL;
50 }
51 
52 static VirtIOSerialPort *find_port_by_vq(VirtIOSerial *vser, VirtQueue *vq)
53 {
54     VirtIOSerialPort *port;
55 
56     QTAILQ_FOREACH(port, &vser->ports, next) {
57         if (port->ivq == vq || port->ovq == vq)
58             return port;
59     }
60     return NULL;
61 }
62 
63 static VirtIOSerialPort *find_port_by_name(char *name)
64 {
65     VirtIOSerial *vser;
66 
67     QLIST_FOREACH(vser, &vserdevices.devices, next) {
68         VirtIOSerialPort *port;
69 
70         QTAILQ_FOREACH(port, &vser->ports, next) {
71             if (port->name && !strcmp(port->name, name)) {
72                 return port;
73             }
74         }
75     }
76     return NULL;
77 }
78 
79 static VirtIOSerialPort *find_first_connected_console(VirtIOSerial *vser)
80 {
81     VirtIOSerialPort *port;
82 
83     QTAILQ_FOREACH(port, &vser->ports, next) {
84         VirtIOSerialPortClass const *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
85         if (vsc->is_console && port->host_connected) {
86             return port;
87         }
88     }
89     return NULL;
90 }
91 
92 static bool use_multiport(VirtIOSerial *vser)
93 {
94     VirtIODevice *vdev = VIRTIO_DEVICE(vser);
95     return virtio_vdev_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT);
96 }
97 
98 static size_t write_to_port(VirtIOSerialPort *port,
99                             const uint8_t *buf, size_t size)
100 {
101     VirtQueueElement *elem;
102     VirtQueue *vq;
103     size_t offset;
104 
105     vq = port->ivq;
106     if (!virtio_queue_ready(vq)) {
107         return 0;
108     }
109 
110     offset = 0;
111     while (offset < size) {
112         size_t len;
113 
114         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
115         if (!elem) {
116             break;
117         }
118 
119         len = iov_from_buf(elem->in_sg, elem->in_num, 0,
120                            buf + offset, size - offset);
121         offset += len;
122 
123         virtqueue_push(vq, elem, len);
124         g_free(elem);
125     }
126 
127     virtio_notify(VIRTIO_DEVICE(port->vser), vq);
128     return offset;
129 }
130 
131 static void discard_vq_data(VirtQueue *vq, VirtIODevice *vdev)
132 {
133     VirtQueueElement *elem;
134 
135     if (!virtio_queue_ready(vq)) {
136         return;
137     }
138     for (;;) {
139         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
140         if (!elem) {
141             break;
142         }
143         virtqueue_push(vq, elem, 0);
144         g_free(elem);
145     }
146     virtio_notify(vdev, vq);
147 }
148 
149 static void discard_throttle_data(VirtIOSerialPort *port)
150 {
151     if (port->elem) {
152         virtqueue_detach_element(port->ovq, port->elem, 0);
153         g_free(port->elem);
154         port->elem = NULL;
155     }
156 }
157 
158 static void do_flush_queued_data(VirtIOSerialPort *port, VirtQueue *vq,
159                                  VirtIODevice *vdev)
160 {
161     VirtIOSerialPortClass *vsc;
162 
163     assert(port);
164     assert(virtio_queue_ready(vq));
165 
166     vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
167 
168     while (!port->throttled) {
169         unsigned int i;
170 
171         /* Pop an elem only if we haven't left off a previous one mid-way */
172         if (!port->elem) {
173             port->elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
174             if (!port->elem) {
175                 break;
176             }
177             port->iov_idx = 0;
178             port->iov_offset = 0;
179         }
180 
181         for (i = port->iov_idx; i < port->elem->out_num; i++) {
182             size_t buf_size;
183             ssize_t ret;
184 
185             buf_size = port->elem->out_sg[i].iov_len - port->iov_offset;
186             ret = vsc->have_data(port,
187                                   port->elem->out_sg[i].iov_base
188                                   + port->iov_offset,
189                                   buf_size);
190             if (!port->elem) { /* bail if we got disconnected */
191                 return;
192             }
193             if (port->throttled) {
194                 port->iov_idx = i;
195                 if (ret > 0) {
196                     port->iov_offset += ret;
197                 }
198                 break;
199             }
200             port->iov_offset = 0;
201         }
202         if (port->throttled) {
203             break;
204         }
205         virtqueue_push(vq, port->elem, 0);
206         g_free(port->elem);
207         port->elem = NULL;
208     }
209     virtio_notify(vdev, vq);
210 }
211 
212 static void flush_queued_data(VirtIOSerialPort *port)
213 {
214     assert(port);
215 
216     if (!virtio_queue_ready(port->ovq)) {
217         return;
218     }
219     do_flush_queued_data(port, port->ovq, VIRTIO_DEVICE(port->vser));
220 }
221 
222 static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len)
223 {
224     VirtQueueElement *elem;
225     VirtQueue *vq;
226 
227     vq = vser->c_ivq;
228     if (!virtio_queue_ready(vq)) {
229         return 0;
230     }
231 
232     elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
233     if (!elem) {
234         return 0;
235     }
236 
237     /* TODO: detect a buffer that's too short, set NEEDS_RESET */
238     iov_from_buf(elem->in_sg, elem->in_num, 0, buf, len);
239 
240     virtqueue_push(vq, elem, len);
241     virtio_notify(VIRTIO_DEVICE(vser), vq);
242     g_free(elem);
243 
244     return len;
245 }
246 
247 static size_t send_control_event(VirtIOSerial *vser, uint32_t port_id,
248                                  uint16_t event, uint16_t value)
249 {
250     VirtIODevice *vdev = VIRTIO_DEVICE(vser);
251     struct virtio_console_control cpkt;
252 
253     virtio_stl_p(vdev, &cpkt.id, port_id);
254     virtio_stw_p(vdev, &cpkt.event, event);
255     virtio_stw_p(vdev, &cpkt.value, value);
256 
257     trace_virtio_serial_send_control_event(port_id, event, value);
258     return send_control_msg(vser, &cpkt, sizeof(cpkt));
259 }
260 
261 /* Functions for use inside qemu to open and read from/write to ports */
262 int virtio_serial_open(VirtIOSerialPort *port)
263 {
264     /* Don't allow opening an already-open port */
265     if (port->host_connected) {
266         return 0;
267     }
268     /* Send port open notification to the guest */
269     port->host_connected = true;
270     send_control_event(port->vser, port->id, VIRTIO_CONSOLE_PORT_OPEN, 1);
271 
272     return 0;
273 }
274 
275 int virtio_serial_close(VirtIOSerialPort *port)
276 {
277     port->host_connected = false;
278     /*
279      * If there's any data the guest sent which the app didn't
280      * consume, reset the throttling flag and discard the data.
281      */
282     port->throttled = false;
283     discard_throttle_data(port);
284     discard_vq_data(port->ovq, VIRTIO_DEVICE(port->vser));
285 
286     send_control_event(port->vser, port->id, VIRTIO_CONSOLE_PORT_OPEN, 0);
287 
288     return 0;
289 }
290 
291 /* Individual ports/apps call this function to write to the guest. */
292 ssize_t virtio_serial_write(VirtIOSerialPort *port, const uint8_t *buf,
293                             size_t size)
294 {
295     if (!port || !port->host_connected || !port->guest_connected) {
296         return 0;
297     }
298     return write_to_port(port, buf, size);
299 }
300 
301 /*
302  * Readiness of the guest to accept data on a port.
303  * Returns max. data the guest can receive
304  */
305 size_t virtio_serial_guest_ready(VirtIOSerialPort *port)
306 {
307     VirtIODevice *vdev = VIRTIO_DEVICE(port->vser);
308     VirtQueue *vq = port->ivq;
309     unsigned int bytes;
310 
311     if (!virtio_queue_ready(vq) ||
312         !(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK) ||
313         virtio_queue_empty(vq)) {
314         return 0;
315     }
316     if (use_multiport(port->vser) && !port->guest_connected) {
317         return 0;
318     }
319     virtqueue_get_avail_bytes(vq, &bytes, NULL, 4096, 0);
320     return bytes;
321 }
322 
323 static void flush_queued_data_bh(void *opaque)
324 {
325     VirtIOSerialPort *port = opaque;
326 
327     flush_queued_data(port);
328 }
329 
330 void virtio_serial_throttle_port(VirtIOSerialPort *port, bool throttle)
331 {
332     if (!port) {
333         return;
334     }
335 
336     trace_virtio_serial_throttle_port(port->id, throttle);
337     port->throttled = throttle;
338     if (throttle) {
339         return;
340     }
341     qemu_bh_schedule(port->bh);
342 }
343 
344 /* Guest wants to notify us of some event */
345 static void handle_control_message(VirtIOSerial *vser, void *buf, size_t len)
346 {
347     VirtIODevice *vdev = VIRTIO_DEVICE(vser);
348     struct VirtIOSerialPort *port;
349     VirtIOSerialPortClass *vsc;
350     struct virtio_console_control cpkt, *gcpkt;
351     uint8_t *buffer;
352     size_t buffer_len;
353 
354     gcpkt = buf;
355 
356     if (len < sizeof(cpkt)) {
357         /* The guest sent an invalid control packet */
358         return;
359     }
360 
361     cpkt.event = virtio_lduw_p(vdev, &gcpkt->event);
362     cpkt.value = virtio_lduw_p(vdev, &gcpkt->value);
363 
364     trace_virtio_serial_handle_control_message(cpkt.event, cpkt.value);
365 
366     if (cpkt.event == VIRTIO_CONSOLE_DEVICE_READY) {
367         if (!cpkt.value) {
368             error_report("virtio-serial-bus: Guest failure in adding device %s",
369                          vser->bus.qbus.name);
370             return;
371         }
372         /*
373          * The device is up, we can now tell the device about all the
374          * ports we have here.
375          */
376         QTAILQ_FOREACH(port, &vser->ports, next) {
377             send_control_event(vser, port->id, VIRTIO_CONSOLE_PORT_ADD, 1);
378         }
379         return;
380     }
381 
382     port = find_port_by_id(vser, virtio_ldl_p(vdev, &gcpkt->id));
383     if (!port) {
384         error_report("virtio-serial-bus: Unexpected port id %u for device %s",
385                      virtio_ldl_p(vdev, &gcpkt->id), vser->bus.qbus.name);
386         return;
387     }
388 
389     trace_virtio_serial_handle_control_message_port(port->id);
390 
391     vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
392 
393     switch(cpkt.event) {
394     case VIRTIO_CONSOLE_PORT_READY:
395         if (!cpkt.value) {
396             error_report("virtio-serial-bus: Guest failure in adding port %u for device %s",
397                          port->id, vser->bus.qbus.name);
398             break;
399         }
400         /*
401          * Now that we know the guest asked for the port name, we're
402          * sure the guest has initialised whatever state is necessary
403          * for this port. Now's a good time to let the guest know if
404          * this port is a console port so that the guest can hook it
405          * up to hvc.
406          */
407         if (vsc->is_console) {
408             send_control_event(vser, port->id, VIRTIO_CONSOLE_CONSOLE_PORT, 1);
409         }
410 
411         if (port->name) {
412             virtio_stl_p(vdev, &cpkt.id, port->id);
413             virtio_stw_p(vdev, &cpkt.event, VIRTIO_CONSOLE_PORT_NAME);
414             virtio_stw_p(vdev, &cpkt.value, 1);
415 
416             buffer_len = sizeof(cpkt) + strlen(port->name) + 1;
417             buffer = g_malloc(buffer_len);
418 
419             memcpy(buffer, &cpkt, sizeof(cpkt));
420             memcpy(buffer + sizeof(cpkt), port->name, strlen(port->name));
421             buffer[buffer_len - 1] = 0;
422 
423             send_control_msg(vser, buffer, buffer_len);
424             g_free(buffer);
425         }
426 
427         if (port->host_connected) {
428             send_control_event(vser, port->id, VIRTIO_CONSOLE_PORT_OPEN, 1);
429         }
430 
431         /*
432          * When the guest has asked us for this information it means
433          * the guest is all setup and has its virtqueues
434          * initialised. If some app is interested in knowing about
435          * this event, let it know.
436          */
437         if (vsc->guest_ready) {
438             vsc->guest_ready(port);
439         }
440         break;
441 
442     case VIRTIO_CONSOLE_PORT_OPEN:
443         port->guest_connected = cpkt.value;
444         if (vsc->set_guest_connected) {
445             /* Send the guest opened notification if an app is interested */
446             vsc->set_guest_connected(port, cpkt.value);
447         }
448         break;
449     }
450 }
451 
452 static void control_in(VirtIODevice *vdev, VirtQueue *vq)
453 {
454 }
455 
456 static void control_out(VirtIODevice *vdev, VirtQueue *vq)
457 {
458     VirtQueueElement *elem;
459     VirtIOSerial *vser;
460     uint8_t *buf;
461     size_t len;
462 
463     vser = VIRTIO_SERIAL(vdev);
464 
465     len = 0;
466     buf = NULL;
467     for (;;) {
468         size_t cur_len;
469 
470         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
471         if (!elem) {
472             break;
473         }
474 
475         cur_len = iov_size(elem->out_sg, elem->out_num);
476         /*
477          * Allocate a new buf only if we didn't have one previously or
478          * if the size of the buf differs
479          */
480         if (cur_len > len) {
481             g_free(buf);
482 
483             buf = g_malloc(cur_len);
484             len = cur_len;
485         }
486         iov_to_buf(elem->out_sg, elem->out_num, 0, buf, cur_len);
487 
488         handle_control_message(vser, buf, cur_len);
489         virtqueue_push(vq, elem, 0);
490         g_free(elem);
491     }
492     g_free(buf);
493     virtio_notify(vdev, vq);
494 }
495 
496 /* Guest wrote something to some port. */
497 static void handle_output(VirtIODevice *vdev, VirtQueue *vq)
498 {
499     VirtIOSerial *vser;
500     VirtIOSerialPort *port;
501 
502     vser = VIRTIO_SERIAL(vdev);
503     port = find_port_by_vq(vser, vq);
504 
505     if (!port || !port->host_connected) {
506         discard_vq_data(vq, vdev);
507         return;
508     }
509 
510     if (!port->throttled) {
511         do_flush_queued_data(port, vq, vdev);
512         return;
513     }
514 }
515 
516 static void handle_input(VirtIODevice *vdev, VirtQueue *vq)
517 {
518     /*
519      * Users of virtio-serial would like to know when guest becomes
520      * writable again -- i.e. if a vq had stuff queued up and the
521      * guest wasn't reading at all, the host would not be able to
522      * write to the vq anymore.  Once the guest reads off something,
523      * we can start queueing things up again.  However, this call is
524      * made for each buffer addition by the guest -- even though free
525      * buffers existed prior to the current buffer addition.  This is
526      * done so as not to maintain previous state, which will need
527      * additional live-migration-related changes.
528      */
529     VirtIOSerial *vser;
530     VirtIOSerialPort *port;
531     VirtIOSerialPortClass *vsc;
532 
533     vser = VIRTIO_SERIAL(vdev);
534     port = find_port_by_vq(vser, vq);
535 
536     if (!port) {
537         return;
538     }
539     vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
540 
541     /*
542      * If guest_connected is false, this call is being made by the
543      * early-boot queueing up of descriptors, which is just noise for
544      * the host apps -- don't disturb them in that case.
545      */
546     if (port->guest_connected && port->host_connected && vsc->guest_writable) {
547         vsc->guest_writable(port);
548     }
549 }
550 
551 static uint64_t get_features(VirtIODevice *vdev, uint64_t features,
552                              Error **errp)
553 {
554     VirtIOSerial *vser;
555 
556     vser = VIRTIO_SERIAL(vdev);
557 
558     features |= vser->host_features;
559     if (vser->bus.max_nr_ports > 1) {
560         virtio_add_feature(&features, VIRTIO_CONSOLE_F_MULTIPORT);
561     }
562     return features;
563 }
564 
565 /* Guest requested config info */
566 static void get_config(VirtIODevice *vdev, uint8_t *config_data)
567 {
568     VirtIOSerial *vser = VIRTIO_SERIAL(vdev);
569     struct virtio_console_config *config =
570         (struct virtio_console_config *)config_data;
571 
572     config->cols = 0;
573     config->rows = 0;
574     config->max_nr_ports = virtio_tswap32(vdev,
575                                           vser->serial.max_virtserial_ports);
576 }
577 
578 /* Guest sent new config info */
579 static void set_config(VirtIODevice *vdev, const uint8_t *config_data)
580 {
581     VirtIOSerial *vser = VIRTIO_SERIAL(vdev);
582     struct virtio_console_config *config =
583         (struct virtio_console_config *)config_data;
584     VirtIOSerialPort *port = find_first_connected_console(vser);
585     VirtIOSerialPortClass *vsc;
586     uint8_t emerg_wr_lo;
587 
588     if (!virtio_has_feature(vser->host_features,
589         VIRTIO_CONSOLE_F_EMERG_WRITE) || !config->emerg_wr) {
590         return;
591     }
592 
593     emerg_wr_lo = le32_to_cpu(config->emerg_wr);
594     /* Make sure we don't misdetect an emergency write when the guest
595      * does a short config write after an emergency write. */
596     config->emerg_wr = 0;
597     if (!port) {
598         return;
599     }
600     vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
601     (void)vsc->have_data(port, &emerg_wr_lo, 1);
602 }
603 
604 static void guest_reset(VirtIOSerial *vser)
605 {
606     VirtIOSerialPort *port;
607     VirtIOSerialPortClass *vsc;
608 
609     QTAILQ_FOREACH(port, &vser->ports, next) {
610         vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
611 
612         discard_throttle_data(port);
613 
614         if (port->guest_connected) {
615             port->guest_connected = false;
616             if (vsc->set_guest_connected) {
617                 vsc->set_guest_connected(port, false);
618             }
619         }
620     }
621 }
622 
623 static void set_status(VirtIODevice *vdev, uint8_t status)
624 {
625     VirtIOSerial *vser;
626     VirtIOSerialPort *port;
627 
628     vser = VIRTIO_SERIAL(vdev);
629     port = find_port_by_id(vser, 0);
630 
631     if (port && !use_multiport(port->vser)
632         && (status & VIRTIO_CONFIG_S_DRIVER_OK)) {
633         /*
634          * Non-multiport guests won't be able to tell us guest
635          * open/close status.  Such guests can only have a port at id
636          * 0, so set guest_connected for such ports as soon as guest
637          * is up.
638          */
639         port->guest_connected = true;
640     }
641     if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
642         guest_reset(vser);
643     }
644 
645     QTAILQ_FOREACH(port, &vser->ports, next) {
646         VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
647         if (vsc->enable_backend) {
648             vsc->enable_backend(port, vdev->vm_running);
649         }
650     }
651 }
652 
653 static void vser_reset(VirtIODevice *vdev)
654 {
655     VirtIOSerial *vser;
656 
657     vser = VIRTIO_SERIAL(vdev);
658     guest_reset(vser);
659 }
660 
661 static void virtio_serial_save_device(VirtIODevice *vdev, QEMUFile *f)
662 {
663     VirtIOSerial *s = VIRTIO_SERIAL(vdev);
664     VirtIOSerialPort *port;
665     uint32_t nr_active_ports;
666     unsigned int i, max_nr_ports;
667     struct virtio_console_config config;
668 
669     /* The config space (ignored on the far end in current versions) */
670     get_config(vdev, (uint8_t *)&config);
671     qemu_put_be16(f, config.cols);
672     qemu_put_be16(f, config.rows);
673     qemu_put_be32(f, config.max_nr_ports);
674 
675     /* The ports map */
676     max_nr_ports = s->serial.max_virtserial_ports;
677     for (i = 0; i < DIV_ROUND_UP(max_nr_ports, 32); i++) {
678         qemu_put_be32s(f, &s->ports_map[i]);
679     }
680 
681     /* Ports */
682 
683     nr_active_ports = 0;
684     QTAILQ_FOREACH(port, &s->ports, next) {
685         nr_active_ports++;
686     }
687 
688     qemu_put_be32s(f, &nr_active_ports);
689 
690     /*
691      * Items in struct VirtIOSerialPort.
692      */
693     QTAILQ_FOREACH(port, &s->ports, next) {
694         uint32_t elem_popped;
695 
696         qemu_put_be32s(f, &port->id);
697         qemu_put_byte(f, port->guest_connected);
698         qemu_put_byte(f, port->host_connected);
699 
700         elem_popped = 0;
701         if (port->elem) {
702             elem_popped = 1;
703         }
704         qemu_put_be32s(f, &elem_popped);
705         if (elem_popped) {
706             qemu_put_be32s(f, &port->iov_idx);
707             qemu_put_be64s(f, &port->iov_offset);
708             qemu_put_virtqueue_element(f, port->elem);
709         }
710     }
711 }
712 
713 static void virtio_serial_post_load_timer_cb(void *opaque)
714 {
715     uint32_t i;
716     VirtIOSerial *s = VIRTIO_SERIAL(opaque);
717     VirtIOSerialPort *port;
718     uint8_t host_connected;
719     VirtIOSerialPortClass *vsc;
720 
721     if (!s->post_load) {
722         return;
723     }
724     for (i = 0 ; i < s->post_load->nr_active_ports; ++i) {
725         port = s->post_load->connected[i].port;
726         host_connected = s->post_load->connected[i].host_connected;
727         if (host_connected != port->host_connected) {
728             /*
729              * We have to let the guest know of the host connection
730              * status change
731              */
732             send_control_event(s, port->id, VIRTIO_CONSOLE_PORT_OPEN,
733                                port->host_connected);
734         }
735         vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
736         if (vsc->set_guest_connected) {
737             vsc->set_guest_connected(port, port->guest_connected);
738         }
739     }
740     g_free(s->post_load->connected);
741     timer_del(s->post_load->timer);
742     timer_free(s->post_load->timer);
743     g_free(s->post_load);
744     s->post_load = NULL;
745 }
746 
747 static int fetch_active_ports_list(QEMUFile *f,
748                                    VirtIOSerial *s, uint32_t nr_active_ports)
749 {
750     VirtIODevice *vdev = VIRTIO_DEVICE(s);
751     uint32_t i;
752 
753     s->post_load = g_malloc0(sizeof(*s->post_load));
754     s->post_load->nr_active_ports = nr_active_ports;
755     s->post_load->connected =
756         g_malloc0(sizeof(*s->post_load->connected) * nr_active_ports);
757 
758     s->post_load->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
759                                             virtio_serial_post_load_timer_cb,
760                                             s);
761 
762     /* Items in struct VirtIOSerialPort */
763     for (i = 0; i < nr_active_ports; i++) {
764         VirtIOSerialPort *port;
765         uint32_t elem_popped;
766         uint32_t id;
767 
768         id = qemu_get_be32(f);
769         port = find_port_by_id(s, id);
770         if (!port) {
771             return -EINVAL;
772         }
773 
774         port->guest_connected = qemu_get_byte(f);
775         s->post_load->connected[i].port = port;
776         s->post_load->connected[i].host_connected = qemu_get_byte(f);
777 
778         qemu_get_be32s(f, &elem_popped);
779         if (elem_popped) {
780             qemu_get_be32s(f, &port->iov_idx);
781             qemu_get_be64s(f, &port->iov_offset);
782 
783             port->elem =
784                 qemu_get_virtqueue_element(vdev, f, sizeof(VirtQueueElement));
785 
786             /*
787              *  Port was throttled on source machine.  Let's
788              *  unthrottle it here so data starts flowing again.
789              */
790             virtio_serial_throttle_port(port, false);
791         }
792     }
793     timer_mod(s->post_load->timer, 1);
794     return 0;
795 }
796 
797 static int virtio_serial_load_device(VirtIODevice *vdev, QEMUFile *f,
798                                      int version_id)
799 {
800     VirtIOSerial *s = VIRTIO_SERIAL(vdev);
801     uint32_t max_nr_ports, nr_active_ports, ports_map;
802     unsigned int i;
803     int ret;
804     uint32_t tmp;
805 
806     /* Unused */
807     qemu_get_be16s(f, (uint16_t *) &tmp);
808     qemu_get_be16s(f, (uint16_t *) &tmp);
809     qemu_get_be32s(f, &tmp);
810 
811     max_nr_ports = s->serial.max_virtserial_ports;
812     for (i = 0; i < DIV_ROUND_UP(max_nr_ports, 32); i++) {
813         qemu_get_be32s(f, &ports_map);
814 
815         if (ports_map != s->ports_map[i]) {
816             /*
817              * Ports active on source and destination don't
818              * match. Fail migration.
819              */
820             return -EINVAL;
821         }
822     }
823 
824     qemu_get_be32s(f, &nr_active_ports);
825 
826     if (nr_active_ports) {
827         ret = fetch_active_ports_list(f, s, nr_active_ports);
828         if (ret) {
829             return ret;
830         }
831     }
832     return 0;
833 }
834 
835 static void virtser_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent);
836 
837 static Property virtser_props[] = {
838     DEFINE_PROP_UINT32("nr", VirtIOSerialPort, id, VIRTIO_CONSOLE_BAD_ID),
839     DEFINE_PROP_STRING("name", VirtIOSerialPort, name),
840     DEFINE_PROP_END_OF_LIST()
841 };
842 
843 #define TYPE_VIRTIO_SERIAL_BUS "virtio-serial-bus"
844 #define VIRTIO_SERIAL_BUS(obj) \
845       OBJECT_CHECK(VirtIOSerialBus, (obj), TYPE_VIRTIO_SERIAL_BUS)
846 
847 static void virtser_bus_class_init(ObjectClass *klass, void *data)
848 {
849     BusClass *k = BUS_CLASS(klass);
850     k->print_dev = virtser_bus_dev_print;
851 }
852 
853 static const TypeInfo virtser_bus_info = {
854     .name = TYPE_VIRTIO_SERIAL_BUS,
855     .parent = TYPE_BUS,
856     .instance_size = sizeof(VirtIOSerialBus),
857     .class_init = virtser_bus_class_init,
858 };
859 
860 static void virtser_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent)
861 {
862     VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(qdev);
863 
864     monitor_printf(mon, "%*sport %d, guest %s, host %s, throttle %s\n",
865                    indent, "", port->id,
866                    port->guest_connected ? "on" : "off",
867                    port->host_connected ? "on" : "off",
868                    port->throttled ? "on" : "off");
869 }
870 
871 /* This function is only used if a port id is not provided by the user */
872 static uint32_t find_free_port_id(VirtIOSerial *vser)
873 {
874     unsigned int i, max_nr_ports;
875 
876     max_nr_ports = vser->serial.max_virtserial_ports;
877     for (i = 0; i < DIV_ROUND_UP(max_nr_ports, 32); i++) {
878         uint32_t map, zeroes;
879 
880         map = vser->ports_map[i];
881         zeroes = ctz32(~map);
882         if (zeroes != 32) {
883             return zeroes + i * 32;
884         }
885     }
886     return VIRTIO_CONSOLE_BAD_ID;
887 }
888 
889 static void mark_port_added(VirtIOSerial *vser, uint32_t port_id)
890 {
891     unsigned int i;
892 
893     i = port_id / 32;
894     vser->ports_map[i] |= 1U << (port_id % 32);
895 }
896 
897 static void add_port(VirtIOSerial *vser, uint32_t port_id)
898 {
899     mark_port_added(vser, port_id);
900     send_control_event(vser, port_id, VIRTIO_CONSOLE_PORT_ADD, 1);
901 }
902 
903 static void remove_port(VirtIOSerial *vser, uint32_t port_id)
904 {
905     VirtIOSerialPort *port;
906 
907     /*
908      * Don't mark port 0 removed -- we explicitly reserve it for
909      * backward compat with older guests, ensure a virtconsole device
910      * unplug retains the reservation.
911      */
912     if (port_id) {
913         unsigned int i;
914 
915         i = port_id / 32;
916         vser->ports_map[i] &= ~(1U << (port_id % 32));
917     }
918 
919     port = find_port_by_id(vser, port_id);
920     /*
921      * This function is only called from qdev's unplug callback; if we
922      * get a NULL port here, we're in trouble.
923      */
924     assert(port);
925 
926     /* Flush out any unconsumed buffers first */
927     discard_throttle_data(port);
928     discard_vq_data(port->ovq, VIRTIO_DEVICE(port->vser));
929 
930     send_control_event(vser, port->id, VIRTIO_CONSOLE_PORT_REMOVE, 1);
931 }
932 
933 static void virtser_port_device_realize(DeviceState *dev, Error **errp)
934 {
935     VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev);
936     VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
937     VirtIOSerialBus *bus = VIRTIO_SERIAL_BUS(qdev_get_parent_bus(dev));
938     int max_nr_ports;
939     bool plugging_port0;
940     Error *err = NULL;
941 
942     port->vser = bus->vser;
943     port->bh = qemu_bh_new(flush_queued_data_bh, port);
944 
945     assert(vsc->have_data);
946 
947     /*
948      * Is the first console port we're seeing? If so, put it up at
949      * location 0. This is done for backward compatibility (old
950      * kernel, new qemu).
951      */
952     plugging_port0 = vsc->is_console && !find_port_by_id(port->vser, 0);
953 
954     if (find_port_by_id(port->vser, port->id)) {
955         error_setg(errp, "virtio-serial-bus: A port already exists at id %u",
956                    port->id);
957         return;
958     }
959 
960     if (port->name != NULL && find_port_by_name(port->name)) {
961         error_setg(errp, "virtio-serial-bus: A port already exists by name %s",
962                    port->name);
963         return;
964     }
965 
966     if (port->id == VIRTIO_CONSOLE_BAD_ID) {
967         if (plugging_port0) {
968             port->id = 0;
969         } else {
970             port->id = find_free_port_id(port->vser);
971             if (port->id == VIRTIO_CONSOLE_BAD_ID) {
972                 error_setg(errp, "virtio-serial-bus: Maximum port limit for "
973                                  "this device reached");
974                 return;
975             }
976         }
977     }
978 
979     max_nr_ports = port->vser->serial.max_virtserial_ports;
980     if (port->id >= max_nr_ports) {
981         error_setg(errp, "virtio-serial-bus: Out-of-range port id specified, "
982                          "max. allowed: %u", max_nr_ports - 1);
983         return;
984     }
985 
986     vsc->realize(dev, &err);
987     if (err != NULL) {
988         error_propagate(errp, err);
989         return;
990     }
991 
992     port->elem = NULL;
993 }
994 
995 static void virtser_port_device_plug(HotplugHandler *hotplug_dev,
996                                      DeviceState *dev, Error **errp)
997 {
998     VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev);
999 
1000     QTAILQ_INSERT_TAIL(&port->vser->ports, port, next);
1001     port->ivq = port->vser->ivqs[port->id];
1002     port->ovq = port->vser->ovqs[port->id];
1003 
1004     add_port(port->vser, port->id);
1005 
1006     /* Send an update to the guest about this new port added */
1007     virtio_notify_config(VIRTIO_DEVICE(hotplug_dev));
1008 }
1009 
1010 static void virtser_port_device_unrealize(DeviceState *dev, Error **errp)
1011 {
1012     VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev);
1013     VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(dev);
1014     VirtIOSerial *vser = port->vser;
1015 
1016     qemu_bh_delete(port->bh);
1017     remove_port(port->vser, port->id);
1018 
1019     QTAILQ_REMOVE(&vser->ports, port, next);
1020 
1021     if (vsc->unrealize) {
1022         vsc->unrealize(dev, errp);
1023     }
1024 }
1025 
1026 static void virtio_serial_device_realize(DeviceState *dev, Error **errp)
1027 {
1028     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1029     VirtIOSerial *vser = VIRTIO_SERIAL(dev);
1030     uint32_t i, max_supported_ports;
1031     size_t config_size = sizeof(struct virtio_console_config);
1032 
1033     if (!vser->serial.max_virtserial_ports) {
1034         error_setg(errp, "Maximum number of serial ports not specified");
1035         return;
1036     }
1037 
1038     /* Each port takes 2 queues, and one pair is for the control queue */
1039     max_supported_ports = VIRTIO_QUEUE_MAX / 2 - 1;
1040 
1041     if (vser->serial.max_virtserial_ports > max_supported_ports) {
1042         error_setg(errp, "maximum ports supported: %u", max_supported_ports);
1043         return;
1044     }
1045 
1046     if (!virtio_has_feature(vser->host_features,
1047                             VIRTIO_CONSOLE_F_EMERG_WRITE)) {
1048         config_size = offsetof(struct virtio_console_config, emerg_wr);
1049     }
1050     virtio_init(vdev, "virtio-serial", VIRTIO_ID_CONSOLE,
1051                 config_size);
1052 
1053     /* Spawn a new virtio-serial bus on which the ports will ride as devices */
1054     qbus_create_inplace(&vser->bus, sizeof(vser->bus), TYPE_VIRTIO_SERIAL_BUS,
1055                         dev, vdev->bus_name);
1056     qbus_set_hotplug_handler(BUS(&vser->bus), OBJECT(vser), errp);
1057     vser->bus.vser = vser;
1058     QTAILQ_INIT(&vser->ports);
1059 
1060     vser->bus.max_nr_ports = vser->serial.max_virtserial_ports;
1061     vser->ivqs = g_malloc(vser->serial.max_virtserial_ports
1062                           * sizeof(VirtQueue *));
1063     vser->ovqs = g_malloc(vser->serial.max_virtserial_ports
1064                           * sizeof(VirtQueue *));
1065 
1066     /* Add a queue for host to guest transfers for port 0 (backward compat) */
1067     vser->ivqs[0] = virtio_add_queue(vdev, 128, handle_input);
1068     /* Add a queue for guest to host transfers for port 0 (backward compat) */
1069     vser->ovqs[0] = virtio_add_queue(vdev, 128, handle_output);
1070 
1071     /* TODO: host to guest notifications can get dropped
1072      * if the queue fills up. Implement queueing in host,
1073      * this might also make it possible to reduce the control
1074      * queue size: as guest preposts buffers there,
1075      * this will save 4Kbyte of guest memory per entry. */
1076 
1077     /* control queue: host to guest */
1078     vser->c_ivq = virtio_add_queue(vdev, 32, control_in);
1079     /* control queue: guest to host */
1080     vser->c_ovq = virtio_add_queue(vdev, 32, control_out);
1081 
1082     for (i = 1; i < vser->bus.max_nr_ports; i++) {
1083         /* Add a per-port queue for host to guest transfers */
1084         vser->ivqs[i] = virtio_add_queue(vdev, 128, handle_input);
1085         /* Add a per-per queue for guest to host transfers */
1086         vser->ovqs[i] = virtio_add_queue(vdev, 128, handle_output);
1087     }
1088 
1089     vser->ports_map = g_malloc0((DIV_ROUND_UP(vser->serial.max_virtserial_ports, 32))
1090         * sizeof(vser->ports_map[0]));
1091     /*
1092      * Reserve location 0 for a console port for backward compat
1093      * (old kernel, new qemu)
1094      */
1095     mark_port_added(vser, 0);
1096 
1097     vser->post_load = NULL;
1098 
1099     QLIST_INSERT_HEAD(&vserdevices.devices, vser, next);
1100 }
1101 
1102 static void virtio_serial_port_class_init(ObjectClass *klass, void *data)
1103 {
1104     DeviceClass *k = DEVICE_CLASS(klass);
1105 
1106     set_bit(DEVICE_CATEGORY_INPUT, k->categories);
1107     k->bus_type = TYPE_VIRTIO_SERIAL_BUS;
1108     k->realize = virtser_port_device_realize;
1109     k->unrealize = virtser_port_device_unrealize;
1110     k->props = virtser_props;
1111 }
1112 
1113 static const TypeInfo virtio_serial_port_type_info = {
1114     .name = TYPE_VIRTIO_SERIAL_PORT,
1115     .parent = TYPE_DEVICE,
1116     .instance_size = sizeof(VirtIOSerialPort),
1117     .abstract = true,
1118     .class_size = sizeof(VirtIOSerialPortClass),
1119     .class_init = virtio_serial_port_class_init,
1120 };
1121 
1122 static void virtio_serial_device_unrealize(DeviceState *dev, Error **errp)
1123 {
1124     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1125     VirtIOSerial *vser = VIRTIO_SERIAL(dev);
1126 
1127     QLIST_REMOVE(vser, next);
1128 
1129     g_free(vser->ivqs);
1130     g_free(vser->ovqs);
1131     g_free(vser->ports_map);
1132     if (vser->post_load) {
1133         g_free(vser->post_load->connected);
1134         timer_del(vser->post_load->timer);
1135         timer_free(vser->post_load->timer);
1136         g_free(vser->post_load);
1137     }
1138 
1139     qbus_set_hotplug_handler(BUS(&vser->bus), NULL, errp);
1140 
1141     virtio_cleanup(vdev);
1142 }
1143 
1144 /* Note: 'console' is used for backwards compatibility */
1145 static const VMStateDescription vmstate_virtio_console = {
1146     .name = "virtio-console",
1147     .minimum_version_id = 3,
1148     .version_id = 3,
1149     .fields = (VMStateField[]) {
1150         VMSTATE_VIRTIO_DEVICE,
1151         VMSTATE_END_OF_LIST()
1152     },
1153 };
1154 
1155 static Property virtio_serial_properties[] = {
1156     DEFINE_PROP_UINT32("max_ports", VirtIOSerial, serial.max_virtserial_ports,
1157                                                   31),
1158     DEFINE_PROP_BIT64("emergency-write", VirtIOSerial, host_features,
1159                       VIRTIO_CONSOLE_F_EMERG_WRITE, true),
1160     DEFINE_PROP_END_OF_LIST(),
1161 };
1162 
1163 static void virtio_serial_class_init(ObjectClass *klass, void *data)
1164 {
1165     DeviceClass *dc = DEVICE_CLASS(klass);
1166     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1167     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass);
1168 
1169     QLIST_INIT(&vserdevices.devices);
1170 
1171     dc->props = virtio_serial_properties;
1172     dc->vmsd = &vmstate_virtio_console;
1173     set_bit(DEVICE_CATEGORY_INPUT, dc->categories);
1174     vdc->realize = virtio_serial_device_realize;
1175     vdc->unrealize = virtio_serial_device_unrealize;
1176     vdc->get_features = get_features;
1177     vdc->get_config = get_config;
1178     vdc->set_config = set_config;
1179     vdc->set_status = set_status;
1180     vdc->reset = vser_reset;
1181     vdc->save = virtio_serial_save_device;
1182     vdc->load = virtio_serial_load_device;
1183     hc->plug = virtser_port_device_plug;
1184     hc->unplug = qdev_simple_device_unplug_cb;
1185 }
1186 
1187 static const TypeInfo virtio_device_info = {
1188     .name = TYPE_VIRTIO_SERIAL,
1189     .parent = TYPE_VIRTIO_DEVICE,
1190     .instance_size = sizeof(VirtIOSerial),
1191     .class_init = virtio_serial_class_init,
1192     .interfaces = (InterfaceInfo[]) {
1193         { TYPE_HOTPLUG_HANDLER },
1194         { }
1195     }
1196 };
1197 
1198 static void virtio_serial_register_types(void)
1199 {
1200     type_register_static(&virtser_bus_info);
1201     type_register_static(&virtio_serial_port_type_info);
1202     type_register_static(&virtio_device_info);
1203 }
1204 
1205 type_init(virtio_serial_register_types)
1206