virtio-serial-bus.c 32.0 KB
Newer Older
1 2 3
/*
 * A bus for connecting virtio serial and console ports
 *
4
 * Copyright (C) 2009, 2010 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15
 *
 * Author(s):
 *  Amit Shah <amit.shah@redhat.com>
 *
 * Some earlier parts are:
 *  Copyright IBM, Corp. 2008
 * authored by
 *  Christian Ehrhardt <ehrhardt@linux.vnet.ibm.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.  See
 * the COPYING file in the top-level directory.
16 17 18
 *
 * Contributions after 2012-01-13 are licensed under the terms of the
 * 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"
A
Amit Shah 已提交
25
#include "trace.h"
P
Paolo Bonzini 已提交
26
#include "hw/virtio/virtio-serial.h"
27
#include "hw/virtio/virtio-access.h"
28

29
static struct VirtIOSerialDevices {
30 31 32
    QLIST_HEAD(, VirtIOSerial) devices;
} vserdevices;

33 34 35 36
static VirtIOSerialPort *find_port_by_id(VirtIOSerial *vser, uint32_t id)
{
    VirtIOSerialPort *port;

37 38 39 40
    if (id == VIRTIO_CONSOLE_BAD_ID) {
        return NULL;
    }

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
    QTAILQ_FOREACH(port, &vser->ports, next) {
        if (port->id == id)
            return port;
    }
    return NULL;
}

static VirtIOSerialPort *find_port_by_vq(VirtIOSerial *vser, VirtQueue *vq)
{
    VirtIOSerialPort *port;

    QTAILQ_FOREACH(port, &vser->ports, next) {
        if (port->ivq == vq || port->ovq == vq)
            return port;
    }
    return NULL;
}

59 60 61 62 63 64 65 66
static VirtIOSerialPort *find_port_by_name(char *name)
{
    VirtIOSerial *vser;

    QLIST_FOREACH(vser, &vserdevices.devices, next) {
        VirtIOSerialPort *port;

        QTAILQ_FOREACH(port, &vser->ports, next) {
67
            if (port->name && !strcmp(port->name, name)) {
68 69 70 71 72 73 74
                return port;
            }
        }
    }
    return NULL;
}

75 76
static bool use_multiport(VirtIOSerial *vser)
{
77
    VirtIODevice *vdev = VIRTIO_DEVICE(vser);
78
    return virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT);
79 80
}

81 82 83 84 85
static size_t write_to_port(VirtIOSerialPort *port,
                            const uint8_t *buf, size_t size)
{
    VirtQueueElement elem;
    VirtQueue *vq;
86
    size_t offset;
87 88 89 90 91 92

    vq = port->ivq;
    if (!virtio_queue_ready(vq)) {
        return 0;
    }

93
    offset = 0;
94
    while (offset < size) {
95
        size_t len;
96 97 98 99 100

        if (!virtqueue_pop(vq, &elem)) {
            break;
        }

101 102
        len = iov_from_buf(elem.in_sg, elem.in_num, 0,
                           buf + offset, size - offset);
103
        offset += len;
104 105 106 107

        virtqueue_push(vq, &elem, len);
    }

108
    virtio_notify(VIRTIO_DEVICE(port->vser), vq);
109 110 111
    return offset;
}

112
static void discard_vq_data(VirtQueue *vq, VirtIODevice *vdev)
113 114 115
{
    VirtQueueElement elem;

116 117 118
    if (!virtio_queue_ready(vq)) {
        return;
    }
119 120 121 122 123 124
    while (virtqueue_pop(vq, &elem)) {
        virtqueue_push(vq, &elem, 0);
    }
    virtio_notify(vdev, vq);
}

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 139 140 141 142 143 144 145
        /* Pop an elem only if we haven't left off a previous one mid-way */
        if (!port->elem.out_num) {
            if (!virtqueue_pop(vq, &port->elem)) {
                break;
            }
            port->iov_idx = 0;
            port->iov_offset = 0;
        }
146

147 148 149 150 151
        for (i = port->iov_idx; i < port->elem.out_num; i++) {
            size_t buf_size;
            ssize_t ret;

            buf_size = port->elem.out_sg[i].iov_len - port->iov_offset;
152
            ret = vsc->have_data(port,
153 154 155
                                  port->elem.out_sg[i].iov_base
                                  + port->iov_offset,
                                  buf_size);
156
            if (port->throttled) {
157 158 159 160 161 162 163
                port->iov_idx = i;
                if (ret > 0) {
                    port->iov_offset += ret;
                }
                break;
            }
            port->iov_offset = 0;
164
        }
