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