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