165 166 167 168 169
        if (port->throttled) {
            break;
        }
        virtqueue_push(vq, &port->elem, 0);
        port->elem.out_num = 0;
170 171 172 173
    }
    virtio_notify(vdev, vq);
}

174
static void flush_queued_data(VirtIOSerialPort *port)
175
{
176
    assert(port);
177

178 179 180
    if (!virtio_queue_ready(port->ovq)) {
        return;
    }
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 187 188
{
    VirtQueueElement elem;
    VirtQueue *vq;

189
    vq = vser->c_ivq;
190 191 192 193 194 195 196 197 198 199
    if (!virtio_queue_ready(vq)) {
        return 0;
    }
    if (!virtqueue_pop(vq, &elem)) {
        return 0;
    }

    memcpy(elem.in_sg[0].iov_base, buf, len);

    virtqueue_push(vq, &elem, len);
200
    virtio_notify(VIRTIO_DEVICE(vser), vq);
201 202 203
    return len;
}

204 205
static size_t send_control_event(VirtIOSerial *vser, uint32_t port_id,
                                 uint16_t event, uint16_t value)
206
{
207
    VirtIODevice *vdev = VIRTIO_DEVICE(vser);
208 209
    struct virtio_console_control cpkt;

210 211 212
    virtio_stl_p(vdev, &cpkt.id, port_id);
    virtio_stw_p(vdev, &cpkt.event, event);
    virtio_stw_p(vdev, &cpkt.value, value);
213

214 215
    trace_virtio_serial_send_control_event(port_id, event, value);
    return send_control_msg(vser, &cpkt, sizeof(cpkt));
216 217 218 219 220
}

/* Functions for use inside qemu to open and read from/write to ports */
int virtio_serial_open(VirtIOSerialPort *port)
{
221 222 223 224 225 226
    /* Don't allow opening an already-open port */
    if (port->host_connected) {
        return 0;
    }
    /* Send port open notification to the guest */
    port->host_connected = true;
227
    send_control_event(port->vser, port->id, VIRTIO_CONSOLE_PORT_OPEN, 1);
228

229 230 231 232 233
    return 0;
}

int virtio_serial_close(VirtIOSerialPort *port)
{
234
    port->host_connected = false;
235 236 237 238 239
    /*
     * If there's any data the guest sent which the app didn't
     * consume, reset the throttling flag and discard the data.
     */
    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 245 246 247 248 249 250
    return 0;
}

/* Individual ports/apps call this function to write to the guest. */
ssize_t virtio_serial_write(VirtIOSerialPort *port, const uint8_t *buf,
                            size_t size)
{
251 252 253
    if (!port || !port->host_connected || !port->guest_connected) {
        return 0;
    }
254 255 256 257 258 259 260 261 262
    return write_to_port(port, buf, size);
}

/*
 * Readiness of the guest to accept data on a port.
 * Returns max. data the guest can receive
 */
size_t virtio_serial_guest_ready(VirtIOSerialPort *port)
{
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 270 271
        virtio_queue_empty(vq)) {
        return 0;
    }
272 273 274
    if (use_multiport(port->vser) && !port->guest_connected) {
        return 0;
    }
275
    virtqueue_get_avail_bytes(vq, &bytes, NULL, 4096, 0);
276
    return bytes;
277 278
}

279 280 281 282 283 284 285
static void flush_queued_data_bh(void *opaque)
{
    VirtIOSerialPort *port = opaque;

    flush_queued_data(port);
}

286 287 288 289 290 291
void virtio_serial_throttle_port(VirtIOSerialPort *port, bool throttle)
{
    if (!port) {
        return;
    }

A
Amit Shah 已提交
292
    trace_virtio_serial_throttle_port(port->id, throttle);
293 294 295 296
    port->throttled = throttle;
    if (throttle) {
        return;
    }
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 308
    uint8_t *buffer;
    size_t buffer_len;
309 310 311

    gcpkt = buf;

312 313 314 315 316
    if (len < sizeof(cpkt)) {
        /* The guest sent an invalid control packet */
        return;
    }

317 318
    cpkt.event = virtio_lduw_p(vdev, &gcpkt->event);
    cpkt.value = virtio_lduw_p(vdev, &gcpkt->value);
319

A
Amit Shah 已提交
320 321
    trace_virtio_serial_handle_control_message(cpkt.event, cpkt.value);

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 330 331 332
        /*
         * The device is up, we can now tell the device about all the
         * ports we have here.
         */
        QTAILQ_FOREACH(port, &vser->ports, next) {
333
            send_control_event(vser, port->id, VIRTIO_CONSOLE_PORT_ADD, 1);
334
        }
335 336
        return;
    }
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 343 344
        return;
    }

