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