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