A
Amit Shah 已提交
345 346
    trace_virtio_serial_handle_control_message_port(port->id);

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 355
            break;
        }
356 357 358 359 360 361 362
        /*
         * Now that we know the guest asked for the port name, we're
         * sure the guest has initialised whatever state is necessary
         * for this port. Now's a good time to let the guest know if
         * this port is a console port so that the guest can hook it
         * up to hvc.
         */
363
        if (vsc->is_console) {
364
            send_control_event(vser, port->id, VIRTIO_CONSOLE_CONSOLE_PORT, 1);
365
        }
366

367
        if (port->name) {
368 369 370
            virtio_stl_p(vdev, &cpkt.id, port->id);
            virtio_stw_p(vdev, &cpkt.event, VIRTIO_CONSOLE_PORT_NAME);
            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 376 377 378

            memcpy(buffer, &cpkt, sizeof(cpkt));
            memcpy(buffer + sizeof(cpkt), port->name, strlen(port->name));
            buffer[buffer_len - 1] = 0;

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 389 390 391 392
        /*
         * When the guest has asked us for this information it means
         * the guest is all setup and has its virtqueues
         * initialised. If some app is interested in knowing about
         * this event, let it know.
         */
393 394
        if (vsc->guest_ready) {
            vsc->guest_ready(port);
395 396
        }
        break;
397 398 399

    case VIRTIO_CONSOLE_PORT_OPEN:
        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 409 410 411 412 413 414 415
    }
}

static void control_in(VirtIODevice *vdev, VirtQueue *vq)
{
}

static void control_out(VirtIODevice *vdev, VirtQueue *vq)
{
    VirtQueueElement elem;
    VirtIOSerial *vser;
416 417
    uint8_t *buf;
    size_t len;
418

419
    vser = VIRTIO_SERIAL(vdev);
420

421 422
    len = 0;
    buf = NULL;
423
    while (virtqueue_pop(vq, &elem)) {
424
        size_t cur_len;
425 426 427 428 429 430 431

        cur_len = iov_size(elem.out_sg, elem.out_num);
        /*
         * Allocate a new buf only if we didn't have one previously or
         * if the size of the buf differs
         */
        if (cur_len > len) {
432
            g_free(buf);
433

434
            buf = g_malloc(cur_len);
435 436
            len = cur_len;
        }
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 444 445 446 447 448 449
    virtio_notify(vdev, vq);
}

/* Guest wrote something to some port. */
static void handle_output(VirtIODevice *vdev, VirtQueue *vq)
{
    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 457 458
        discard_vq_data(vq, vdev);
        return;
    }
459 460 461

    if (!port->throttled) {
        do_flush_queued_data(port, vq, vdev);
462 463
        return;
    }
464 465 466 467
}

static void handle_input(VirtIODevice *vdev, VirtQueue *vq)
{
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    /*
     * Users of virtio-serial would like to know when guest becomes
     * writable again -- i.e. if a vq had stuff queued up and the
     * guest wasn't reading at all, the host would not be able to
     * write to the vq anymore.  Once the guest reads off something,
     * we can start queueing things up again.  However, this call is
     * made for each buffer addition by the guest -- even though free
     * buffers existed prior to the current buffer addition.  This is
     * done so as not to maintain previous state, which will need
     * additional live-migration-related changes.
     */
    VirtIOSerial *vser;
    VirtIOSerialPort *port;
    VirtIOSerialPortClass *vsc;

    vser = VIRTIO_SERIAL(vdev);
    port = find_port_by_vq(vser, vq);

    if (!port) {
        return;
    }
    vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);

    /*
     * If guest_connected is false, this call is being made by the
     * early-boot queueing up of descriptors, which is just noise for
     * the host apps -- don't disturb them in that case.
     */
    if (port->guest_connected && port->host_connected && vsc->guest_writable) {
        vsc->guest_writable(port);
    }
499 500
}

G
Gerd Hoffmann 已提交
501
static uint64_t get_features(VirtIODevice *vdev, uint64_t features)
502
{
503 504
    VirtIOSerial *vser;

505
    vser = VIRTIO_SERIAL(vdev);
506

507
    if (vser->bus.max_nr_ports > 1) {
508
        virtio_add_feature(&features, VIRTIO_CONSOLE_F_MULTIPORT);
509
    }
510 511 512 513 514 515
    return features;
}

/* Guest requested config info */
static void get_config(VirtIODevice *vdev, uint8_t *config_data)
{
516 517 518
    VirtIOSerial *vser = VIRTIO_SERIAL(vdev);
    struct virtio_console_config *config =
        (struct virtio_console_config *)config_data;
519

520 521 522 523
    config->cols = 0;
    config->rows = 0;
    config->max_nr_ports = virtio_tswap32(vdev,
                                          vser->serial.max_virtserial_ports);
524 525
}

