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