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