526 527 528 529 530 531 532 533 534
static void guest_reset(VirtIOSerial *vser)
{
    VirtIOSerialPort *port;
    VirtIOSerialPortClass *vsc;

    QTAILQ_FOREACH(port, &vser->ports, next) {
        vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
        if (port->guest_connected) {
            port->guest_connected = false;
535 536 537
            if (vsc->set_guest_connected) {
                vsc->set_guest_connected(port, false);
            }
538 539 540 541
        }
    }
}

542 543 544 545 546
static void set_status(VirtIODevice *vdev, uint8_t status)
{
    VirtIOSerial *vser;
    VirtIOSerialPort *port;

547
    vser = VIRTIO_SERIAL(vdev);
548 549 550 551 552 553 554 555 556 557 558 559
    port = find_port_by_id(vser, 0);

    if (port && !use_multiport(port->vser)
        && (status & VIRTIO_CONFIG_S_DRIVER_OK)) {
        /*
         * Non-multiport guests won't be able to tell us guest
         * open/close status.  Such guests can only have a port at id
         * 0, so set guest_connected for such ports as soon as guest
         * is up.
         */
        port->guest_connected = true;
    }
560 561 562 563 564 565 566 567 568
    if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
        guest_reset(vser);
    }
}

static void vser_reset(VirtIODevice *vdev)
{
    VirtIOSerial *vser;

569
    vser = VIRTIO_SERIAL(vdev);
570
    guest_reset(vser);
571 572
}

573 574
static void virtio_serial_save(QEMUFile *f, void *opaque)
{
575 576 577 578 579 580 581
    /* The virtio device */
    virtio_save(VIRTIO_DEVICE(opaque), f);
}

static void virtio_serial_save_device(VirtIODevice *vdev, QEMUFile *f)
{
    VirtIOSerial *s = VIRTIO_SERIAL(vdev);
582 583
    VirtIOSerialPort *port;
    uint32_t nr_active_ports;
584
    unsigned int i, max_nr_ports;
585
    struct virtio_console_config config;
586

587 588 589 590 591
    /* The config space (ignored on the far end in current versions) */
    get_config(vdev, (uint8_t *)&config);
    qemu_put_be16s(f, &config.cols);
    qemu_put_be16s(f, &config.rows);
    qemu_put_be32s(f, &config.max_nr_ports);
592 593

    /* The ports map */
594
    max_nr_ports = s->serial.max_virtserial_ports;
595
    for (i = 0; i < (max_nr_ports + 31) / 32; i++) {
596 597
        qemu_put_be32s(f, &s->ports_map[i]);
    }
598

599
    /* Ports */
600

601
    nr_active_ports = 0;
602
    QTAILQ_FOREACH(port, &s->ports, next) {
603
        nr_active_ports++;
604
    }
605 606 607 608 609 610 611

    qemu_put_be32s(f, &nr_active_ports);

    /*
     * Items in struct VirtIOSerialPort.
     */
    QTAILQ_FOREACH(port, &s->ports, next) {
612 613
        uint32_t elem_popped;

614 615
        qemu_put_be32s(f, &port->id);
        qemu_put_byte(f, port->guest_connected);
616
        qemu_put_byte(f, port->host_connected);
617 618 619 620 621 622 623 624 625 626 627 628 629

	elem_popped = 0;
        if (port->elem.out_num) {
            elem_popped = 1;
        }
        qemu_put_be32s(f, &elem_popped);
        if (elem_popped) {
            qemu_put_be32s(f, &port->iov_idx);
            qemu_put_be64s(f, &port->iov_offset);

            qemu_put_buffer(f, (unsigned char *)&port->elem,
                            sizeof(port->elem));
        }
630
    }
631 632
}

633 634
static void virtio_serial_post_load_timer_cb(void *opaque)
{
635
    uint32_t i;
636
    VirtIOSerial *s = VIRTIO_SERIAL(opaque);
637 638
    VirtIOSerialPort *port;
    uint8_t host_connected;
639
    VirtIOSerialPortClass *vsc;
640

641 642 643 644 645 646
    if (!s->post_load) {
        return;
    }
    for (i = 0 ; i < s->post_load->nr_active_ports; ++i) {
        port = s->post_load->connected[i].port;
        host_connected = s->post_load->connected[i].host_connected;
647 648 649 650 651
        if (host_connected != port->host_connected) {
            /*
             * We have to let the guest know of the host connection
             * status change
             */
652
            send_control_event(s, port->id, VIRTIO_CONSOLE_PORT_OPEN,
653 654
                               port->host_connected);
        }
655 656 657 658
        vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
        if (vsc->set_guest_connected) {
            vsc->set_guest_connected(port, port->guest_connected);
        }
659
    }
660
    g_free(s->post_load->connected);
661
    timer_free(s->post_load->timer);
662 663
    g_free(s->post_load);
    s->post_load = NULL;
664 665
}

