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