qemu/hw/virtio/virtio.c
<<
>>
Prefs
   1/*
   2 * Virtio Support
   3 *
   4 * Copyright IBM, Corp. 2007
   5 *
   6 * Authors:
   7 *  Anthony Liguori   <aliguori@us.ibm.com>
   8 *
   9 * This work is licensed under the terms of the GNU GPL, version 2.  See
  10 * the COPYING file in the top-level directory.
  11 *
  12 */
  13
  14#include "qemu/osdep.h"
  15#include "qapi/error.h"
  16#include "qemu-common.h"
  17#include "cpu.h"
  18#include "trace.h"
  19#include "exec/address-spaces.h"
  20#include "qemu/error-report.h"
  21#include "hw/virtio/virtio.h"
  22#include "qemu/atomic.h"
  23#include "hw/virtio/virtio-bus.h"
  24#include "migration/migration.h"
  25#include "hw/virtio/virtio-access.h"
  26
  27/*
  28 * The alignment to use between consumer and producer parts of vring.
  29 * x86 pagesize again. This is the default, used by transports like PCI
  30 * which don't provide a means for the guest to tell the host the alignment.
  31 */
  32#define VIRTIO_PCI_VRING_ALIGN         4096
  33
  34typedef struct VRingDesc
  35{
  36    uint64_t addr;
  37    uint32_t len;
  38    uint16_t flags;
  39    uint16_t next;
  40} VRingDesc;
  41
  42typedef struct VRingAvail
  43{
  44    uint16_t flags;
  45    uint16_t idx;
  46    uint16_t ring[0];
  47} VRingAvail;
  48
  49typedef struct VRingUsedElem
  50{
  51    uint32_t id;
  52    uint32_t len;
  53} VRingUsedElem;
  54
  55typedef struct VRingUsed
  56{
  57    uint16_t flags;
  58    uint16_t idx;
  59    VRingUsedElem ring[0];
  60} VRingUsed;
  61
  62typedef struct VRing
  63{
  64    unsigned int num;
  65    unsigned int num_default;
  66    unsigned int align;
  67    hwaddr desc;
  68    hwaddr avail;
  69    hwaddr used;
  70} VRing;
  71
  72struct VirtQueue
  73{
  74    VRing vring;
  75
  76    /* Next head to pop */
  77    uint16_t last_avail_idx;
  78
  79    /* Last avail_idx read from VQ. */
  80    uint16_t shadow_avail_idx;
  81
  82    uint16_t used_idx;
  83
  84    /* Last used index value we have signalled on */
  85    uint16_t signalled_used;
  86
  87    /* Last used index value we have signalled on */
  88    bool signalled_used_valid;
  89
  90    /* Notification enabled? */
  91    bool notification;
  92
  93    uint16_t queue_index;
  94
  95    int inuse;
  96
  97    uint16_t vector;
  98    void (*handle_output)(VirtIODevice *vdev, VirtQueue *vq);
  99    void (*handle_aio_output)(VirtIODevice *vdev, VirtQueue *vq);
 100    VirtIODevice *vdev;
 101    EventNotifier guest_notifier;
 102    EventNotifier host_notifier;
 103    QLIST_ENTRY(VirtQueue) node;
 104};
 105
 106/* virt queue functions */
 107void virtio_queue_update_rings(VirtIODevice *vdev, int n)
 108{
 109    VRing *vring = &vdev->vq[n].vring;
 110
 111    if (!vring->desc) {
 112        /* not yet setup -> nothing to do */
 113        return;
 114    }
 115    vring->avail = vring->desc + vring->num * sizeof(VRingDesc);
 116    vring->used = vring_align(vring->avail +
 117                              offsetof(VRingAvail, ring[vring->num]),
 118                              vring->align);
 119}
 120
 121static void vring_desc_read(VirtIODevice *vdev, VRingDesc *desc,
 122                            hwaddr desc_pa, int i)
 123{
 124    address_space_read(&address_space_memory, desc_pa + i * sizeof(VRingDesc),
 125                       MEMTXATTRS_UNSPECIFIED, (void *)desc, sizeof(VRingDesc));
 126    virtio_tswap64s(vdev, &desc->addr);
 127    virtio_tswap32s(vdev, &desc->len);
 128    virtio_tswap16s(vdev, &desc->flags);
 129    virtio_tswap16s(vdev, &desc->next);
 130}
 131
 132static inline uint16_t vring_avail_flags(VirtQueue *vq)
 133{
 134    hwaddr pa;
 135    pa = vq->vring.avail + offsetof(VRingAvail, flags);
 136    return virtio_lduw_phys(vq->vdev, pa);
 137}
 138
 139static inline uint16_t vring_avail_idx(VirtQueue *vq)
 140{
 141    hwaddr pa;
 142    pa = vq->vring.avail + offsetof(VRingAvail, idx);
 143    vq->shadow_avail_idx = virtio_lduw_phys(vq->vdev, pa);
 144    return vq->shadow_avail_idx;
 145}
 146
 147static inline uint16_t vring_avail_ring(VirtQueue *vq, int i)
 148{
 149    hwaddr pa;
 150    pa = vq->vring.avail + offsetof(VRingAvail, ring[i]);
 151    return virtio_lduw_phys(vq->vdev, pa);
 152}
 153
 154static inline uint16_t vring_get_used_event(VirtQueue *vq)
 155{
 156    return vring_avail_ring(vq, vq->vring.num);
 157}
 158
 159static inline void vring_used_write(VirtQueue *vq, VRingUsedElem *uelem,
 160                                    int i)
 161{
 162    hwaddr pa;
 163    virtio_tswap32s(vq->vdev, &uelem->id);
 164    virtio_tswap32s(vq->vdev, &uelem->len);
 165    pa = vq->vring.used + offsetof(VRingUsed, ring[i]);
 166    address_space_write(&address_space_memory, pa, MEMTXATTRS_UNSPECIFIED,
 167                       (void *)uelem, sizeof(VRingUsedElem));
 168}
 169
 170static uint16_t vring_used_idx(VirtQueue *vq)
 171{
 172    hwaddr pa;
 173    pa = vq->vring.used + offsetof(VRingUsed, idx);
 174    return virtio_lduw_phys(vq->vdev, pa);
 175}
 176
 177static inline void vring_used_idx_set(VirtQueue *vq, uint16_t val)
 178{
 179    hwaddr pa;
 180    pa = vq->vring.used + offsetof(VRingUsed, idx);
 181    virtio_stw_phys(vq->vdev, pa, val);
 182    vq->used_idx = val;
 183}
 184
 185static inline void vring_used_flags_set_bit(VirtQueue *vq, int mask)
 186{
 187    VirtIODevice *vdev = vq->vdev;
 188    hwaddr pa;
 189    pa = vq->vring.used + offsetof(VRingUsed, flags);
 190    virtio_stw_phys(vdev, pa, virtio_lduw_phys(vdev, pa) | mask);
 191}
 192
 193static inline void vring_used_flags_unset_bit(VirtQueue *vq, int mask)
 194{
 195    VirtIODevice *vdev = vq->vdev;
 196    hwaddr pa;
 197    pa = vq->vring.used + offsetof(VRingUsed, flags);
 198    virtio_stw_phys(vdev, pa, virtio_lduw_phys(vdev, pa) & ~mask);
 199}
 200
 201static inline void vring_set_avail_event(VirtQueue *vq, uint16_t val)
 202{
 203    hwaddr pa;
 204    if (!vq->notification) {
 205        return;
 206    }
 207    pa = vq->vring.used + offsetof(VRingUsed, ring[vq->vring.num]);
 208    virtio_stw_phys(vq->vdev, pa, val);
 209}
 210
 211void virtio_queue_set_notification(VirtQueue *vq, int enable)
 212{
 213    vq->notification = enable;
 214    if (virtio_vdev_has_feature(vq->vdev, VIRTIO_RING_F_EVENT_IDX)) {
 215        vring_set_avail_event(vq, vring_avail_idx(vq));
 216    } else if (enable) {
 217        vring_used_flags_unset_bit(vq, VRING_USED_F_NO_NOTIFY);
 218    } else {
 219        vring_used_flags_set_bit(vq, VRING_USED_F_NO_NOTIFY);
 220    }
 221    if (enable) {
 222        /* Expose avail event/used flags before caller checks the avail idx. */
 223        smp_mb();
 224    }
 225}
 226
 227int virtio_queue_ready(VirtQueue *vq)
 228{
 229    return vq->vring.avail != 0;
 230}
 231
 232/* Fetch avail_idx from VQ memory only when we really need to know if
 233 * guest has added some buffers. */
 234int virtio_queue_empty(VirtQueue *vq)
 235{
 236    if (vq->shadow_avail_idx != vq->last_avail_idx) {
 237        return 0;
 238    }
 239
 240    return vring_avail_idx(vq) == vq->last_avail_idx;
 241}
 242
 243static void virtqueue_unmap_sg(VirtQueue *vq, const VirtQueueElement *elem,
 244                               unsigned int len)
 245{
 246    unsigned int offset;
 247    int i;
 248
 249    offset = 0;
 250    for (i = 0; i < elem->in_num; i++) {
 251        size_t size = MIN(len - offset, elem->in_sg[i].iov_len);
 252
 253        cpu_physical_memory_unmap(elem->in_sg[i].iov_base,
 254                                  elem->in_sg[i].iov_len,
 255                                  1, size);
 256
 257        offset += size;
 258    }
 259
 260    for (i = 0; i < elem->out_num; i++)
 261        cpu_physical_memory_unmap(elem->out_sg[i].iov_base,
 262                                  elem->out_sg[i].iov_len,
 263                                  0, elem->out_sg[i].iov_len);
 264}
 265
 266void virtqueue_discard(VirtQueue *vq, const VirtQueueElement *elem,
 267                       unsigned int len)
 268{
 269    vq->last_avail_idx--;
 270    virtqueue_unmap_sg(vq, elem, len);
 271}
 272
 273void virtqueue_fill(VirtQueue *vq, const VirtQueueElement *elem,
 274                    unsigned int len, unsigned int idx)
 275{
 276    VRingUsedElem uelem;
 277
 278    trace_virtqueue_fill(vq, elem, len, idx);
 279
 280    virtqueue_unmap_sg(vq, elem, len);
 281
 282    idx = (idx + vq->used_idx) % vq->vring.num;
 283
 284    uelem.id = elem->index;
 285    uelem.len = len;
 286    vring_used_write(vq, &uelem, idx);
 287}
 288
 289void virtqueue_flush(VirtQueue *vq, unsigned int count)
 290{
 291    uint16_t old, new;
 292    /* Make sure buffer is written before we update index. */
 293    smp_wmb();
 294    trace_virtqueue_flush(vq, count);
 295    old = vq->used_idx;
 296    new = old + count;
 297    vring_used_idx_set(vq, new);
 298    vq->inuse -= count;
 299    if (unlikely((int16_t)(new - vq->signalled_used) < (uint16_t)(new - old)))
 300        vq->signalled_used_valid = false;
 301}
 302
 303void virtqueue_push(VirtQueue *vq, const VirtQueueElement *elem,
 304                    unsigned int len)
 305{
 306    virtqueue_fill(vq, elem, len, 0);
 307    virtqueue_flush(vq, 1);
 308}
 309
 310static int virtqueue_num_heads(VirtQueue *vq, unsigned int idx)
 311{
 312    uint16_t num_heads = vring_avail_idx(vq) - idx;
 313
 314    /* Check it isn't doing very strange things with descriptor numbers. */
 315    if (num_heads > vq->vring.num) {
 316        error_report("Guest moved used index from %u to %u",
 317                     idx, vq->shadow_avail_idx);
 318        exit(1);
 319    }
 320    /* On success, callers read a descriptor at vq->last_avail_idx.
 321     * Make sure descriptor read does not bypass avail index read. */
 322    if (num_heads) {
 323        smp_rmb();
 324    }
 325
 326    return num_heads;
 327}
 328
 329static unsigned int virtqueue_get_head(VirtQueue *vq, unsigned int idx)
 330{
 331    unsigned int head;
 332
 333    /* Grab the next descriptor number they're advertising, and increment
 334     * the index we've seen. */
 335    head = vring_avail_ring(vq, idx % vq->vring.num);
 336
 337    /* If their number is silly, that's a fatal mistake. */
 338    if (head >= vq->vring.num) {
 339        error_report("Guest says index %u is available", head);
 340        exit(1);
 341    }
 342
 343    return head;
 344}
 345
 346static unsigned virtqueue_read_next_desc(VirtIODevice *vdev, VRingDesc *desc,
 347                                         hwaddr desc_pa, unsigned int max)
 348{
 349    unsigned int next;
 350
 351    /* If this descriptor says it doesn't chain, we're done. */
 352    if (!(desc->flags & VRING_DESC_F_NEXT)) {
 353        return max;
 354    }
 355
 356    /* Check they're not leading us off end of descriptors. */
 357    next = desc->next;
 358    /* Make sure compiler knows to grab that: we don't want it changing! */
 359    smp_wmb();
 360
 361    if (next >= max) {
 362        error_report("Desc next is %u", next);
 363        exit(1);
 364    }
 365
 366    vring_desc_read(vdev, desc, desc_pa, next);
 367    return next;
 368}
 369
 370void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,
 371                               unsigned int *out_bytes,
 372                               unsigned max_in_bytes, unsigned max_out_bytes)
 373{
 374    unsigned int idx;
 375    unsigned int total_bufs, in_total, out_total;
 376
 377    idx = vq->last_avail_idx;
 378
 379    total_bufs = in_total = out_total = 0;
 380    while (virtqueue_num_heads(vq, idx)) {
 381        VirtIODevice *vdev = vq->vdev;
 382        unsigned int max, num_bufs, indirect = 0;
 383        VRingDesc desc;
 384        hwaddr desc_pa;
 385        int i;
 386
 387        max = vq->vring.num;
 388        num_bufs = total_bufs;
 389        i = virtqueue_get_head(vq, idx++);
 390        desc_pa = vq->vring.desc;
 391        vring_desc_read(vdev, &desc, desc_pa, i);
 392
 393        if (desc.flags & VRING_DESC_F_INDIRECT) {
 394            if (desc.len % sizeof(VRingDesc)) {
 395                error_report("Invalid size for indirect buffer table");
 396                exit(1);
 397            }
 398
 399            /* If we've got too many, that implies a descriptor loop. */
 400            if (num_bufs >= max) {
 401                error_report("Looped descriptor");
 402                exit(1);
 403            }
 404
 405            /* loop over the indirect descriptor table */
 406            indirect = 1;
 407            max = desc.len / sizeof(VRingDesc);
 408            desc_pa = desc.addr;
 409            num_bufs = i = 0;
 410            vring_desc_read(vdev, &desc, desc_pa, i);
 411        }
 412
 413        do {
 414            /* If we've got too many, that implies a descriptor loop. */
 415            if (++num_bufs > max) {
 416                error_report("Looped descriptor");
 417                exit(1);
 418            }
 419
 420            if (desc.flags & VRING_DESC_F_WRITE) {
 421                in_total += desc.len;
 422            } else {
 423                out_total += desc.len;
 424            }
 425            if (in_total >= max_in_bytes && out_total >= max_out_bytes) {
 426                goto done;
 427            }
 428        } while ((i = virtqueue_read_next_desc(vdev, &desc, desc_pa, max)) != max);
 429
 430        if (!indirect)
 431            total_bufs = num_bufs;
 432        else
 433            total_bufs++;
 434    }
 435done:
 436    if (in_bytes) {
 437        *in_bytes = in_total;
 438    }
 439    if (out_bytes) {
 440        *out_bytes = out_total;
 441    }
 442}
 443
 444int virtqueue_avail_bytes(VirtQueue *vq, unsigned int in_bytes,
 445                          unsigned int out_bytes)
 446{
 447    unsigned int in_total, out_total;
 448
 449    virtqueue_get_avail_bytes(vq, &in_total, &out_total, in_bytes, out_bytes);
 450    return in_bytes <= in_total && out_bytes <= out_total;
 451}
 452
 453static void virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov,
 454                               unsigned int max_num_sg, bool is_write,
 455                               hwaddr pa, size_t sz)
 456{
 457    unsigned num_sg = *p_num_sg;
 458    assert(num_sg <= max_num_sg);
 459
 460    while (sz) {
 461        hwaddr len = sz;
 462
 463        if (num_sg == max_num_sg) {
 464            error_report("virtio: too many write descriptors in indirect table");
 465            exit(1);
 466        }
 467
 468        iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write);
 469        iov[num_sg].iov_len = len;
 470        addr[num_sg] = pa;
 471
 472        sz -= len;
 473        pa += len;
 474        num_sg++;
 475    }
 476    *p_num_sg = num_sg;
 477}
 478
 479static void virtqueue_map_iovec(struct iovec *sg, hwaddr *addr,
 480                                unsigned int *num_sg, unsigned int max_size,
 481                                int is_write)
 482{
 483    unsigned int i;
 484    hwaddr len;
 485
 486    /* Note: this function MUST validate input, some callers
 487     * are passing in num_sg values received over the network.
 488     */
 489    /* TODO: teach all callers that this can fail, and return failure instead
 490     * of asserting here.
 491     * When we do, we might be able to re-enable NDEBUG below.
 492     */
 493#ifdef NDEBUG
 494#error building with NDEBUG is not supported
 495#endif
 496    assert(*num_sg <= max_size);
 497
 498    for (i = 0; i < *num_sg; i++) {
 499        len = sg[i].iov_len;
 500        sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write);
 501        if (!sg[i].iov_base) {
 502            error_report("virtio: error trying to map MMIO memory");
 503            exit(1);
 504        }
 505        if (len != sg[i].iov_len) {
 506            error_report("virtio: unexpected memory split");
 507            exit(1);
 508        }
 509    }
 510}
 511
 512void virtqueue_map(VirtQueueElement *elem)
 513{
 514    virtqueue_map_iovec(elem->in_sg, elem->in_addr, &elem->in_num,
 515                        VIRTQUEUE_MAX_SIZE, 1);
 516    virtqueue_map_iovec(elem->out_sg, elem->out_addr, &elem->out_num,
 517                        VIRTQUEUE_MAX_SIZE, 0);
 518}
 519
 520void *virtqueue_alloc_element(size_t sz, unsigned out_num, unsigned in_num)
 521{
 522    VirtQueueElement *elem;
 523    size_t in_addr_ofs = QEMU_ALIGN_UP(sz, __alignof__(elem->in_addr[0]));
 524    size_t out_addr_ofs = in_addr_ofs + in_num * sizeof(elem->in_addr[0]);
 525    size_t out_addr_end = out_addr_ofs + out_num * sizeof(elem->out_addr[0]);
 526    size_t in_sg_ofs = QEMU_ALIGN_UP(out_addr_end, __alignof__(elem->in_sg[0]));
 527    size_t out_sg_ofs = in_sg_ofs + in_num * sizeof(elem->in_sg[0]);
 528    size_t out_sg_end = out_sg_ofs + out_num * sizeof(elem->out_sg[0]);
 529
 530    assert(sz >= sizeof(VirtQueueElement));
 531    elem = g_malloc(out_sg_end);
 532    elem->out_num = out_num;
 533    elem->in_num = in_num;
 534    elem->in_addr = (void *)elem + in_addr_ofs;
 535    elem->out_addr = (void *)elem + out_addr_ofs;
 536    elem->in_sg = (void *)elem + in_sg_ofs;
 537    elem->out_sg = (void *)elem + out_sg_ofs;
 538    return elem;
 539}
 540
 541void *virtqueue_pop(VirtQueue *vq, size_t sz)
 542{
 543    unsigned int i, head, max;
 544    hwaddr desc_pa = vq->vring.desc;
 545    VirtIODevice *vdev = vq->vdev;
 546    VirtQueueElement *elem;
 547    unsigned out_num, in_num;
 548    hwaddr addr[VIRTQUEUE_MAX_SIZE];
 549    struct iovec iov[VIRTQUEUE_MAX_SIZE];
 550    VRingDesc desc;
 551
 552    if (virtio_queue_empty(vq)) {
 553        return NULL;
 554    }
 555    /* Needed after virtio_queue_empty(), see comment in
 556     * virtqueue_num_heads(). */
 557    smp_rmb();
 558
 559    /* When we start there are none of either input nor output. */
 560    out_num = in_num = 0;
 561
 562    max = vq->vring.num;
 563
 564    if (vq->inuse >= vq->vring.num) {
 565        error_report("Virtqueue size exceeded");
 566        exit(1);
 567    }
 568
 569    i = head = virtqueue_get_head(vq, vq->last_avail_idx++);
 570    if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
 571        vring_set_avail_event(vq, vq->last_avail_idx);
 572    }
 573
 574    vring_desc_read(vdev, &desc, desc_pa, i);
 575    if (desc.flags & VRING_DESC_F_INDIRECT) {
 576        if (desc.len % sizeof(VRingDesc)) {
 577            error_report("Invalid size for indirect buffer table");
 578            exit(1);
 579        }
 580
 581        /* loop over the indirect descriptor table */
 582        max = desc.len / sizeof(VRingDesc);
 583        desc_pa = desc.addr;
 584        i = 0;
 585        vring_desc_read(vdev, &desc, desc_pa, i);
 586    }
 587
 588    /* Collect all the descriptors */
 589    do {
 590        if (desc.flags & VRING_DESC_F_WRITE) {
 591            virtqueue_map_desc(&in_num, addr + out_num, iov + out_num,
 592                               VIRTQUEUE_MAX_SIZE - out_num, true, desc.addr, desc.len);
 593        } else {
 594            if (in_num) {
 595                error_report("Incorrect order for descriptors");
 596                exit(1);
 597            }
 598            virtqueue_map_desc(&out_num, addr, iov,
 599                               VIRTQUEUE_MAX_SIZE, false, desc.addr, desc.len);
 600        }
 601
 602        /* If we've got too many, that implies a descriptor loop. */
 603        if ((in_num + out_num) > max) {
 604            error_report("Looped descriptor");
 605            exit(1);
 606        }
 607    } while ((i = virtqueue_read_next_desc(vdev, &desc, desc_pa, max)) != max);
 608
 609    /* Now copy what we have collected and mapped */
 610    elem = virtqueue_alloc_element(sz, out_num, in_num);
 611    elem->index = head;
 612    for (i = 0; i < out_num; i++) {
 613        elem->out_addr[i] = addr[i];
 614        elem->out_sg[i] = iov[i];
 615    }
 616    for (i = 0; i < in_num; i++) {
 617        elem->in_addr[i] = addr[out_num + i];
 618        elem->in_sg[i] = iov[out_num + i];
 619    }
 620
 621    vq->inuse++;
 622
 623    trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
 624    return elem;
 625}
 626
 627/* Reading and writing a structure directly to QEMUFile is *awful*, but
 628 * it is what QEMU has always done by mistake.  We can change it sooner
 629 * or later by bumping the version number of the affected vm states.
 630 * In the meanwhile, since the in-memory layout of VirtQueueElement
 631 * has changed, we need to marshal to and from the layout that was
 632 * used before the change.
 633 */
 634typedef struct VirtQueueElementOld {
 635    unsigned int index;
 636    unsigned int out_num;
 637    unsigned int in_num;
 638    hwaddr in_addr[VIRTQUEUE_MAX_SIZE];
 639    hwaddr out_addr[VIRTQUEUE_MAX_SIZE];
 640    struct iovec in_sg[VIRTQUEUE_MAX_SIZE];
 641    struct iovec out_sg[VIRTQUEUE_MAX_SIZE];
 642} VirtQueueElementOld;
 643
 644void *qemu_get_virtqueue_element(QEMUFile *f, size_t sz)
 645{
 646    VirtQueueElement *elem;
 647    VirtQueueElementOld data;
 648    int i;
 649
 650    qemu_get_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
 651
 652    elem = virtqueue_alloc_element(sz, data.out_num, data.in_num);
 653    elem->index = data.index;
 654
 655    for (i = 0; i < elem->in_num; i++) {
 656        elem->in_addr[i] = data.in_addr[i];
 657    }
 658
 659    for (i = 0; i < elem->out_num; i++) {
 660        elem->out_addr[i] = data.out_addr[i];
 661    }
 662
 663    for (i = 0; i < elem->in_num; i++) {
 664        /* Base is overwritten by virtqueue_map.  */
 665        elem->in_sg[i].iov_base = 0;
 666        elem->in_sg[i].iov_len = data.in_sg[i].iov_len;
 667    }
 668
 669    for (i = 0; i < elem->out_num; i++) {
 670        /* Base is overwritten by virtqueue_map.  */
 671        elem->out_sg[i].iov_base = 0;
 672        elem->out_sg[i].iov_len = data.out_sg[i].iov_len;
 673    }
 674
 675    virtqueue_map(elem);
 676    return elem;
 677}
 678
 679void qemu_put_virtqueue_element(QEMUFile *f, VirtQueueElement *elem)
 680{
 681    VirtQueueElementOld data;
 682    int i;
 683
 684    memset(&data, 0, sizeof(data));
 685    data.index = elem->index;
 686    data.in_num = elem->in_num;
 687    data.out_num = elem->out_num;
 688
 689    for (i = 0; i < elem->in_num; i++) {
 690        data.in_addr[i] = elem->in_addr[i];
 691    }
 692
 693    for (i = 0; i < elem->out_num; i++) {
 694        data.out_addr[i] = elem->out_addr[i];
 695    }
 696
 697    for (i = 0; i < elem->in_num; i++) {
 698        /* Base is overwritten by virtqueue_map when loading.  Do not
 699         * save it, as it would leak the QEMU address space layout.  */
 700        data.in_sg[i].iov_len = elem->in_sg[i].iov_len;
 701    }
 702
 703    for (i = 0; i < elem->out_num; i++) {
 704        /* Do not save iov_base as above.  */
 705        data.out_sg[i].iov_len = elem->out_sg[i].iov_len;
 706    }
 707    qemu_put_buffer(f, (uint8_t *)&data, sizeof(VirtQueueElementOld));
 708}
 709
 710/* virtio device */
 711static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
 712{
 713    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
 714    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
 715
 716    if (k->notify) {
 717        k->notify(qbus->parent, vector);
 718    }
 719}
 720
 721void virtio_update_irq(VirtIODevice *vdev)
 722{
 723    virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
 724}
 725
 726static int virtio_validate_features(VirtIODevice *vdev)
 727{
 728    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 729
 730    if (k->validate_features) {
 731        return k->validate_features(vdev);
 732    } else {
 733        return 0;
 734    }
 735}
 736
 737int virtio_set_status(VirtIODevice *vdev, uint8_t val)
 738{
 739    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 740    trace_virtio_set_status(vdev, val);
 741
 742    if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
 743        if (!(vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) &&
 744            val & VIRTIO_CONFIG_S_FEATURES_OK) {
 745            int ret = virtio_validate_features(vdev);
 746
 747            if (ret) {
 748                return ret;
 749            }
 750        }
 751    }
 752    if (k->set_status) {
 753        k->set_status(vdev, val);
 754    }
 755    vdev->status = val;
 756    return 0;
 757}
 758
 759bool target_words_bigendian(void);
 760static enum virtio_device_endian virtio_default_endian(void)
 761{
 762    if (target_words_bigendian()) {
 763        return VIRTIO_DEVICE_ENDIAN_BIG;
 764    } else {
 765        return VIRTIO_DEVICE_ENDIAN_LITTLE;
 766    }
 767}
 768
 769static enum virtio_device_endian virtio_current_cpu_endian(void)
 770{
 771    CPUClass *cc = CPU_GET_CLASS(current_cpu);
 772
 773    if (cc->virtio_is_big_endian(current_cpu)) {
 774        return VIRTIO_DEVICE_ENDIAN_BIG;
 775    } else {
 776        return VIRTIO_DEVICE_ENDIAN_LITTLE;
 777    }
 778}
 779
 780void virtio_reset(void *opaque)
 781{
 782    VirtIODevice *vdev = opaque;
 783    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 784    int i;
 785
 786    virtio_set_status(vdev, 0);
 787    if (current_cpu) {
 788        /* Guest initiated reset */
 789        vdev->device_endian = virtio_current_cpu_endian();
 790    } else {
 791        /* System reset */
 792        vdev->device_endian = virtio_default_endian();
 793    }
 794
 795    if (k->reset) {
 796        k->reset(vdev);
 797    }
 798
 799    vdev->guest_features = 0;
 800    vdev->queue_sel = 0;
 801    vdev->status = 0;
 802    vdev->isr = 0;
 803    vdev->config_vector = VIRTIO_NO_VECTOR;
 804    virtio_notify_vector(vdev, vdev->config_vector);
 805
 806    for(i = 0; i < VIRTIO_QUEUE_MAX; i++) {
 807        vdev->vq[i].vring.desc = 0;
 808        vdev->vq[i].vring.avail = 0;
 809        vdev->vq[i].vring.used = 0;
 810        vdev->vq[i].last_avail_idx = 0;
 811        vdev->vq[i].shadow_avail_idx = 0;
 812        vdev->vq[i].used_idx = 0;
 813        virtio_queue_set_vector(vdev, i, VIRTIO_NO_VECTOR);
 814        vdev->vq[i].signalled_used = 0;
 815        vdev->vq[i].signalled_used_valid = false;
 816        vdev->vq[i].notification = true;
 817        vdev->vq[i].vring.num = vdev->vq[i].vring.num_default;
 818    }
 819}
 820
 821uint32_t virtio_config_readb(VirtIODevice *vdev, uint32_t addr)
 822{
 823    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 824    uint8_t val;
 825
 826    if (addr + sizeof(val) > vdev->config_len) {
 827        return (uint32_t)-1;
 828    }
 829
 830    k->get_config(vdev, vdev->config);
 831
 832    val = ldub_p(vdev->config + addr);
 833    return val;
 834}
 835
 836uint32_t virtio_config_readw(VirtIODevice *vdev, uint32_t addr)
 837{
 838    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 839    uint16_t val;
 840
 841    if (addr + sizeof(val) > vdev->config_len) {
 842        return (uint32_t)-1;
 843    }
 844
 845    k->get_config(vdev, vdev->config);
 846
 847    val = lduw_p(vdev->config + addr);
 848    return val;
 849}
 850
 851uint32_t virtio_config_readl(VirtIODevice *vdev, uint32_t addr)
 852{
 853    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 854    uint32_t val;
 855
 856    if (addr + sizeof(val) > vdev->config_len) {
 857        return (uint32_t)-1;
 858    }
 859
 860    k->get_config(vdev, vdev->config);
 861
 862    val = ldl_p(vdev->config + addr);
 863    return val;
 864}
 865
 866void virtio_config_writeb(VirtIODevice *vdev, uint32_t addr, uint32_t data)
 867{
 868    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 869    uint8_t val = data;
 870
 871    if (addr + sizeof(val) > vdev->config_len) {
 872        return;
 873    }
 874
 875    stb_p(vdev->config + addr, val);
 876
 877    if (k->set_config) {
 878        k->set_config(vdev, vdev->config);
 879    }
 880}
 881
 882void virtio_config_writew(VirtIODevice *vdev, uint32_t addr, uint32_t data)
 883{
 884    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 885    uint16_t val = data;
 886
 887    if (addr + sizeof(val) > vdev->config_len) {
 888        return;
 889    }
 890
 891    stw_p(vdev->config + addr, val);
 892
 893    if (k->set_config) {
 894        k->set_config(vdev, vdev->config);
 895    }
 896}
 897
 898void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)
 899{
 900    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 901    uint32_t val = data;
 902
 903    if (addr + sizeof(val) > vdev->config_len) {
 904        return;
 905    }
 906
 907    stl_p(vdev->config + addr, val);
 908
 909    if (k->set_config) {
 910        k->set_config(vdev, vdev->config);
 911    }
 912}
 913
 914uint32_t virtio_config_modern_readb(VirtIODevice *vdev, uint32_t addr)
 915{
 916    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 917    uint8_t val;
 918
 919    if (addr + sizeof(val) > vdev->config_len) {
 920        return (uint32_t)-1;
 921    }
 922
 923    k->get_config(vdev, vdev->config);
 924
 925    val = ldub_p(vdev->config + addr);
 926    return val;
 927}
 928
 929uint32_t virtio_config_modern_readw(VirtIODevice *vdev, uint32_t addr)
 930{
 931    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 932    uint16_t val;
 933
 934    if (addr + sizeof(val) > vdev->config_len) {
 935        return (uint32_t)-1;
 936    }
 937
 938    k->get_config(vdev, vdev->config);
 939
 940    val = lduw_le_p(vdev->config + addr);
 941    return val;
 942}
 943
 944uint32_t virtio_config_modern_readl(VirtIODevice *vdev, uint32_t addr)
 945{
 946    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 947    uint32_t val;
 948
 949    if (addr + sizeof(val) > vdev->config_len) {
 950        return (uint32_t)-1;
 951    }
 952
 953    k->get_config(vdev, vdev->config);
 954
 955    val = ldl_le_p(vdev->config + addr);
 956    return val;
 957}
 958
 959void virtio_config_modern_writeb(VirtIODevice *vdev,
 960                                 uint32_t addr, uint32_t data)
 961{
 962    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 963    uint8_t val = data;
 964
 965    if (addr + sizeof(val) > vdev->config_len) {
 966        return;
 967    }
 968
 969    stb_p(vdev->config + addr, val);
 970
 971    if (k->set_config) {
 972        k->set_config(vdev, vdev->config);
 973    }
 974}
 975
 976void virtio_config_modern_writew(VirtIODevice *vdev,
 977                                 uint32_t addr, uint32_t data)
 978{
 979    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 980    uint16_t val = data;
 981
 982    if (addr + sizeof(val) > vdev->config_len) {
 983        return;
 984    }
 985
 986    stw_le_p(vdev->config + addr, val);
 987
 988    if (k->set_config) {
 989        k->set_config(vdev, vdev->config);
 990    }
 991}
 992
 993void virtio_config_modern_writel(VirtIODevice *vdev,
 994                                 uint32_t addr, uint32_t data)
 995{
 996    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
 997    uint32_t val = data;
 998
 999    if (addr + sizeof(val) > vdev->config_len) {
1000        return;
1001    }
1002
1003    stl_le_p(vdev->config + addr, val);
1004
1005    if (k->set_config) {
1006        k->set_config(vdev, vdev->config);
1007    }
1008}
1009
1010void virtio_queue_set_addr(VirtIODevice *vdev, int n, hwaddr addr)
1011{
1012    vdev->vq[n].vring.desc = addr;
1013    virtio_queue_update_rings(vdev, n);
1014}
1015
1016hwaddr virtio_queue_get_addr(VirtIODevice *vdev, int n)
1017{
1018    return vdev->vq[n].vring.desc;
1019}
1020
1021void virtio_queue_set_rings(VirtIODevice *vdev, int n, hwaddr desc,
1022                            hwaddr avail, hwaddr used)
1023{
1024    vdev->vq[n].vring.desc = desc;
1025    vdev->vq[n].vring.avail = avail;
1026    vdev->vq[n].vring.used = used;
1027}
1028
1029void virtio_queue_set_num(VirtIODevice *vdev, int n, int num)
1030{
1031    /* Don't allow guest to flip queue between existent and
1032     * nonexistent states, or to set it to an invalid size.
1033     */
1034    if (!!num != !!vdev->vq[n].vring.num ||
1035        num > VIRTQUEUE_MAX_SIZE ||
1036        num < 0) {
1037        return;
1038    }
1039    vdev->vq[n].vring.num = num;
1040}
1041
1042VirtQueue *virtio_vector_first_queue(VirtIODevice *vdev, uint16_t vector)
1043{
1044    return QLIST_FIRST(&vdev->vector_queues[vector]);
1045}
1046
1047VirtQueue *virtio_vector_next_queue(VirtQueue *vq)
1048{
1049    return QLIST_NEXT(vq, node);
1050}
1051
1052int virtio_queue_get_num(VirtIODevice *vdev, int n)
1053{
1054    return vdev->vq[n].vring.num;
1055}
1056
1057int virtio_get_num_queues(VirtIODevice *vdev)
1058{
1059    int i;
1060
1061    for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1062        if (!virtio_queue_get_num(vdev, i)) {
1063            break;
1064        }
1065    }
1066
1067    return i;
1068}
1069
1070int virtio_queue_get_id(VirtQueue *vq)
1071{
1072    VirtIODevice *vdev = vq->vdev;
1073    assert(vq >= &vdev->vq[0] && vq < &vdev->vq[VIRTIO_QUEUE_MAX]);
1074    return vq - &vdev->vq[0];
1075}
1076
1077void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)
1078{
1079    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1080    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1081
1082    /* virtio-1 compliant devices cannot change the alignment */
1083    if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1084        error_report("tried to modify queue alignment for virtio-1 device");
1085        return;
1086    }
1087    /* Check that the transport told us it was going to do this
1088     * (so a buggy transport will immediately assert rather than
1089     * silently failing to migrate this state)
1090     */
1091    assert(k->has_variable_vring_alignment);
1092
1093    vdev->vq[n].vring.align = align;
1094    virtio_queue_update_rings(vdev, n);
1095}
1096
1097static void virtio_queue_notify_aio_vq(VirtQueue *vq)
1098{
1099    if (vq->vring.desc && vq->handle_aio_output) {
1100        VirtIODevice *vdev = vq->vdev;
1101
1102        trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
1103        vq->handle_aio_output(vdev, vq);
1104    }
1105}
1106
1107static void virtio_queue_notify_vq(VirtQueue *vq)
1108{
1109    if (vq->vring.desc && vq->handle_output) {
1110        VirtIODevice *vdev = vq->vdev;
1111
1112        trace_virtio_queue_notify(vdev, vq - vdev->vq, vq);
1113        vq->handle_output(vdev, vq);
1114    }
1115}
1116
1117void virtio_queue_notify(VirtIODevice *vdev, int n)
1118{
1119    virtio_queue_notify_vq(&vdev->vq[n]);
1120}
1121
1122uint16_t virtio_queue_vector(VirtIODevice *vdev, int n)
1123{
1124    return n < VIRTIO_QUEUE_MAX ? vdev->vq[n].vector :
1125        VIRTIO_NO_VECTOR;
1126}
1127
1128void virtio_queue_set_vector(VirtIODevice *vdev, int n, uint16_t vector)
1129{
1130    VirtQueue *vq = &vdev->vq[n];
1131
1132    if (n < VIRTIO_QUEUE_MAX) {
1133        if (vdev->vector_queues &&
1134            vdev->vq[n].vector != VIRTIO_NO_VECTOR) {
1135            QLIST_REMOVE(vq, node);
1136        }
1137        vdev->vq[n].vector = vector;
1138        if (vdev->vector_queues &&
1139            vector != VIRTIO_NO_VECTOR) {
1140            QLIST_INSERT_HEAD(&vdev->vector_queues[vector], vq, node);
1141        }
1142    }
1143}
1144
1145VirtQueue *virtio_add_queue(VirtIODevice *vdev, int queue_size,
1146                            void (*handle_output)(VirtIODevice *, VirtQueue *))
1147{
1148    int i;
1149
1150    for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1151        if (vdev->vq[i].vring.num == 0)
1152            break;
1153    }
1154
1155    if (i == VIRTIO_QUEUE_MAX || queue_size > VIRTQUEUE_MAX_SIZE)
1156        abort();
1157
1158    vdev->vq[i].vring.num = queue_size;
1159    vdev->vq[i].vring.num_default = queue_size;
1160    vdev->vq[i].vring.align = VIRTIO_PCI_VRING_ALIGN;
1161    vdev->vq[i].handle_output = handle_output;
1162    vdev->vq[i].handle_aio_output = NULL;
1163
1164    return &vdev->vq[i];
1165}
1166
1167void virtio_del_queue(VirtIODevice *vdev, int n)
1168{
1169    if (n < 0 || n >= VIRTIO_QUEUE_MAX) {
1170        abort();
1171    }
1172
1173    vdev->vq[n].vring.num = 0;
1174    vdev->vq[n].vring.num_default = 0;
1175}
1176
1177void virtio_irq(VirtQueue *vq)
1178{
1179    trace_virtio_irq(vq);
1180    vq->vdev->isr |= 0x01;
1181    virtio_notify_vector(vq->vdev, vq->vector);
1182}
1183
1184bool virtio_should_notify(VirtIODevice *vdev, VirtQueue *vq)
1185{
1186    uint16_t old, new;
1187    bool v;
1188    /* We need to expose used array entries before checking used event. */
1189    smp_mb();
1190    /* Always notify when queue is empty (when feature acknowledge) */
1191    if (virtio_vdev_has_feature(vdev, VIRTIO_F_NOTIFY_ON_EMPTY) &&
1192        !vq->inuse && virtio_queue_empty(vq)) {
1193        return true;
1194    }
1195
1196    if (!virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
1197        return !(vring_avail_flags(vq) & VRING_AVAIL_F_NO_INTERRUPT);
1198    }
1199
1200    v = vq->signalled_used_valid;
1201    vq->signalled_used_valid = true;
1202    old = vq->signalled_used;
1203    new = vq->signalled_used = vq->used_idx;
1204    return !v || vring_need_event(vring_get_used_event(vq), new, old);
1205}
1206
1207void virtio_notify(VirtIODevice *vdev, VirtQueue *vq)
1208{
1209    if (!virtio_should_notify(vdev, vq)) {
1210        return;
1211    }
1212
1213    trace_virtio_notify(vdev, vq);
1214    vdev->isr |= 0x01;
1215    virtio_notify_vector(vdev, vq->vector);
1216}
1217
1218void virtio_notify_config(VirtIODevice *vdev)
1219{
1220    if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))
1221        return;
1222
1223    vdev->isr |= 0x03;
1224    vdev->generation++;
1225    virtio_notify_vector(vdev, vdev->config_vector);
1226}
1227
1228static bool virtio_device_endian_needed(void *opaque)
1229{
1230    VirtIODevice *vdev = opaque;
1231
1232    assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN);
1233    if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1234        return vdev->device_endian != virtio_default_endian();
1235    }
1236    /* Devices conforming to VIRTIO 1.0 or later are always LE. */
1237    return vdev->device_endian != VIRTIO_DEVICE_ENDIAN_LITTLE;
1238}
1239
1240static bool virtio_64bit_features_needed(void *opaque)
1241{
1242    VirtIODevice *vdev = opaque;
1243
1244    return (vdev->host_features >> 32) != 0;
1245}
1246
1247static bool virtio_virtqueue_needed(void *opaque)
1248{
1249    VirtIODevice *vdev = opaque;
1250
1251    return virtio_host_has_feature(vdev, VIRTIO_F_VERSION_1);
1252}
1253
1254static bool virtio_ringsize_needed(void *opaque)
1255{
1256    VirtIODevice *vdev = opaque;
1257    int i;
1258
1259    for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1260        if (vdev->vq[i].vring.num != vdev->vq[i].vring.num_default) {
1261            return true;
1262        }
1263    }
1264    return false;
1265}
1266
1267static bool virtio_extra_state_needed(void *opaque)
1268{
1269    VirtIODevice *vdev = opaque;
1270    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1271    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1272
1273    return k->has_extra_state &&
1274        k->has_extra_state(qbus->parent);
1275}
1276
1277static const VMStateDescription vmstate_virtqueue = {
1278    .name = "virtqueue_state",
1279    .version_id = 1,
1280    .minimum_version_id = 1,
1281    .fields = (VMStateField[]) {
1282        VMSTATE_UINT64(vring.avail, struct VirtQueue),
1283        VMSTATE_UINT64(vring.used, struct VirtQueue),
1284        VMSTATE_END_OF_LIST()
1285    }
1286};
1287
1288static const VMStateDescription vmstate_virtio_virtqueues = {
1289    .name = "virtio/virtqueues",
1290    .version_id = 1,
1291    .minimum_version_id = 1,
1292    .needed = &virtio_virtqueue_needed,
1293    .fields = (VMStateField[]) {
1294        VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
1295                      VIRTIO_QUEUE_MAX, 0, vmstate_virtqueue, VirtQueue),
1296        VMSTATE_END_OF_LIST()
1297    }
1298};
1299
1300static const VMStateDescription vmstate_ringsize = {
1301    .name = "ringsize_state",
1302    .version_id = 1,
1303    .minimum_version_id = 1,
1304    .fields = (VMStateField[]) {
1305        VMSTATE_UINT32(vring.num_default, struct VirtQueue),
1306        VMSTATE_END_OF_LIST()
1307    }
1308};
1309
1310static const VMStateDescription vmstate_virtio_ringsize = {
1311    .name = "virtio/ringsize",
1312    .version_id = 1,
1313    .minimum_version_id = 1,
1314    .needed = &virtio_ringsize_needed,
1315    .fields = (VMStateField[]) {
1316        VMSTATE_STRUCT_VARRAY_POINTER_KNOWN(vq, struct VirtIODevice,
1317                      VIRTIO_QUEUE_MAX, 0, vmstate_ringsize, VirtQueue),
1318        VMSTATE_END_OF_LIST()
1319    }
1320};
1321
1322static int get_extra_state(QEMUFile *f, void *pv, size_t size)
1323{
1324    VirtIODevice *vdev = pv;
1325    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1326    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1327
1328    if (!k->load_extra_state) {
1329        return -1;
1330    } else {
1331        return k->load_extra_state(qbus->parent, f);
1332    }
1333}
1334
1335static void put_extra_state(QEMUFile *f, void *pv, size_t size)
1336{
1337    VirtIODevice *vdev = pv;
1338    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1339    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1340
1341    k->save_extra_state(qbus->parent, f);
1342}
1343
1344static const VMStateInfo vmstate_info_extra_state = {
1345    .name = "virtqueue_extra_state",
1346    .get = get_extra_state,
1347    .put = put_extra_state,
1348};
1349
1350static const VMStateDescription vmstate_virtio_extra_state = {
1351    .name = "virtio/extra_state",
1352    .version_id = 1,
1353    .minimum_version_id = 1,
1354    .needed = &virtio_extra_state_needed,
1355    .fields = (VMStateField[]) {
1356        {
1357            .name         = "extra_state",
1358            .version_id   = 0,
1359            .field_exists = NULL,
1360            .size         = 0,
1361            .info         = &vmstate_info_extra_state,
1362            .flags        = VMS_SINGLE,
1363            .offset       = 0,
1364        },
1365        VMSTATE_END_OF_LIST()
1366    }
1367};
1368
1369static const VMStateDescription vmstate_virtio_device_endian = {
1370    .name = "virtio/device_endian",
1371    .version_id = 1,
1372    .minimum_version_id = 1,
1373    .needed = &virtio_device_endian_needed,
1374    .fields = (VMStateField[]) {
1375        VMSTATE_UINT8(device_endian, VirtIODevice),
1376        VMSTATE_END_OF_LIST()
1377    }
1378};
1379
1380static const VMStateDescription vmstate_virtio_64bit_features = {
1381    .name = "virtio/64bit_features",
1382    .version_id = 1,
1383    .minimum_version_id = 1,
1384    .needed = &virtio_64bit_features_needed,
1385    .fields = (VMStateField[]) {
1386        VMSTATE_UINT64(guest_features, VirtIODevice),
1387        VMSTATE_END_OF_LIST()
1388    }
1389};
1390
1391static const VMStateDescription vmstate_virtio = {
1392    .name = "virtio",
1393    .version_id = 1,
1394    .minimum_version_id = 1,
1395    .minimum_version_id_old = 1,
1396    .fields = (VMStateField[]) {
1397        VMSTATE_END_OF_LIST()
1398    },
1399    .subsections = (const VMStateDescription*[]) {
1400        &vmstate_virtio_device_endian,
1401        &vmstate_virtio_64bit_features,
1402        &vmstate_virtio_virtqueues,
1403        &vmstate_virtio_ringsize,
1404        &vmstate_virtio_extra_state,
1405        NULL
1406    }
1407};
1408
1409void virtio_save(VirtIODevice *vdev, QEMUFile *f)
1410{
1411    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1412    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1413    VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
1414    uint32_t guest_features_lo = (vdev->guest_features & 0xffffffff);
1415    int i;
1416
1417    if (k->save_config) {
1418        k->save_config(qbus->parent, f);
1419    }
1420
1421    qemu_put_8s(f, &vdev->status);
1422    qemu_put_8s(f, &vdev->isr);
1423    qemu_put_be16s(f, &vdev->queue_sel);
1424    qemu_put_be32s(f, &guest_features_lo);
1425    qemu_put_be32(f, vdev->config_len);
1426    qemu_put_buffer(f, vdev->config, vdev->config_len);
1427
1428    for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1429        if (vdev->vq[i].vring.num == 0)
1430            break;
1431    }
1432
1433    qemu_put_be32(f, i);
1434
1435    for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1436        if (vdev->vq[i].vring.num == 0)
1437            break;
1438
1439        qemu_put_be32(f, vdev->vq[i].vring.num);
1440        if (k->has_variable_vring_alignment) {
1441            qemu_put_be32(f, vdev->vq[i].vring.align);
1442        }
1443        /* XXX virtio-1 devices */
1444        qemu_put_be64(f, vdev->vq[i].vring.desc);
1445        qemu_put_be16s(f, &vdev->vq[i].last_avail_idx);
1446        if (k->save_queue) {
1447            k->save_queue(qbus->parent, i, f);
1448        }
1449    }
1450
1451    if (vdc->save != NULL) {
1452        vdc->save(vdev, f);
1453    }
1454
1455    /* Subsections */
1456    vmstate_save_state(f, &vmstate_virtio, vdev, NULL);
1457}
1458
1459static int virtio_set_features_nocheck(VirtIODevice *vdev, uint64_t val)
1460{
1461    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
1462    bool bad = (val & ~(vdev->host_features)) != 0;
1463
1464    val &= vdev->host_features;
1465    if (k->set_features) {
1466        k->set_features(vdev, val);
1467    }
1468    vdev->guest_features = val;
1469    return bad ? -1 : 0;
1470}
1471
1472int virtio_set_features(VirtIODevice *vdev, uint64_t val)
1473{
1474   /*
1475     * The driver must not attempt to set features after feature negotiation
1476     * has finished.
1477     */
1478    if (vdev->status & VIRTIO_CONFIG_S_FEATURES_OK) {
1479        return -EINVAL;
1480    }
1481    return virtio_set_features_nocheck(vdev, val);
1482}
1483
1484int virtio_load(VirtIODevice *vdev, QEMUFile *f, int version_id)
1485{
1486    int i, ret;
1487    int32_t config_len;
1488    uint32_t num;
1489    uint32_t features;
1490    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1491    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1492    VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);
1493
1494    /*
1495     * We poison the endianness to ensure it does not get used before
1496     * subsections have been loaded.
1497     */
1498    vdev->device_endian = VIRTIO_DEVICE_ENDIAN_UNKNOWN;
1499
1500    if (k->load_config) {
1501        ret = k->load_config(qbus->parent, f);
1502        if (ret)
1503            return ret;
1504    }
1505
1506    qemu_get_8s(f, &vdev->status);
1507    qemu_get_8s(f, &vdev->isr);
1508    qemu_get_be16s(f, &vdev->queue_sel);
1509    if (vdev->queue_sel >= VIRTIO_QUEUE_MAX) {
1510        return -1;
1511    }
1512    qemu_get_be32s(f, &features);
1513
1514    /*
1515     * Temporarily set guest_features low bits - needed by
1516     * virtio net load code testing for VIRTIO_NET_F_CTRL_GUEST_OFFLOADS
1517     * VIRTIO_NET_F_GUEST_ANNOUNCE and VIRTIO_NET_F_CTRL_VQ.
1518     *
1519     * Note: devices should always test host features in future - don't create
1520     * new dependencies like this.
1521     */
1522    vdev->guest_features = features;
1523
1524    config_len = qemu_get_be32(f);
1525
1526    /*
1527     * There are cases where the incoming config can be bigger or smaller
1528     * than what we have; so load what we have space for, and skip
1529     * any excess that's in the stream.
1530     */
1531    qemu_get_buffer(f, vdev->config, MIN(config_len, vdev->config_len));
1532
1533    while (config_len > vdev->config_len) {
1534        qemu_get_byte(f);
1535        config_len--;
1536    }
1537
1538    num = qemu_get_be32(f);
1539
1540    if (num > VIRTIO_QUEUE_MAX) {
1541        error_report("Invalid number of virtqueues: 0x%x", num);
1542        return -1;
1543    }
1544
1545    for (i = 0; i < num; i++) {
1546        vdev->vq[i].vring.num = qemu_get_be32(f);
1547        if (k->has_variable_vring_alignment) {
1548            vdev->vq[i].vring.align = qemu_get_be32(f);
1549        }
1550        vdev->vq[i].vring.desc = qemu_get_be64(f);
1551        qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
1552        vdev->vq[i].signalled_used_valid = false;
1553        vdev->vq[i].notification = true;
1554
1555        if (vdev->vq[i].vring.desc) {
1556            /* XXX virtio-1 devices */
1557            virtio_queue_update_rings(vdev, i);
1558        } else if (vdev->vq[i].last_avail_idx) {
1559            error_report("VQ %d address 0x0 "
1560                         "inconsistent with Host index 0x%x",
1561                         i, vdev->vq[i].last_avail_idx);
1562                return -1;
1563        }
1564        if (k->load_queue) {
1565            ret = k->load_queue(qbus->parent, i, f);
1566            if (ret)
1567                return ret;
1568        }
1569    }
1570
1571    virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
1572
1573    if (vdc->load != NULL) {
1574        ret = vdc->load(vdev, f, version_id);
1575        if (ret) {
1576            return ret;
1577        }
1578    }
1579
1580    /* Subsections */
1581    ret = vmstate_load_state(f, &vmstate_virtio, vdev, 1);
1582    if (ret) {
1583        return ret;
1584    }
1585
1586    if (vdev->device_endian == VIRTIO_DEVICE_ENDIAN_UNKNOWN) {
1587        vdev->device_endian = virtio_default_endian();
1588    }
1589
1590    if (virtio_64bit_features_needed(vdev)) {
1591        /*
1592         * Subsection load filled vdev->guest_features.  Run them
1593         * through virtio_set_features to sanity-check them against
1594         * host_features.
1595         */
1596        uint64_t features64 = vdev->guest_features;
1597        if (virtio_set_features_nocheck(vdev, features64) < 0) {
1598            error_report("Features 0x%" PRIx64 " unsupported. "
1599                         "Allowed features: 0x%" PRIx64,
1600                         features64, vdev->host_features);
1601            return -1;
1602        }
1603    } else {
1604        if (virtio_set_features_nocheck(vdev, features) < 0) {
1605            error_report("Features 0x%x unsupported. "
1606                         "Allowed features: 0x%" PRIx64,
1607                         features, vdev->host_features);
1608            return -1;
1609        }
1610    }
1611
1612    for (i = 0; i < num; i++) {
1613        if (vdev->vq[i].vring.desc) {
1614            uint16_t nheads;
1615            nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
1616            /* Check it isn't doing strange things with descriptor numbers. */
1617            if (nheads > vdev->vq[i].vring.num) {
1618                error_report("VQ %d size 0x%x Guest index 0x%x "
1619                             "inconsistent with Host index 0x%x: delta 0x%x",
1620                             i, vdev->vq[i].vring.num,
1621                             vring_avail_idx(&vdev->vq[i]),
1622                             vdev->vq[i].last_avail_idx, nheads);
1623                return -1;
1624            }
1625            vdev->vq[i].used_idx = vring_used_idx(&vdev->vq[i]);
1626            vdev->vq[i].shadow_avail_idx = vring_avail_idx(&vdev->vq[i]);
1627        }
1628    }
1629
1630    return 0;
1631}
1632
1633void virtio_cleanup(VirtIODevice *vdev)
1634{
1635    qemu_del_vm_change_state_handler(vdev->vmstate);
1636    g_free(vdev->config);
1637    g_free(vdev->vq);
1638    g_free(vdev->vector_queues);
1639}
1640
1641static void virtio_vmstate_change(void *opaque, int running, RunState state)
1642{
1643    VirtIODevice *vdev = opaque;
1644    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1645    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1646    bool backend_run = running && (vdev->status & VIRTIO_CONFIG_S_DRIVER_OK);
1647    vdev->vm_running = running;
1648
1649    if (backend_run) {
1650        virtio_set_status(vdev, vdev->status);
1651    }
1652
1653    if (k->vmstate_change) {
1654        k->vmstate_change(qbus->parent, backend_run);
1655    }
1656
1657    if (!backend_run) {
1658        virtio_set_status(vdev, vdev->status);
1659    }
1660}
1661
1662void virtio_instance_init_common(Object *proxy_obj, void *data,
1663                                 size_t vdev_size, const char *vdev_name)
1664{
1665    DeviceState *vdev = data;
1666
1667    object_initialize(vdev, vdev_size, vdev_name);
1668    object_property_add_child(proxy_obj, "virtio-backend", OBJECT(vdev), NULL);
1669    object_unref(OBJECT(vdev));
1670    qdev_alias_all_properties(vdev, proxy_obj);
1671}
1672
1673void virtio_init(VirtIODevice *vdev, const char *name,
1674                 uint16_t device_id, size_t config_size)
1675{
1676    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
1677    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
1678    int i;
1679    int nvectors = k->query_nvectors ? k->query_nvectors(qbus->parent) : 0;
1680
1681    if (nvectors) {
1682        vdev->vector_queues =
1683            g_malloc0(sizeof(*vdev->vector_queues) * nvectors);
1684    }
1685
1686    vdev->device_id = device_id;
1687    vdev->status = 0;
1688    vdev->isr = 0;
1689    vdev->queue_sel = 0;
1690    vdev->config_vector = VIRTIO_NO_VECTOR;
1691    vdev->vq = g_malloc0(sizeof(VirtQueue) * VIRTIO_QUEUE_MAX);
1692    vdev->vm_running = runstate_is_running();
1693    for (i = 0; i < VIRTIO_QUEUE_MAX; i++) {
1694        vdev->vq[i].vector = VIRTIO_NO_VECTOR;
1695        vdev->vq[i].vdev = vdev;
1696        vdev->vq[i].queue_index = i;
1697    }
1698
1699    vdev->name = name;
1700    vdev->config_len = config_size;
1701    if (vdev->config_len) {
1702        vdev->config = g_malloc0(config_size);
1703    } else {
1704        vdev->config = NULL;
1705    }
1706    vdev->vmstate = qemu_add_vm_change_state_handler(virtio_vmstate_change,
1707                                                     vdev);
1708    vdev->device_endian = virtio_default_endian();
1709    vdev->use_guest_notifier_mask = true;
1710}
1711
1712hwaddr virtio_queue_get_desc_addr(VirtIODevice *vdev, int n)
1713{
1714    return vdev->vq[n].vring.desc;
1715}
1716
1717hwaddr virtio_queue_get_avail_addr(VirtIODevice *vdev, int n)
1718{
1719    return vdev->vq[n].vring.avail;
1720}
1721
1722hwaddr virtio_queue_get_used_addr(VirtIODevice *vdev, int n)
1723{
1724    return vdev->vq[n].vring.used;
1725}
1726
1727hwaddr virtio_queue_get_ring_addr(VirtIODevice *vdev, int n)
1728{
1729    return vdev->vq[n].vring.desc;
1730}
1731
1732hwaddr virtio_queue_get_desc_size(VirtIODevice *vdev, int n)
1733{
1734    return sizeof(VRingDesc) * vdev->vq[n].vring.num;
1735}
1736
1737hwaddr virtio_queue_get_avail_size(VirtIODevice *vdev, int n)
1738{
1739    return offsetof(VRingAvail, ring) +
1740        sizeof(uint16_t) * vdev->vq[n].vring.num;
1741}
1742
1743hwaddr virtio_queue_get_used_size(VirtIODevice *vdev, int n)
1744{
1745    return offsetof(VRingUsed, ring) +
1746        sizeof(VRingUsedElem) * vdev->vq[n].vring.num;
1747}
1748
1749hwaddr virtio_queue_get_ring_size(VirtIODevice *vdev, int n)
1750{
1751    return vdev->vq[n].vring.used - vdev->vq[n].vring.desc +
1752            virtio_queue_get_used_size(vdev, n);
1753}
1754
1755uint16_t virtio_queue_get_last_avail_idx(VirtIODevice *vdev, int n)
1756{
1757    return vdev->vq[n].last_avail_idx;
1758}
1759
1760void virtio_queue_set_last_avail_idx(VirtIODevice *vdev, int n, uint16_t idx)
1761{
1762    vdev->vq[n].last_avail_idx = idx;
1763    vdev->vq[n].shadow_avail_idx = idx;
1764}
1765
1766void virtio_queue_invalidate_signalled_used(VirtIODevice *vdev, int n)
1767{
1768    vdev->vq[n].signalled_used_valid = false;
1769}
1770
1771VirtQueue *virtio_get_queue(VirtIODevice *vdev, int n)
1772{
1773    return vdev->vq + n;
1774}
1775
1776uint16_t virtio_get_queue_index(VirtQueue *vq)
1777{
1778    return vq->queue_index;
1779}
1780
1781static void virtio_queue_guest_notifier_read(EventNotifier *n)
1782{
1783    VirtQueue *vq = container_of(n, VirtQueue, guest_notifier);
1784    if (event_notifier_test_and_clear(n)) {
1785        virtio_irq(vq);
1786    }
1787}
1788
1789void virtio_queue_set_guest_notifier_fd_handler(VirtQueue *vq, bool assign,
1790                                                bool with_irqfd)
1791{
1792    if (assign && !with_irqfd) {
1793        event_notifier_set_handler(&vq->guest_notifier, false,
1794                                   virtio_queue_guest_notifier_read);
1795    } else {
1796        event_notifier_set_handler(&vq->guest_notifier, false, NULL);
1797    }
1798    if (!assign) {
1799        /* Test and clear notifier before closing it,
1800         * in case poll callback didn't have time to run. */
1801        virtio_queue_guest_notifier_read(&vq->guest_notifier);
1802    }
1803}
1804
1805EventNotifier *virtio_queue_get_guest_notifier(VirtQueue *vq)
1806{
1807    return &vq->guest_notifier;
1808}
1809
1810static void virtio_queue_host_notifier_aio_read(EventNotifier *n)
1811{
1812    VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
1813    if (event_notifier_test_and_clear(n)) {
1814        virtio_queue_notify_aio_vq(vq);
1815    }
1816}
1817
1818void virtio_queue_aio_set_host_notifier_handler(VirtQueue *vq, AioContext *ctx,
1819                                                void (*handle_output)(VirtIODevice *,
1820                                                                      VirtQueue *))
1821{
1822    if (handle_output) {
1823        vq->handle_aio_output = handle_output;
1824        aio_set_event_notifier(ctx, &vq->host_notifier, true,
1825                               virtio_queue_host_notifier_aio_read);
1826    } else {
1827        aio_set_event_notifier(ctx, &vq->host_notifier, true, NULL);
1828        /* Test and clear notifier before after disabling event,
1829         * in case poll callback didn't have time to run. */
1830        virtio_queue_host_notifier_aio_read(&vq->host_notifier);
1831        vq->handle_aio_output = NULL;
1832    }
1833}
1834
1835static void virtio_queue_host_notifier_read(EventNotifier *n)
1836{
1837    VirtQueue *vq = container_of(n, VirtQueue, host_notifier);
1838    if (event_notifier_test_and_clear(n)) {
1839        virtio_queue_notify_vq(vq);
1840    }
1841}
1842
1843void virtio_queue_set_host_notifier_fd_handler(VirtQueue *vq, bool assign,
1844                                               bool set_handler)
1845{
1846    if (assign && set_handler) {
1847        event_notifier_set_handler(&vq->host_notifier, true,
1848                                   virtio_queue_host_notifier_read);
1849    } else {
1850        event_notifier_set_handler(&vq->host_notifier, true, NULL);
1851    }
1852    if (!assign) {
1853        /* Test and clear notifier before after disabling event,
1854         * in case poll callback didn't have time to run. */
1855        virtio_queue_host_notifier_read(&vq->host_notifier);
1856    }
1857}
1858
1859EventNotifier *virtio_queue_get_host_notifier(VirtQueue *vq)
1860{
1861    return &vq->host_notifier;
1862}
1863
1864void virtio_device_set_child_bus_name(VirtIODevice *vdev, char *bus_name)
1865{
1866    g_free(vdev->bus_name);
1867    vdev->bus_name = g_strdup(bus_name);
1868}
1869
1870static void virtio_device_realize(DeviceState *dev, Error **errp)
1871{
1872    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1873    VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
1874    Error *err = NULL;
1875
1876    if (vdc->realize != NULL) {
1877        vdc->realize(dev, &err);
1878        if (err != NULL) {
1879            error_propagate(errp, err);
1880            return;
1881        }
1882    }
1883
1884    virtio_bus_device_plugged(vdev, &err);
1885    if (err != NULL) {
1886        error_propagate(errp, err);
1887        return;
1888    }
1889}
1890
1891static void virtio_device_unrealize(DeviceState *dev, Error **errp)
1892{
1893    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1894    VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
1895    Error *err = NULL;
1896
1897    virtio_bus_device_unplugged(vdev);
1898
1899    if (vdc->unrealize != NULL) {
1900        vdc->unrealize(dev, &err);
1901        if (err != NULL) {
1902            error_propagate(errp, err);
1903            return;
1904        }
1905    }
1906
1907    g_free(vdev->bus_name);
1908    vdev->bus_name = NULL;
1909}
1910
1911static Property virtio_properties[] = {
1912    DEFINE_VIRTIO_COMMON_FEATURES(VirtIODevice, host_features),
1913    DEFINE_PROP_END_OF_LIST(),
1914};
1915
1916static void virtio_device_class_init(ObjectClass *klass, void *data)
1917{
1918    /* Set the default value here. */
1919    DeviceClass *dc = DEVICE_CLASS(klass);
1920
1921    dc->realize = virtio_device_realize;
1922    dc->unrealize = virtio_device_unrealize;
1923    dc->bus_type = TYPE_VIRTIO_BUS;
1924    dc->props = virtio_properties;
1925}
1926
1927static const TypeInfo virtio_device_info = {
1928    .name = TYPE_VIRTIO_DEVICE,
1929    .parent = TYPE_DEVICE,
1930    .instance_size = sizeof(VirtIODevice),
1931    .class_init = virtio_device_class_init,
1932    .abstract = true,
1933    .class_size = sizeof(VirtioDeviceClass),
1934};
1935
1936static void virtio_register_types(void)
1937{
1938    type_register_static(&virtio_device_info);
1939}
1940
1941type_init(virtio_register_types)
1942