666 667 668 669 670
static int fetch_active_ports_list(QEMUFile *f, int version_id,
                                   VirtIOSerial *s, uint32_t nr_active_ports)
{
    uint32_t i;

671 672 673 674 675
    s->post_load = g_malloc0(sizeof(*s->post_load));
    s->post_load->nr_active_ports = nr_active_ports;
    s->post_load->connected =
        g_malloc0(sizeof(*s->post_load->connected) * nr_active_ports);

676
    s->post_load->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
677 678
                                            virtio_serial_post_load_timer_cb,
                                            s);
679 680 681 682 683 684 685 686 687 688 689 690 691

    /* Items in struct VirtIOSerialPort */
    for (i = 0; i < nr_active_ports; i++) {
        VirtIOSerialPort *port;
        uint32_t id;

        id = qemu_get_be32(f);
        port = find_port_by_id(s, id);
        if (!port) {
            return -EINVAL;
        }

        port->guest_connected = qemu_get_byte(f);
692 693
        s->post_load->connected[i].port = port;
        s->post_load->connected[i].host_connected = qemu_get_byte(f);
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717

        if (version_id > 2) {
            uint32_t elem_popped;

            qemu_get_be32s(f, &elem_popped);
            if (elem_popped) {
                qemu_get_be32s(f, &port->iov_idx);
                qemu_get_be64s(f, &port->iov_offset);

                qemu_get_buffer(f, (unsigned char *)&port->elem,
                                sizeof(port->elem));
                virtqueue_map_sg(port->elem.in_sg, port->elem.in_addr,
                                 port->elem.in_num, 1);
                virtqueue_map_sg(port->elem.out_sg, port->elem.out_addr,
                                 port->elem.out_num, 1);

                /*
                 *  Port was throttled on source machine.  Let's
                 *  unthrottle it here so data starts flowing again.
                 */
                virtio_serial_throttle_port(port, false);
            }
        }
    }
718
    timer_mod(s->post_load->timer, 1);
719 720 721
    return 0;
}

722 723
static int virtio_serial_load(QEMUFile *f, void *opaque, int version_id)
{
724
    if (version_id > 3) {
725 726
        return -EINVAL;
    }
727

728
    /* The virtio device */
729 730 731 732 733 734 735 736 737 738 739
    return virtio_load(VIRTIO_DEVICE(opaque), f, version_id);
}

static int virtio_serial_load_device(VirtIODevice *vdev, QEMUFile *f,
                                     int version_id)
{
    VirtIOSerial *s = VIRTIO_SERIAL(vdev);
    uint32_t max_nr_ports, nr_active_ports, ports_map;
    unsigned int i;
    int ret;
    uint32_t tmp;
740 741 742 743 744

    if (version_id < 2) {
        return 0;
    }

745 746 747 748
    /* Unused */
    qemu_get_be16s(f, (uint16_t *) &tmp);
    qemu_get_be16s(f, (uint16_t *) &tmp);
    qemu_get_be32s(f, &tmp);
749

750
    max_nr_ports = s->serial.max_virtserial_ports;
751
    for (i = 0; i < (max_nr_ports + 31) / 32; i++) {
752
        qemu_get_be32s(f, &ports_map);
753

754
        if (ports_map != s->ports_map[i]) {
755 756 757 758 759 760
            /*
             * Ports active on source and destination don't
             * match. Fail migration.
             */
            return -EINVAL;
        }
761 762
    }

763 764
    qemu_get_be32s(f, &nr_active_ports);

765 766 767 768
    if (nr_active_ports) {
        ret = fetch_active_ports_list(f, version_id, s, nr_active_ports);
        if (ret) {
            return ret;
769
        }
770
    }
771 772 773 774 775
    return 0;
}

static void virtser_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent);

776 777 778 779 780 781
static Property virtser_props[] = {
    DEFINE_PROP_UINT32("nr", VirtIOSerialPort, id, VIRTIO_CONSOLE_BAD_ID),
    DEFINE_PROP_STRING("name", VirtIOSerialPort, name),
    DEFINE_PROP_END_OF_LIST()
};

