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