782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
#define TYPE_VIRTIO_SERIAL_BUS "virtio-serial-bus"
#define VIRTIO_SERIAL_BUS(obj) \
      OBJECT_CHECK(VirtIOSerialBus, (obj), TYPE_VIRTIO_SERIAL_BUS)

static void virtser_bus_class_init(ObjectClass *klass, void *data)
{
    BusClass *k = BUS_CLASS(klass);
    k->print_dev = virtser_bus_dev_print;
}

static const TypeInfo virtser_bus_info = {
    .name = TYPE_VIRTIO_SERIAL_BUS,
    .parent = TYPE_BUS,
    .instance_size = sizeof(VirtIOSerialBus),
    .class_init = virtser_bus_class_init,
797 798 799 800
};

static void virtser_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent)
{
801
    VirtIOSerialPort *port = DO_UPCAST(VirtIOSerialPort, dev, qdev);
802

803 804 805 806 807
    monitor_printf(mon, "%*sport %d, guest %s, host %s, throttle %s\n",
                   indent, "", port->id,
                   port->guest_connected ? "on" : "off",
                   port->host_connected ? "on" : "off",
                   port->throttled ? "on" : "off");
808 809
}

810 811 812
/* This function is only used if a port id is not provided by the user */
static uint32_t find_free_port_id(VirtIOSerial *vser)
{
813
    unsigned int i, max_nr_ports;
814

815
    max_nr_ports = vser->serial.max_virtserial_ports;
816
    for (i = 0; i < (max_nr_ports + 31) / 32; i++) {
817
        uint32_t map, zeroes;
818 819

        map = vser->ports_map[i];
820 821 822
        zeroes = ctz32(~map);
        if (zeroes != 32) {
            return zeroes + i * 32;
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
        }
    }
    return VIRTIO_CONSOLE_BAD_ID;
}

static void mark_port_added(VirtIOSerial *vser, uint32_t port_id)
{
    unsigned int i;

    i = port_id / 32;
    vser->ports_map[i] |= 1U << (port_id % 32);
}

static void add_port(VirtIOSerial *vser, uint32_t port_id)
{
    mark_port_added(vser, port_id);
839
    send_control_event(vser, port_id, VIRTIO_CONSOLE_PORT_ADD, 1);
840 841 842 843
}

static void remove_port(VirtIOSerial *vser, uint32_t port_id)
{
844
    VirtIOSerialPort *port;
845

846 847 848 849 850 851 852 853 854 855 856
    /*
     * Don't mark port 0 removed -- we explicitly reserve it for
     * backward compat with older guests, ensure a virtconsole device
     * unplug retains the reservation.
     */
    if (port_id) {
        unsigned int i;

        i = port_id / 32;
        vser->ports_map[i] &= ~(1U << (port_id % 32));
    }
857

858
    port = find_port_by_id(vser, port_id);
859 860 861 862 863 864
    /*
     * This function is only called from qdev's unplug callback; if we
     * get a NULL port here, we're in trouble.
     */
    assert(port);

865
    /* Flush out any unconsumed buffers first */
866
    discard_vq_data(port->ovq, VIRTIO_DEVICE(port->vser));
867

868
    send_control_event(vser, port->id, VIRTIO_CONSOLE_PORT_REMOVE, 1);
869 870
}

871
static void virtser_port_device_realize(DeviceState *dev, Error **errp)
872
{
873
    VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev);
874
    VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);
875 876
    VirtIOSerialBus *bus = VIRTIO_SERIAL_BUS(qdev_get_parent_bus(dev));
    int max_nr_ports;
877
    bool plugging_port0;
878
    Error *err = NULL;
879 880

    port->vser = bus->vser;
881
    port->bh = qemu_bh_new(flush_queued_data_bh, port);
882

883
    assert(vsc->have_data);
884

885 886 887 888 889
    /*
     * Is the first console port we're seeing? If so, put it up at
     * location 0. This is done for backward compatibility (old
     * kernel, new qemu).
     */
890
    plugging_port0 = vsc->is_console && !find_port_by_id(port->vser, 0);
891

892
    if (find_port_by_id(port->vser, port->id)) {
893 894 895
        error_setg(errp, "virtio-serial-bus: A port already exists at id %u",
                   port->id);
        return;
896 897
    }

898
    if (port->name != NULL && find_port_by_name(port->name)) {
899 900 901 902 903
        error_setg(errp, "virtio-serial-bus: A port already exists by name %s",
                   port->name);
        return;
    }

904 905 906 907 908 909
    if (port->id == VIRTIO_CONSOLE_BAD_ID) {
        if (plugging_port0) {
            port->id = 0;
        } else {
            port->id = find_free_port_id(port->vser);
            if (port->id == VIRTIO_CONSOLE_BAD_ID) {
910 911 912
                error_setg(errp, "virtio-serial-bus: Maximum port limit for "
                                 "this device reached");
                return;
913 914 915 916
            }
        }
    }

917
    max_nr_ports = port->vser->serial.max_virtserial_ports;
918
    if (port->id >= max_nr_ports) {
919 920 921
        error_setg(errp, "virtio-serial-bus: Out-of-range port id specified, "
                         "max. allowed: %u", max_nr_ports - 1);
        return;
922 923
    }

924 925 926 927
    vsc->realize(dev, &err);
    if (err != NULL) {
        error_propagate(errp, err);
        return;
928 929
    }

930
    port->elem.out_num = 0;
931 932 933 934 935 936
}

static void virtser_port_device_plug(HotplugHandler *hotplug_dev,
                                     DeviceState *dev, Error **errp)
{
    VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev);
937

938 939 940 941
    QTAILQ_INSERT_TAIL(&port->vser->ports, port, next);
    port->ivq = port->vser->ivqs[port->id];
    port->ovq = port->vser->ovqs[port->id];

942 943
    add_port(port->vser, port->id);

944
    /* Send an update to the guest about this new port added */
945
    virtio_notify_config(VIRTIO_DEVICE(hotplug_dev));
946 947
}

948
static void virtser_port_device_unrealize(DeviceState *dev, Error **errp)
949
{
950 951
    VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev);
    VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(dev);
952 953
    VirtIOSerial *vser = port->vser;

954
    qemu_bh_delete(port->bh);
955
    remove_port(port->vser, port->id);
956

957 958
    QTAILQ_REMOVE(&vser->ports, port, next);

959 960
    if (vsc->unrealize) {
        vsc->unrealize(dev, errp);
961
    }
962 963
}

964
static void virtio_serial_device_realize(DeviceState *dev, Error **errp)
965
{
966
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
967
    VirtIOSerial *vser = VIRTIO_SERIAL(dev);
968
    uint32_t i, max_supported_ports;
969

970
    if (!vser->serial.max_virtserial_ports) {
971 972
        error_setg(errp, "Maximum number of serial ports not specified");
        return;
973
    }
974

975
    /* Each port takes 2 queues, and one pair is for the control queue */
976
    max_supported_ports = VIRTIO_QUEUE_MAX / 2 - 1;
977

978
    if (vser->serial.max_virtserial_ports > max_supported_ports) {
979 980
        error_setg(errp, "maximum ports supported: %u", max_supported_ports);
        return;
981 982
    }

983 984
    /* We don't support emergency write, skip it for now. */
    /* TODO: cleaner fix, depending on host features. */
985
    virtio_init(vdev, "virtio-serial", VIRTIO_ID_CONSOLE,
986
                offsetof(struct virtio_console_config, emerg_wr));
987 988

    /* Spawn a new virtio-serial bus on which the ports will ride as devices */
989
    qbus_create_inplace(&vser->bus, sizeof(vser->bus), TYPE_VIRTIO_SERIAL_BUS,
990
                        dev, vdev->bus_name);
991
    qbus_set_hotplug_handler(BUS(&vser->bus), DEVICE(vser), errp);
992
    vser->bus.vser = vser;
993 994
    QTAILQ_INIT(&vser->ports);

995 996 997 998 999
    vser->bus.max_nr_ports = vser->serial.max_virtserial_ports;
    vser->ivqs = g_malloc(vser->serial.max_virtserial_ports
                          * sizeof(VirtQueue *));
    vser->ovqs = g_malloc(vser->serial.max_virtserial_ports
                          * sizeof(VirtQueue *));
1000 1001 1002 1003 1004 1005

    /* Add a queue for host to guest transfers for port 0 (backward compat) */
    vser->ivqs[0] = virtio_add_queue(vdev, 128, handle_input);
    /* Add a queue for guest to host transfers for port 0 (backward compat) */
    vser->ovqs[0] = virtio_add_queue(vdev, 128, handle_output);

1006 1007 1008 1009 1010 1011
    /* TODO: host to guest notifications can get dropped
     * if the queue fills up. Implement queueing in host,
     * this might also make it possible to reduce the control
     * queue size: as guest preposts buffers there,
     * this will save 4Kbyte of guest memory per entry. */

1012
    /* control queue: host to guest */
1013
    vser->c_ivq = virtio_add_queue(vdev, 32, control_in);
1014
    /* control queue: guest to host */
1015
    vser->c_ovq = virtio_add_queue(vdev, 32, control_out);
1016

1017
    for (i = 1; i < vser->bus.max_nr_ports; i++) {
1018 1019 1020 1021 1022 1023
        /* Add a per-port queue for host to guest transfers */
        vser->ivqs[i] = virtio_add_queue(vdev, 128, handle_input);
        /* Add a per-per queue for guest to host transfers */
        vser->ovqs[i] = virtio_add_queue(vdev, 128, handle_output);
    }

1024
    vser->ports_map = g_malloc0(((vser->serial.max_virtserial_ports + 31) / 32)
1025
        * sizeof(vser->ports_map[0]));
1026 1027 1028 1029
    /*
     * Reserve location 0 for a console port for backward compat
     * (old kernel, new qemu)
     */
1030
    mark_port_added(vser, 0);
1031

1032 1033
    vser->post_load = NULL;

1034 1035 1036 1037
    /*
     * Register for the savevm section with the virtio-console name
     * to preserve backward compat
     */
1038
    register_savevm(dev, "virtio-console", -1, 3, virtio_serial_save,
1039
                    virtio_serial_load, vser);
1040 1041

    QLIST_INSERT_HEAD(&vserdevices.devices, vser, next);
1042
}
1043

1044 1045 1046
static void virtio_serial_port_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *k = DEVICE_CLASS(klass);
1047

1048
    set_bit(DEVICE_CATEGORY_INPUT, k->categories);
1049
    k->bus_type = TYPE_VIRTIO_SERIAL_BUS;
1050 1051
    k->realize = virtser_port_device_realize;
    k->unrealize = virtser_port_device_unrealize;
1052
    k->props = virtser_props;
1053 1054
}

1055
static const TypeInfo virtio_serial_port_type_info = {
1056 1057 1058 1059 1060
    .name = TYPE_VIRTIO_SERIAL_PORT,
    .parent = TYPE_DEVICE,
    .instance_size = sizeof(VirtIOSerialPort),
    .abstract = true,
    .class_size = sizeof(VirtIOSerialPortClass),
1061
    .class_init = virtio_serial_port_class_init,
1062 1063
};

1064
static void virtio_serial_device_unrealize(DeviceState *dev, Error **errp)
1065
{
1066 1067
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
    VirtIOSerial *vser = VIRTIO_SERIAL(dev);
1068

1069 1070
    QLIST_REMOVE(vser, next);

1071
    unregister_savevm(dev, "virtio-console", vser);
1072 1073 1074 1075 1076 1077

    g_free(vser->ivqs);
    g_free(vser->ovqs);
    g_free(vser->ports_map);
    if (vser->post_load) {
        g_free(vser->post_load->connected);
1078 1079
        timer_del(vser->post_load->timer);
        timer_free(vser->post_load->timer);
1080 1081
        g_free(vser->post_load);
    }
1082
    virtio_cleanup(vdev);
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
}

static Property virtio_serial_properties[] = {
    DEFINE_VIRTIO_SERIAL_PROPERTIES(VirtIOSerial, serial),
    DEFINE_PROP_END_OF_LIST(),
};

static void virtio_serial_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);
    VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1094
    HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass);
1095

1096 1097
    QLIST_INIT(&vserdevices.devices);

1098
    dc->props = virtio_serial_properties;
1099
    set_bit(DEVICE_CATEGORY_INPUT, dc->categories);
1100
    vdc->realize = virtio_serial_device_realize;
1101
    vdc->unrealize = virtio_serial_device_unrealize;
1102 1103 1104 1105
    vdc->get_features = get_features;
    vdc->get_config = get_config;
    vdc->set_status = set_status;
    vdc->reset = vser_reset;
1106 1107
    vdc->save = virtio_serial_save_device;
    vdc->load = virtio_serial_load_device;
1108 1109
    hc->plug = virtser_port_device_plug;
    hc->unplug = qdev_simple_device_unplug_cb;
1110 1111 1112 1113 1114 1115 1116
}

static const TypeInfo virtio_device_info = {
    .name = TYPE_VIRTIO_SERIAL,
    .parent = TYPE_VIRTIO_DEVICE,
    .instance_size = sizeof(VirtIOSerial),
    .class_init = virtio_serial_class_init,
1117 1118 1119 1120
    .interfaces = (InterfaceInfo[]) {
        { TYPE_HOTPLUG_HANDLER },
        { }
    }
1121 1122
};

A
Andreas Färber 已提交
1123
static void virtio_serial_register_types(void)
1124
{
1125
    type_register_static(&virtser_bus_info);
1126
    type_register_static(&virtio_serial_port_type_info);
1127
    type_register_static(&virtio_device_info);
1128 1129
}

A
Andreas Färber 已提交
1130
type_init(virtio_serial_register_types)