qemu/hw/net/virtio-net.c
<<
>>
Prefs
   1/*
   2 * Virtio Network Device
   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 "qemu/iov.h"
  16#include "hw/virtio/virtio.h"
  17#include "net/net.h"
  18#include "net/checksum.h"
  19#include "net/tap.h"
  20#include "qemu/error-report.h"
  21#include "qemu/timer.h"
  22#include "hw/virtio/virtio-net.h"
  23#include "net/vhost_net.h"
  24#include "hw/virtio/virtio-bus.h"
  25#include "qapi/qmp/qjson.h"
  26#include "qapi-event.h"
  27#include "hw/virtio/virtio-access.h"
  28#include "migration/misc.h"
  29
  30#define VIRTIO_NET_VM_VERSION    11
  31
  32#define MAC_TABLE_ENTRIES    64
  33#define MAX_VLAN    (1 << 12)   /* Per 802.1Q definition */
  34
  35/* previously fixed value */
  36#define VIRTIO_NET_RX_QUEUE_DEFAULT_SIZE 256
  37#define VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE 256
  38
  39/* for now, only allow larger queues; with virtio-1, guest can downsize */
  40#define VIRTIO_NET_RX_QUEUE_MIN_SIZE VIRTIO_NET_RX_QUEUE_DEFAULT_SIZE
  41#define VIRTIO_NET_TX_QUEUE_MIN_SIZE VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE
  42
  43/*
  44 * Calculate the number of bytes up to and including the given 'field' of
  45 * 'container'.
  46 */
  47#define endof(container, field) \
  48    (offsetof(container, field) + sizeof(((container *)0)->field))
  49
  50typedef struct VirtIOFeature {
  51    uint32_t flags;
  52    size_t end;
  53} VirtIOFeature;
  54
  55static VirtIOFeature feature_sizes[] = {
  56    {.flags = 1 << VIRTIO_NET_F_MAC,
  57     .end = endof(struct virtio_net_config, mac)},
  58    {.flags = 1 << VIRTIO_NET_F_STATUS,
  59     .end = endof(struct virtio_net_config, status)},
  60    {.flags = 1 << VIRTIO_NET_F_MQ,
  61     .end = endof(struct virtio_net_config, max_virtqueue_pairs)},
  62    {.flags = 1 << VIRTIO_NET_F_MTU,
  63     .end = endof(struct virtio_net_config, mtu)},
  64    {}
  65};
  66
  67static VirtIONetQueue *virtio_net_get_subqueue(NetClientState *nc)
  68{
  69    VirtIONet *n = qemu_get_nic_opaque(nc);
  70
  71    return &n->vqs[nc->queue_index];
  72}
  73
  74static int vq2q(int queue_index)
  75{
  76    return queue_index / 2;
  77}
  78
  79/* TODO
  80 * - we could suppress RX interrupt if we were so inclined.
  81 */
  82
  83static void virtio_net_get_config(VirtIODevice *vdev, uint8_t *config)
  84{
  85    VirtIONet *n = VIRTIO_NET(vdev);
  86    struct virtio_net_config netcfg;
  87
  88    virtio_stw_p(vdev, &netcfg.status, n->status);
  89    virtio_stw_p(vdev, &netcfg.max_virtqueue_pairs, n->max_queues);
  90    virtio_stw_p(vdev, &netcfg.mtu, n->net_conf.mtu);
  91    memcpy(netcfg.mac, n->mac, ETH_ALEN);
  92    memcpy(config, &netcfg, n->config_size);
  93}
  94
  95static void virtio_net_set_config(VirtIODevice *vdev, const uint8_t *config)
  96{
  97    VirtIONet *n = VIRTIO_NET(vdev);
  98    struct virtio_net_config netcfg = {};
  99
 100    memcpy(&netcfg, config, n->config_size);
 101
 102    if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR) &&
 103        !virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1) &&
 104        memcmp(netcfg.mac, n->mac, ETH_ALEN)) {
 105        memcpy(n->mac, netcfg.mac, ETH_ALEN);
 106        qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
 107    }
 108}
 109
 110static bool virtio_net_started(VirtIONet *n, uint8_t status)
 111{
 112    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 113    return (status & VIRTIO_CONFIG_S_DRIVER_OK) &&
 114        (n->status & VIRTIO_NET_S_LINK_UP) && vdev->vm_running;
 115}
 116
 117static void virtio_net_announce_timer(void *opaque)
 118{
 119    VirtIONet *n = opaque;
 120    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 121
 122    n->announce_counter--;
 123    n->status |= VIRTIO_NET_S_ANNOUNCE;
 124    virtio_notify_config(vdev);
 125}
 126
 127static void virtio_net_vhost_status(VirtIONet *n, uint8_t status)
 128{
 129    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 130    NetClientState *nc = qemu_get_queue(n->nic);
 131    int queues = n->multiqueue ? n->max_queues : 1;
 132
 133    if (!get_vhost_net(nc->peer)) {
 134        return;
 135    }
 136
 137    if ((virtio_net_started(n, status) && !nc->peer->link_down) ==
 138        !!n->vhost_started) {
 139        return;
 140    }
 141    if (!n->vhost_started) {
 142        int r, i;
 143
 144        if (n->needs_vnet_hdr_swap) {
 145            error_report("backend does not support %s vnet headers; "
 146                         "falling back on userspace virtio",
 147                         virtio_is_big_endian(vdev) ? "BE" : "LE");
 148            return;
 149        }
 150
 151        /* Any packets outstanding? Purge them to avoid touching rings
 152         * when vhost is running.
 153         */
 154        for (i = 0;  i < queues; i++) {
 155            NetClientState *qnc = qemu_get_subqueue(n->nic, i);
 156
 157            /* Purge both directions: TX and RX. */
 158            qemu_net_queue_purge(qnc->peer->incoming_queue, qnc);
 159            qemu_net_queue_purge(qnc->incoming_queue, qnc->peer);
 160        }
 161
 162        if (virtio_has_feature(vdev->guest_features, VIRTIO_NET_F_MTU)) {
 163            r = vhost_net_set_mtu(get_vhost_net(nc->peer), n->net_conf.mtu);
 164            if (r < 0) {
 165                error_report("%uBytes MTU not supported by the backend",
 166                             n->net_conf.mtu);
 167
 168                return;
 169            }
 170        }
 171
 172        n->vhost_started = 1;
 173        r = vhost_net_start(vdev, n->nic->ncs, queues);
 174        if (r < 0) {
 175            error_report("unable to start vhost net: %d: "
 176                         "falling back on userspace virtio", -r);
 177            n->vhost_started = 0;
 178        }
 179    } else {
 180        vhost_net_stop(vdev, n->nic->ncs, queues);
 181        n->vhost_started = 0;
 182    }
 183}
 184
 185static int virtio_net_set_vnet_endian_one(VirtIODevice *vdev,
 186                                          NetClientState *peer,
 187                                          bool enable)
 188{
 189    if (virtio_is_big_endian(vdev)) {
 190        return qemu_set_vnet_be(peer, enable);
 191    } else {
 192        return qemu_set_vnet_le(peer, enable);
 193    }
 194}
 195
 196static bool virtio_net_set_vnet_endian(VirtIODevice *vdev, NetClientState *ncs,
 197                                       int queues, bool enable)
 198{
 199    int i;
 200
 201    for (i = 0; i < queues; i++) {
 202        if (virtio_net_set_vnet_endian_one(vdev, ncs[i].peer, enable) < 0 &&
 203            enable) {
 204            while (--i >= 0) {
 205                virtio_net_set_vnet_endian_one(vdev, ncs[i].peer, false);
 206            }
 207
 208            return true;
 209        }
 210    }
 211
 212    return false;
 213}
 214
 215static void virtio_net_vnet_endian_status(VirtIONet *n, uint8_t status)
 216{
 217    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 218    int queues = n->multiqueue ? n->max_queues : 1;
 219
 220    if (virtio_net_started(n, status)) {
 221        /* Before using the device, we tell the network backend about the
 222         * endianness to use when parsing vnet headers. If the backend
 223         * can't do it, we fallback onto fixing the headers in the core
 224         * virtio-net code.
 225         */
 226        n->needs_vnet_hdr_swap = virtio_net_set_vnet_endian(vdev, n->nic->ncs,
 227                                                            queues, true);
 228    } else if (virtio_net_started(n, vdev->status)) {
 229        /* After using the device, we need to reset the network backend to
 230         * the default (guest native endianness), otherwise the guest may
 231         * lose network connectivity if it is rebooted into a different
 232         * endianness.
 233         */
 234        virtio_net_set_vnet_endian(vdev, n->nic->ncs, queues, false);
 235    }
 236}
 237
 238static void virtio_net_drop_tx_queue_data(VirtIODevice *vdev, VirtQueue *vq)
 239{
 240    unsigned int dropped = virtqueue_drop_all(vq);
 241    if (dropped) {
 242        virtio_notify(vdev, vq);
 243    }
 244}
 245
 246static void virtio_net_set_status(struct VirtIODevice *vdev, uint8_t status)
 247{
 248    VirtIONet *n = VIRTIO_NET(vdev);
 249    VirtIONetQueue *q;
 250    int i;
 251    uint8_t queue_status;
 252
 253    virtio_net_vnet_endian_status(n, status);
 254    virtio_net_vhost_status(n, status);
 255
 256    for (i = 0; i < n->max_queues; i++) {
 257        NetClientState *ncs = qemu_get_subqueue(n->nic, i);
 258        bool queue_started;
 259        q = &n->vqs[i];
 260
 261        if ((!n->multiqueue && i != 0) || i >= n->curr_queues) {
 262            queue_status = 0;
 263        } else {
 264            queue_status = status;
 265        }
 266        queue_started =
 267            virtio_net_started(n, queue_status) && !n->vhost_started;
 268
 269        if (queue_started) {
 270            qemu_flush_queued_packets(ncs);
 271        }
 272
 273        if (!q->tx_waiting) {
 274            continue;
 275        }
 276
 277        if (queue_started) {
 278            if (q->tx_timer) {
 279                timer_mod(q->tx_timer,
 280                               qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
 281            } else {
 282                qemu_bh_schedule(q->tx_bh);
 283            }
 284        } else {
 285            if (q->tx_timer) {
 286                timer_del(q->tx_timer);
 287            } else {
 288                qemu_bh_cancel(q->tx_bh);
 289            }
 290            if ((n->status & VIRTIO_NET_S_LINK_UP) == 0 &&
 291                (queue_status & VIRTIO_CONFIG_S_DRIVER_OK) &&
 292                vdev->vm_running) {
 293                /* if tx is waiting we are likely have some packets in tx queue
 294                 * and disabled notification */
 295                q->tx_waiting = 0;
 296                virtio_queue_set_notification(q->tx_vq, 1);
 297                virtio_net_drop_tx_queue_data(vdev, q->tx_vq);
 298            }
 299        }
 300    }
 301}
 302
 303static void virtio_net_set_link_status(NetClientState *nc)
 304{
 305    VirtIONet *n = qemu_get_nic_opaque(nc);
 306    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 307    uint16_t old_status = n->status;
 308
 309    if (nc->link_down)
 310        n->status &= ~VIRTIO_NET_S_LINK_UP;
 311    else
 312        n->status |= VIRTIO_NET_S_LINK_UP;
 313
 314    if (n->status != old_status)
 315        virtio_notify_config(vdev);
 316
 317    virtio_net_set_status(vdev, vdev->status);
 318}
 319
 320static void rxfilter_notify(NetClientState *nc)
 321{
 322    VirtIONet *n = qemu_get_nic_opaque(nc);
 323
 324    if (nc->rxfilter_notify_enabled) {
 325        gchar *path = object_get_canonical_path(OBJECT(n->qdev));
 326        qapi_event_send_nic_rx_filter_changed(!!n->netclient_name,
 327                                              n->netclient_name, path, &error_abort);
 328        g_free(path);
 329
 330        /* disable event notification to avoid events flooding */
 331        nc->rxfilter_notify_enabled = 0;
 332    }
 333}
 334
 335static intList *get_vlan_table(VirtIONet *n)
 336{
 337    intList *list, *entry;
 338    int i, j;
 339
 340    list = NULL;
 341    for (i = 0; i < MAX_VLAN >> 5; i++) {
 342        for (j = 0; n->vlans[i] && j <= 0x1f; j++) {
 343            if (n->vlans[i] & (1U << j)) {
 344                entry = g_malloc0(sizeof(*entry));
 345                entry->value = (i << 5) + j;
 346                entry->next = list;
 347                list = entry;
 348            }
 349        }
 350    }
 351
 352    return list;
 353}
 354
 355static RxFilterInfo *virtio_net_query_rxfilter(NetClientState *nc)
 356{
 357    VirtIONet *n = qemu_get_nic_opaque(nc);
 358    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 359    RxFilterInfo *info;
 360    strList *str_list, *entry;
 361    int i;
 362
 363    info = g_malloc0(sizeof(*info));
 364    info->name = g_strdup(nc->name);
 365    info->promiscuous = n->promisc;
 366
 367    if (n->nouni) {
 368        info->unicast = RX_STATE_NONE;
 369    } else if (n->alluni) {
 370        info->unicast = RX_STATE_ALL;
 371    } else {
 372        info->unicast = RX_STATE_NORMAL;
 373    }
 374
 375    if (n->nomulti) {
 376        info->multicast = RX_STATE_NONE;
 377    } else if (n->allmulti) {
 378        info->multicast = RX_STATE_ALL;
 379    } else {
 380        info->multicast = RX_STATE_NORMAL;
 381    }
 382
 383    info->broadcast_allowed = n->nobcast;
 384    info->multicast_overflow = n->mac_table.multi_overflow;
 385    info->unicast_overflow = n->mac_table.uni_overflow;
 386
 387    info->main_mac = qemu_mac_strdup_printf(n->mac);
 388
 389    str_list = NULL;
 390    for (i = 0; i < n->mac_table.first_multi; i++) {
 391        entry = g_malloc0(sizeof(*entry));
 392        entry->value = qemu_mac_strdup_printf(n->mac_table.macs + i * ETH_ALEN);
 393        entry->next = str_list;
 394        str_list = entry;
 395    }
 396    info->unicast_table = str_list;
 397
 398    str_list = NULL;
 399    for (i = n->mac_table.first_multi; i < n->mac_table.in_use; i++) {
 400        entry = g_malloc0(sizeof(*entry));
 401        entry->value = qemu_mac_strdup_printf(n->mac_table.macs + i * ETH_ALEN);
 402        entry->next = str_list;
 403        str_list = entry;
 404    }
 405    info->multicast_table = str_list;
 406    info->vlan_table = get_vlan_table(n);
 407
 408    if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VLAN)) {
 409        info->vlan = RX_STATE_ALL;
 410    } else if (!info->vlan_table) {
 411        info->vlan = RX_STATE_NONE;
 412    } else {
 413        info->vlan = RX_STATE_NORMAL;
 414    }
 415
 416    /* enable event notification after query */
 417    nc->rxfilter_notify_enabled = 1;
 418
 419    return info;
 420}
 421
 422static void virtio_net_reset(VirtIODevice *vdev)
 423{
 424    VirtIONet *n = VIRTIO_NET(vdev);
 425    int i;
 426
 427    /* Reset back to compatibility mode */
 428    n->promisc = 1;
 429    n->allmulti = 0;
 430    n->alluni = 0;
 431    n->nomulti = 0;
 432    n->nouni = 0;
 433    n->nobcast = 0;
 434    /* multiqueue is disabled by default */
 435    n->curr_queues = 1;
 436    timer_del(n->announce_timer);
 437    n->announce_counter = 0;
 438    n->status &= ~VIRTIO_NET_S_ANNOUNCE;
 439
 440    /* Flush any MAC and VLAN filter table state */
 441    n->mac_table.in_use = 0;
 442    n->mac_table.first_multi = 0;
 443    n->mac_table.multi_overflow = 0;
 444    n->mac_table.uni_overflow = 0;
 445    memset(n->mac_table.macs, 0, MAC_TABLE_ENTRIES * ETH_ALEN);
 446    memcpy(&n->mac[0], &n->nic->conf->macaddr, sizeof(n->mac));
 447    qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
 448    memset(n->vlans, 0, MAX_VLAN >> 3);
 449
 450    /* Flush any async TX */
 451    for (i = 0;  i < n->max_queues; i++) {
 452        NetClientState *nc = qemu_get_subqueue(n->nic, i);
 453
 454        if (nc->peer) {
 455            qemu_flush_or_purge_queued_packets(nc->peer, true);
 456            assert(!virtio_net_get_subqueue(nc)->async_tx.elem);
 457        }
 458    }
 459}
 460
 461static void peer_test_vnet_hdr(VirtIONet *n)
 462{
 463    NetClientState *nc = qemu_get_queue(n->nic);
 464    if (!nc->peer) {
 465        return;
 466    }
 467
 468    n->has_vnet_hdr = qemu_has_vnet_hdr(nc->peer);
 469}
 470
 471static int peer_has_vnet_hdr(VirtIONet *n)
 472{
 473    return n->has_vnet_hdr;
 474}
 475
 476static int peer_has_ufo(VirtIONet *n)
 477{
 478    if (!peer_has_vnet_hdr(n))
 479        return 0;
 480
 481    n->has_ufo = qemu_has_ufo(qemu_get_queue(n->nic)->peer);
 482
 483    return n->has_ufo;
 484}
 485
 486static void virtio_net_set_mrg_rx_bufs(VirtIONet *n, int mergeable_rx_bufs,
 487                                       int version_1)
 488{
 489    int i;
 490    NetClientState *nc;
 491
 492    n->mergeable_rx_bufs = mergeable_rx_bufs;
 493
 494    if (version_1) {
 495        n->guest_hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
 496    } else {
 497        n->guest_hdr_len = n->mergeable_rx_bufs ?
 498            sizeof(struct virtio_net_hdr_mrg_rxbuf) :
 499            sizeof(struct virtio_net_hdr);
 500    }
 501
 502    for (i = 0; i < n->max_queues; i++) {
 503        nc = qemu_get_subqueue(n->nic, i);
 504
 505        if (peer_has_vnet_hdr(n) &&
 506            qemu_has_vnet_hdr_len(nc->peer, n->guest_hdr_len)) {
 507            qemu_set_vnet_hdr_len(nc->peer, n->guest_hdr_len);
 508            n->host_hdr_len = n->guest_hdr_len;
 509        }
 510    }
 511}
 512
 513static int virtio_net_max_tx_queue_size(VirtIONet *n)
 514{
 515    NetClientState *peer = n->nic_conf.peers.ncs[0];
 516
 517    /*
 518     * Backends other than vhost-user don't support max queue size.
 519     */
 520    if (!peer) {
 521        return VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE;
 522    }
 523
 524    if (peer->info->type != NET_CLIENT_DRIVER_VHOST_USER) {
 525        return VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE;
 526    }
 527
 528    return VIRTQUEUE_MAX_SIZE;
 529}
 530
 531static int peer_attach(VirtIONet *n, int index)
 532{
 533    NetClientState *nc = qemu_get_subqueue(n->nic, index);
 534
 535    if (!nc->peer) {
 536        return 0;
 537    }
 538
 539    if (nc->peer->info->type == NET_CLIENT_DRIVER_VHOST_USER) {
 540        vhost_set_vring_enable(nc->peer, 1);
 541    }
 542
 543    if (nc->peer->info->type != NET_CLIENT_DRIVER_TAP) {
 544        return 0;
 545    }
 546
 547    if (n->max_queues == 1) {
 548        return 0;
 549    }
 550
 551    return tap_enable(nc->peer);
 552}
 553
 554static int peer_detach(VirtIONet *n, int index)
 555{
 556    NetClientState *nc = qemu_get_subqueue(n->nic, index);
 557
 558    if (!nc->peer) {
 559        return 0;
 560    }
 561
 562    if (nc->peer->info->type == NET_CLIENT_DRIVER_VHOST_USER) {
 563        vhost_set_vring_enable(nc->peer, 0);
 564    }
 565
 566    if (nc->peer->info->type !=  NET_CLIENT_DRIVER_TAP) {
 567        return 0;
 568    }
 569
 570    return tap_disable(nc->peer);
 571}
 572
 573static void virtio_net_set_queues(VirtIONet *n)
 574{
 575    int i;
 576    int r;
 577
 578    if (n->nic->peer_deleted) {
 579        return;
 580    }
 581
 582    for (i = 0; i < n->max_queues; i++) {
 583        if (i < n->curr_queues) {
 584            r = peer_attach(n, i);
 585            assert(!r);
 586        } else {
 587            r = peer_detach(n, i);
 588            assert(!r);
 589        }
 590    }
 591}
 592
 593static void virtio_net_set_multiqueue(VirtIONet *n, int multiqueue);
 594
 595static uint64_t virtio_net_get_features(VirtIODevice *vdev, uint64_t features,
 596                                        Error **errp)
 597{
 598    VirtIONet *n = VIRTIO_NET(vdev);
 599    NetClientState *nc = qemu_get_queue(n->nic);
 600
 601    /* Firstly sync all virtio-net possible supported features */
 602    features |= n->host_features;
 603
 604    virtio_add_feature(&features, VIRTIO_NET_F_MAC);
 605
 606    if (!peer_has_vnet_hdr(n)) {
 607        virtio_clear_feature(&features, VIRTIO_NET_F_CSUM);
 608        virtio_clear_feature(&features, VIRTIO_NET_F_HOST_TSO4);
 609        virtio_clear_feature(&features, VIRTIO_NET_F_HOST_TSO6);
 610        virtio_clear_feature(&features, VIRTIO_NET_F_HOST_ECN);
 611
 612        virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_CSUM);
 613        virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_TSO4);
 614        virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_TSO6);
 615        virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_ECN);
 616    }
 617
 618    if (!peer_has_vnet_hdr(n) || !peer_has_ufo(n)) {
 619        virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_UFO);
 620        virtio_clear_feature(&features, VIRTIO_NET_F_HOST_UFO);
 621    }
 622
 623    if (!get_vhost_net(nc->peer)) {
 624        return features;
 625    }
 626    features = vhost_net_get_features(get_vhost_net(nc->peer), features);
 627    vdev->backend_features = features;
 628
 629    if (n->mtu_bypass_backend &&
 630            (n->host_features & 1ULL << VIRTIO_NET_F_MTU)) {
 631        features |= (1ULL << VIRTIO_NET_F_MTU);
 632    }
 633
 634    return features;
 635}
 636
 637static uint64_t virtio_net_bad_features(VirtIODevice *vdev)
 638{
 639    uint64_t features = 0;
 640
 641    /* Linux kernel 2.6.25.  It understood MAC (as everyone must),
 642     * but also these: */
 643    virtio_add_feature(&features, VIRTIO_NET_F_MAC);
 644    virtio_add_feature(&features, VIRTIO_NET_F_CSUM);
 645    virtio_add_feature(&features, VIRTIO_NET_F_HOST_TSO4);
 646    virtio_add_feature(&features, VIRTIO_NET_F_HOST_TSO6);
 647    virtio_add_feature(&features, VIRTIO_NET_F_HOST_ECN);
 648
 649    return features;
 650}
 651
 652static void virtio_net_apply_guest_offloads(VirtIONet *n)
 653{
 654    qemu_set_offload(qemu_get_queue(n->nic)->peer,
 655            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_CSUM)),
 656            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO4)),
 657            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO6)),
 658            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_ECN)),
 659            !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_UFO)));
 660}
 661
 662static uint64_t virtio_net_guest_offloads_by_features(uint32_t features)
 663{
 664    static const uint64_t guest_offloads_mask =
 665        (1ULL << VIRTIO_NET_F_GUEST_CSUM) |
 666        (1ULL << VIRTIO_NET_F_GUEST_TSO4) |
 667        (1ULL << VIRTIO_NET_F_GUEST_TSO6) |
 668        (1ULL << VIRTIO_NET_F_GUEST_ECN)  |
 669        (1ULL << VIRTIO_NET_F_GUEST_UFO);
 670
 671    return guest_offloads_mask & features;
 672}
 673
 674static inline uint64_t virtio_net_supported_guest_offloads(VirtIONet *n)
 675{
 676    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 677    return virtio_net_guest_offloads_by_features(vdev->guest_features);
 678}
 679
 680static void virtio_net_set_features(VirtIODevice *vdev, uint64_t features)
 681{
 682    VirtIONet *n = VIRTIO_NET(vdev);
 683    int i;
 684
 685    if (n->mtu_bypass_backend &&
 686            !virtio_has_feature(vdev->backend_features, VIRTIO_NET_F_MTU)) {
 687        features &= ~(1ULL << VIRTIO_NET_F_MTU);
 688    }
 689
 690    virtio_net_set_multiqueue(n,
 691                              virtio_has_feature(features, VIRTIO_NET_F_MQ));
 692
 693    virtio_net_set_mrg_rx_bufs(n,
 694                               virtio_has_feature(features,
 695                                                  VIRTIO_NET_F_MRG_RXBUF),
 696                               virtio_has_feature(features,
 697                                                  VIRTIO_F_VERSION_1));
 698
 699    if (n->has_vnet_hdr) {
 700        n->curr_guest_offloads =
 701            virtio_net_guest_offloads_by_features(features);
 702        virtio_net_apply_guest_offloads(n);
 703    }
 704
 705    for (i = 0;  i < n->max_queues; i++) {
 706        NetClientState *nc = qemu_get_subqueue(n->nic, i);
 707
 708        if (!get_vhost_net(nc->peer)) {
 709            continue;
 710        }
 711        vhost_net_ack_features(get_vhost_net(nc->peer), features);
 712    }
 713
 714    if (virtio_has_feature(features, VIRTIO_NET_F_CTRL_VLAN)) {
 715        memset(n->vlans, 0, MAX_VLAN >> 3);
 716    } else {
 717        memset(n->vlans, 0xff, MAX_VLAN >> 3);
 718    }
 719}
 720
 721static int virtio_net_handle_rx_mode(VirtIONet *n, uint8_t cmd,
 722                                     struct iovec *iov, unsigned int iov_cnt)
 723{
 724    uint8_t on;
 725    size_t s;
 726    NetClientState *nc = qemu_get_queue(n->nic);
 727
 728    s = iov_to_buf(iov, iov_cnt, 0, &on, sizeof(on));
 729    if (s != sizeof(on)) {
 730        return VIRTIO_NET_ERR;
 731    }
 732
 733    if (cmd == VIRTIO_NET_CTRL_RX_PROMISC) {
 734        n->promisc = on;
 735    } else if (cmd == VIRTIO_NET_CTRL_RX_ALLMULTI) {
 736        n->allmulti = on;
 737    } else if (cmd == VIRTIO_NET_CTRL_RX_ALLUNI) {
 738        n->alluni = on;
 739    } else if (cmd == VIRTIO_NET_CTRL_RX_NOMULTI) {
 740        n->nomulti = on;
 741    } else if (cmd == VIRTIO_NET_CTRL_RX_NOUNI) {
 742        n->nouni = on;
 743    } else if (cmd == VIRTIO_NET_CTRL_RX_NOBCAST) {
 744        n->nobcast = on;
 745    } else {
 746        return VIRTIO_NET_ERR;
 747    }
 748
 749    rxfilter_notify(nc);
 750
 751    return VIRTIO_NET_OK;
 752}
 753
 754static int virtio_net_handle_offloads(VirtIONet *n, uint8_t cmd,
 755                                     struct iovec *iov, unsigned int iov_cnt)
 756{
 757    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 758    uint64_t offloads;
 759    size_t s;
 760
 761    if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)) {
 762        return VIRTIO_NET_ERR;
 763    }
 764
 765    s = iov_to_buf(iov, iov_cnt, 0, &offloads, sizeof(offloads));
 766    if (s != sizeof(offloads)) {
 767        return VIRTIO_NET_ERR;
 768    }
 769
 770    if (cmd == VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET) {
 771        uint64_t supported_offloads;
 772
 773        offloads = virtio_ldq_p(vdev, &offloads);
 774
 775        if (!n->has_vnet_hdr) {
 776            return VIRTIO_NET_ERR;
 777        }
 778
 779        supported_offloads = virtio_net_supported_guest_offloads(n);
 780        if (offloads & ~supported_offloads) {
 781            return VIRTIO_NET_ERR;
 782        }
 783
 784        n->curr_guest_offloads = offloads;
 785        virtio_net_apply_guest_offloads(n);
 786
 787        return VIRTIO_NET_OK;
 788    } else {
 789        return VIRTIO_NET_ERR;
 790    }
 791}
 792
 793static int virtio_net_handle_mac(VirtIONet *n, uint8_t cmd,
 794                                 struct iovec *iov, unsigned int iov_cnt)
 795{
 796    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 797    struct virtio_net_ctrl_mac mac_data;
 798    size_t s;
 799    NetClientState *nc = qemu_get_queue(n->nic);
 800
 801    if (cmd == VIRTIO_NET_CTRL_MAC_ADDR_SET) {
 802        if (iov_size(iov, iov_cnt) != sizeof(n->mac)) {
 803            return VIRTIO_NET_ERR;
 804        }
 805        s = iov_to_buf(iov, iov_cnt, 0, &n->mac, sizeof(n->mac));
 806        assert(s == sizeof(n->mac));
 807        qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
 808        rxfilter_notify(nc);
 809
 810        return VIRTIO_NET_OK;
 811    }
 812
 813    if (cmd != VIRTIO_NET_CTRL_MAC_TABLE_SET) {
 814        return VIRTIO_NET_ERR;
 815    }
 816
 817    int in_use = 0;
 818    int first_multi = 0;
 819    uint8_t uni_overflow = 0;
 820    uint8_t multi_overflow = 0;
 821    uint8_t *macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN);
 822
 823    s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries,
 824                   sizeof(mac_data.entries));
 825    mac_data.entries = virtio_ldl_p(vdev, &mac_data.entries);
 826    if (s != sizeof(mac_data.entries)) {
 827        goto error;
 828    }
 829    iov_discard_front(&iov, &iov_cnt, s);
 830
 831    if (mac_data.entries * ETH_ALEN > iov_size(iov, iov_cnt)) {
 832        goto error;
 833    }
 834
 835    if (mac_data.entries <= MAC_TABLE_ENTRIES) {
 836        s = iov_to_buf(iov, iov_cnt, 0, macs,
 837                       mac_data.entries * ETH_ALEN);
 838        if (s != mac_data.entries * ETH_ALEN) {
 839            goto error;
 840        }
 841        in_use += mac_data.entries;
 842    } else {
 843        uni_overflow = 1;
 844    }
 845
 846    iov_discard_front(&iov, &iov_cnt, mac_data.entries * ETH_ALEN);
 847
 848    first_multi = in_use;
 849
 850    s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries,
 851                   sizeof(mac_data.entries));
 852    mac_data.entries = virtio_ldl_p(vdev, &mac_data.entries);
 853    if (s != sizeof(mac_data.entries)) {
 854        goto error;
 855    }
 856
 857    iov_discard_front(&iov, &iov_cnt, s);
 858
 859    if (mac_data.entries * ETH_ALEN != iov_size(iov, iov_cnt)) {
 860        goto error;
 861    }
 862
 863    if (mac_data.entries <= MAC_TABLE_ENTRIES - in_use) {
 864        s = iov_to_buf(iov, iov_cnt, 0, &macs[in_use * ETH_ALEN],
 865                       mac_data.entries * ETH_ALEN);
 866        if (s != mac_data.entries * ETH_ALEN) {
 867            goto error;
 868        }
 869        in_use += mac_data.entries;
 870    } else {
 871        multi_overflow = 1;
 872    }
 873
 874    n->mac_table.in_use = in_use;
 875    n->mac_table.first_multi = first_multi;
 876    n->mac_table.uni_overflow = uni_overflow;
 877    n->mac_table.multi_overflow = multi_overflow;
 878    memcpy(n->mac_table.macs, macs, MAC_TABLE_ENTRIES * ETH_ALEN);
 879    g_free(macs);
 880    rxfilter_notify(nc);
 881
 882    return VIRTIO_NET_OK;
 883
 884error:
 885    g_free(macs);
 886    return VIRTIO_NET_ERR;
 887}
 888
 889static int virtio_net_handle_vlan_table(VirtIONet *n, uint8_t cmd,
 890                                        struct iovec *iov, unsigned int iov_cnt)
 891{
 892    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 893    uint16_t vid;
 894    size_t s;
 895    NetClientState *nc = qemu_get_queue(n->nic);
 896
 897    s = iov_to_buf(iov, iov_cnt, 0, &vid, sizeof(vid));
 898    vid = virtio_lduw_p(vdev, &vid);
 899    if (s != sizeof(vid)) {
 900        return VIRTIO_NET_ERR;
 901    }
 902
 903    if (vid >= MAX_VLAN)
 904        return VIRTIO_NET_ERR;
 905
 906    if (cmd == VIRTIO_NET_CTRL_VLAN_ADD)
 907        n->vlans[vid >> 5] |= (1U << (vid & 0x1f));
 908    else if (cmd == VIRTIO_NET_CTRL_VLAN_DEL)
 909        n->vlans[vid >> 5] &= ~(1U << (vid & 0x1f));
 910    else
 911        return VIRTIO_NET_ERR;
 912
 913    rxfilter_notify(nc);
 914
 915    return VIRTIO_NET_OK;
 916}
 917
 918static int virtio_net_handle_announce(VirtIONet *n, uint8_t cmd,
 919                                      struct iovec *iov, unsigned int iov_cnt)
 920{
 921    if (cmd == VIRTIO_NET_CTRL_ANNOUNCE_ACK &&
 922        n->status & VIRTIO_NET_S_ANNOUNCE) {
 923        n->status &= ~VIRTIO_NET_S_ANNOUNCE;
 924        if (n->announce_counter) {
 925            timer_mod(n->announce_timer,
 926                      qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
 927                      self_announce_delay(n->announce_counter));
 928        }
 929        return VIRTIO_NET_OK;
 930    } else {
 931        return VIRTIO_NET_ERR;
 932    }
 933}
 934
 935static int virtio_net_handle_mq(VirtIONet *n, uint8_t cmd,
 936                                struct iovec *iov, unsigned int iov_cnt)
 937{
 938    VirtIODevice *vdev = VIRTIO_DEVICE(n);
 939    struct virtio_net_ctrl_mq mq;
 940    size_t s;
 941    uint16_t queues;
 942
 943    s = iov_to_buf(iov, iov_cnt, 0, &mq, sizeof(mq));
 944    if (s != sizeof(mq)) {
 945        return VIRTIO_NET_ERR;
 946    }
 947
 948    if (cmd != VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET) {
 949        return VIRTIO_NET_ERR;
 950    }
 951
 952    queues = virtio_lduw_p(vdev, &mq.virtqueue_pairs);
 953
 954    if (queues < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
 955        queues > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
 956        queues > n->max_queues ||
 957        !n->multiqueue) {
 958        return VIRTIO_NET_ERR;
 959    }
 960
 961    n->curr_queues = queues;
 962    /* stop the backend before changing the number of queues to avoid handling a
 963     * disabled queue */
 964    virtio_net_set_status(vdev, vdev->status);
 965    virtio_net_set_queues(n);
 966
 967    return VIRTIO_NET_OK;
 968}
 969
 970static void virtio_net_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
 971{
 972    VirtIONet *n = VIRTIO_NET(vdev);
 973    struct virtio_net_ctrl_hdr ctrl;
 974    virtio_net_ctrl_ack status = VIRTIO_NET_ERR;
 975    VirtQueueElement *elem;
 976    size_t s;
 977    struct iovec *iov, *iov2;
 978    unsigned int iov_cnt;
 979
 980    for (;;) {
 981        elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
 982        if (!elem) {
 983            break;
 984        }
 985        if (iov_size(elem->in_sg, elem->in_num) < sizeof(status) ||
 986            iov_size(elem->out_sg, elem->out_num) < sizeof(ctrl)) {
 987            virtio_error(vdev, "virtio-net ctrl missing headers");
 988            virtqueue_detach_element(vq, elem, 0);
 989            g_free(elem);
 990            break;
 991        }
 992
 993        iov_cnt = elem->out_num;
 994        iov2 = iov = g_memdup(elem->out_sg, sizeof(struct iovec) * elem->out_num);
 995        s = iov_to_buf(iov, iov_cnt, 0, &ctrl, sizeof(ctrl));
 996        iov_discard_front(&iov, &iov_cnt, sizeof(ctrl));
 997        if (s != sizeof(ctrl)) {
 998            status = VIRTIO_NET_ERR;
 999        } else if (ctrl.class == VIRTIO_NET_CTRL_RX) {
1000            status = virtio_net_handle_rx_mode(n, ctrl.cmd, iov, iov_cnt);
1001        } else if (ctrl.class == VIRTIO_NET_CTRL_MAC) {
1002            status = virtio_net_handle_mac(n, ctrl.cmd, iov, iov_cnt);
1003        } else if (ctrl.class == VIRTIO_NET_CTRL_VLAN) {
1004            status = virtio_net_handle_vlan_table(n, ctrl.cmd, iov, iov_cnt);
1005        } else if (ctrl.class == VIRTIO_NET_CTRL_ANNOUNCE) {
1006            status = virtio_net_handle_announce(n, ctrl.cmd, iov, iov_cnt);
1007        } else if (ctrl.class == VIRTIO_NET_CTRL_MQ) {
1008            status = virtio_net_handle_mq(n, ctrl.cmd, iov, iov_cnt);
1009        } else if (ctrl.class == VIRTIO_NET_CTRL_GUEST_OFFLOADS) {
1010            status = virtio_net_handle_offloads(n, ctrl.cmd, iov, iov_cnt);
1011        }
1012
1013        s = iov_from_buf(elem->in_sg, elem->in_num, 0, &status, sizeof(status));
1014        assert(s == sizeof(status));
1015
1016        virtqueue_push(vq, elem, sizeof(status));
1017        virtio_notify(vdev, vq);
1018        g_free(iov2);
1019        g_free(elem);
1020    }
1021}
1022
1023/* RX */
1024
1025static void virtio_net_handle_rx(VirtIODevice *vdev, VirtQueue *vq)
1026{
1027    VirtIONet *n = VIRTIO_NET(vdev);
1028    int queue_index = vq2q(virtio_get_queue_index(vq));
1029
1030    qemu_flush_queued_packets(qemu_get_subqueue(n->nic, queue_index));
1031}
1032
1033static int virtio_net_can_receive(NetClientState *nc)
1034{
1035    VirtIONet *n = qemu_get_nic_opaque(nc);
1036    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1037    VirtIONetQueue *q = virtio_net_get_subqueue(nc);
1038
1039    if (!vdev->vm_running) {
1040        return 0;
1041    }
1042
1043    if (nc->queue_index >= n->curr_queues) {
1044        return 0;
1045    }
1046
1047    if (!virtio_queue_ready(q->rx_vq) ||
1048        !(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1049        return 0;
1050    }
1051
1052    return 1;
1053}
1054
1055static int virtio_net_has_buffers(VirtIONetQueue *q, int bufsize)
1056{
1057    VirtIONet *n = q->n;
1058    if (virtio_queue_empty(q->rx_vq) ||
1059        (n->mergeable_rx_bufs &&
1060         !virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
1061        virtio_queue_set_notification(q->rx_vq, 1);
1062
1063        /* To avoid a race condition where the guest has made some buffers
1064         * available after the above check but before notification was
1065         * enabled, check for available buffers again.
1066         */
1067        if (virtio_queue_empty(q->rx_vq) ||
1068            (n->mergeable_rx_bufs &&
1069             !virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
1070            return 0;
1071        }
1072    }
1073
1074    virtio_queue_set_notification(q->rx_vq, 0);
1075    return 1;
1076}
1077
1078static void virtio_net_hdr_swap(VirtIODevice *vdev, struct virtio_net_hdr *hdr)
1079{
1080    virtio_tswap16s(vdev, &hdr->hdr_len);
1081    virtio_tswap16s(vdev, &hdr->gso_size);
1082    virtio_tswap16s(vdev, &hdr->csum_start);
1083    virtio_tswap16s(vdev, &hdr->csum_offset);
1084}
1085
1086/* dhclient uses AF_PACKET but doesn't pass auxdata to the kernel so
1087 * it never finds out that the packets don't have valid checksums.  This
1088 * causes dhclient to get upset.  Fedora's carried a patch for ages to
1089 * fix this with Xen but it hasn't appeared in an upstream release of
1090 * dhclient yet.
1091 *
1092 * To avoid breaking existing guests, we catch udp packets and add
1093 * checksums.  This is terrible but it's better than hacking the guest
1094 * kernels.
1095 *
1096 * N.B. if we introduce a zero-copy API, this operation is no longer free so
1097 * we should provide a mechanism to disable it to avoid polluting the host
1098 * cache.
1099 */
1100static void work_around_broken_dhclient(struct virtio_net_hdr *hdr,
1101                                        uint8_t *buf, size_t size)
1102{
1103    if ((hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && /* missing csum */
1104        (size > 27 && size < 1500) && /* normal sized MTU */
1105        (buf[12] == 0x08 && buf[13] == 0x00) && /* ethertype == IPv4 */
1106        (buf[23] == 17) && /* ip.protocol == UDP */
1107        (buf[34] == 0 && buf[35] == 67)) { /* udp.srcport == bootps */
1108        net_checksum_calculate(buf, size);
1109        hdr->flags &= ~VIRTIO_NET_HDR_F_NEEDS_CSUM;
1110    }
1111}
1112
1113static void receive_header(VirtIONet *n, const struct iovec *iov, int iov_cnt,
1114                           const void *buf, size_t size)
1115{
1116    if (n->has_vnet_hdr) {
1117        /* FIXME this cast is evil */
1118        void *wbuf = (void *)buf;
1119        work_around_broken_dhclient(wbuf, wbuf + n->host_hdr_len,
1120                                    size - n->host_hdr_len);
1121
1122        if (n->needs_vnet_hdr_swap) {
1123            virtio_net_hdr_swap(VIRTIO_DEVICE(n), wbuf);
1124        }
1125        iov_from_buf(iov, iov_cnt, 0, buf, sizeof(struct virtio_net_hdr));
1126    } else {
1127        struct virtio_net_hdr hdr = {
1128            .flags = 0,
1129            .gso_type = VIRTIO_NET_HDR_GSO_NONE
1130        };
1131        iov_from_buf(iov, iov_cnt, 0, &hdr, sizeof hdr);
1132    }
1133}
1134
1135static int receive_filter(VirtIONet *n, const uint8_t *buf, int size)
1136{
1137    static const uint8_t bcast[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
1138    static const uint8_t vlan[] = {0x81, 0x00};
1139    uint8_t *ptr = (uint8_t *)buf;
1140    int i;
1141
1142    if (n->promisc)
1143        return 1;
1144
1145    ptr += n->host_hdr_len;
1146
1147    if (!memcmp(&ptr[12], vlan, sizeof(vlan))) {
1148        int vid = lduw_be_p(ptr + 14) & 0xfff;
1149        if (!(n->vlans[vid >> 5] & (1U << (vid & 0x1f))))
1150            return 0;
1151    }
1152
1153    if (ptr[0] & 1) { // multicast
1154        if (!memcmp(ptr, bcast, sizeof(bcast))) {
1155            return !n->nobcast;
1156        } else if (n->nomulti) {
1157            return 0;
1158        } else if (n->allmulti || n->mac_table.multi_overflow) {
1159            return 1;
1160        }
1161
1162        for (i = n->mac_table.first_multi; i < n->mac_table.in_use; i++) {
1163            if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN)) {
1164                return 1;
1165            }
1166        }
1167    } else { // unicast
1168        if (n->nouni) {
1169            return 0;
1170        } else if (n->alluni || n->mac_table.uni_overflow) {
1171            return 1;
1172        } else if (!memcmp(ptr, n->mac, ETH_ALEN)) {
1173            return 1;
1174        }
1175
1176        for (i = 0; i < n->mac_table.first_multi; i++) {
1177            if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN)) {
1178                return 1;
1179            }
1180        }
1181    }
1182
1183    return 0;
1184}
1185
1186static ssize_t virtio_net_receive_rcu(NetClientState *nc, const uint8_t *buf,
1187                                      size_t size)
1188{
1189    VirtIONet *n = qemu_get_nic_opaque(nc);
1190    VirtIONetQueue *q = virtio_net_get_subqueue(nc);
1191    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1192    struct iovec mhdr_sg[VIRTQUEUE_MAX_SIZE];
1193    struct virtio_net_hdr_mrg_rxbuf mhdr;
1194    unsigned mhdr_cnt = 0;
1195    size_t offset, i, guest_offset;
1196
1197    if (!virtio_net_can_receive(nc)) {
1198        return -1;
1199    }
1200
1201    /* hdr_len refers to the header we supply to the guest */
1202    if (!virtio_net_has_buffers(q, size + n->guest_hdr_len - n->host_hdr_len)) {
1203        return 0;
1204    }
1205
1206    if (!receive_filter(n, buf, size))
1207        return size;
1208
1209    offset = i = 0;
1210
1211    while (offset < size) {
1212        VirtQueueElement *elem;
1213        int len, total;
1214        const struct iovec *sg;
1215
1216        total = 0;
1217
1218        elem = virtqueue_pop(q->rx_vq, sizeof(VirtQueueElement));
1219        if (!elem) {
1220            if (i) {
1221                virtio_error(vdev, "virtio-net unexpected empty queue: "
1222                             "i %zd mergeable %d offset %zd, size %zd, "
1223                             "guest hdr len %zd, host hdr len %zd "
1224                             "guest features 0x%" PRIx64,
1225                             i, n->mergeable_rx_bufs, offset, size,
1226                             n->guest_hdr_len, n->host_hdr_len,
1227                             vdev->guest_features);
1228            }
1229            return -1;
1230        }
1231
1232        if (elem->in_num < 1) {
1233            virtio_error(vdev,
1234                         "virtio-net receive queue contains no in buffers");
1235            virtqueue_detach_element(q->rx_vq, elem, 0);
1236            g_free(elem);
1237            return -1;
1238        }
1239
1240        sg = elem->in_sg;
1241        if (i == 0) {
1242            assert(offset == 0);
1243            if (n->mergeable_rx_bufs) {
1244                mhdr_cnt = iov_copy(mhdr_sg, ARRAY_SIZE(mhdr_sg),
1245                                    sg, elem->in_num,
1246                                    offsetof(typeof(mhdr), num_buffers),
1247                                    sizeof(mhdr.num_buffers));
1248            }
1249
1250            receive_header(n, sg, elem->in_num, buf, size);
1251            offset = n->host_hdr_len;
1252            total += n->guest_hdr_len;
1253            guest_offset = n->guest_hdr_len;
1254        } else {
1255            guest_offset = 0;
1256        }
1257
1258        /* copy in packet.  ugh */
1259        len = iov_from_buf(sg, elem->in_num, guest_offset,
1260                           buf + offset, size - offset);
1261        total += len;
1262        offset += len;
1263        /* If buffers can't be merged, at this point we
1264         * must have consumed the complete packet.
1265         * Otherwise, drop it. */
1266        if (!n->mergeable_rx_bufs && offset < size) {
1267            virtqueue_unpop(q->rx_vq, elem, total);
1268            g_free(elem);
1269            return size;
1270        }
1271
1272        /* signal other side */
1273        virtqueue_fill(q->rx_vq, elem, total, i++);
1274        g_free(elem);
1275    }
1276
1277    if (mhdr_cnt) {
1278        virtio_stw_p(vdev, &mhdr.num_buffers, i);
1279        iov_from_buf(mhdr_sg, mhdr_cnt,
1280                     0,
1281                     &mhdr.num_buffers, sizeof mhdr.num_buffers);
1282    }
1283
1284    virtqueue_flush(q->rx_vq, i);
1285    virtio_notify(vdev, q->rx_vq);
1286
1287    return size;
1288}
1289
1290static ssize_t virtio_net_receive(NetClientState *nc, const uint8_t *buf,
1291                                  size_t size)
1292{
1293    ssize_t r;
1294
1295    rcu_read_lock();
1296    r = virtio_net_receive_rcu(nc, buf, size);
1297    rcu_read_unlock();
1298    return r;
1299}
1300
1301static int32_t virtio_net_flush_tx(VirtIONetQueue *q);
1302
1303static void virtio_net_tx_complete(NetClientState *nc, ssize_t len)
1304{
1305    VirtIONet *n = qemu_get_nic_opaque(nc);
1306    VirtIONetQueue *q = virtio_net_get_subqueue(nc);
1307    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1308
1309    virtqueue_push(q->tx_vq, q->async_tx.elem, 0);
1310    virtio_notify(vdev, q->tx_vq);
1311
1312    g_free(q->async_tx.elem);
1313    q->async_tx.elem = NULL;
1314
1315    virtio_queue_set_notification(q->tx_vq, 1);
1316    virtio_net_flush_tx(q);
1317}
1318
1319/* TX */
1320static int32_t virtio_net_flush_tx(VirtIONetQueue *q)
1321{
1322    VirtIONet *n = q->n;
1323    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1324    VirtQueueElement *elem;
1325    int32_t num_packets = 0;
1326    int queue_index = vq2q(virtio_get_queue_index(q->tx_vq));
1327    if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1328        return num_packets;
1329    }
1330
1331    if (q->async_tx.elem) {
1332        virtio_queue_set_notification(q->tx_vq, 0);
1333        return num_packets;
1334    }
1335
1336    for (;;) {
1337        ssize_t ret;
1338        unsigned int out_num;
1339        struct iovec sg[VIRTQUEUE_MAX_SIZE], sg2[VIRTQUEUE_MAX_SIZE + 1], *out_sg;
1340        struct virtio_net_hdr_mrg_rxbuf mhdr;
1341
1342        elem = virtqueue_pop(q->tx_vq, sizeof(VirtQueueElement));
1343        if (!elem) {
1344            break;
1345        }
1346
1347        out_num = elem->out_num;
1348        out_sg = elem->out_sg;
1349        if (out_num < 1) {
1350            virtio_error(vdev, "virtio-net header not in first element");
1351            virtqueue_detach_element(q->tx_vq, elem, 0);
1352            g_free(elem);
1353            return -EINVAL;
1354        }
1355
1356        if (n->has_vnet_hdr) {
1357            if (iov_to_buf(out_sg, out_num, 0, &mhdr, n->guest_hdr_len) <
1358                n->guest_hdr_len) {
1359                virtio_error(vdev, "virtio-net header incorrect");
1360                virtqueue_detach_element(q->tx_vq, elem, 0);
1361                g_free(elem);
1362                return -EINVAL;
1363            }
1364            if (n->needs_vnet_hdr_swap) {
1365                virtio_net_hdr_swap(vdev, (void *) &mhdr);
1366                sg2[0].iov_base = &mhdr;
1367                sg2[0].iov_len = n->guest_hdr_len;
1368                out_num = iov_copy(&sg2[1], ARRAY_SIZE(sg2) - 1,
1369                                   out_sg, out_num,
1370                                   n->guest_hdr_len, -1);
1371                if (out_num == VIRTQUEUE_MAX_SIZE) {
1372                    goto drop;
1373                }
1374                out_num += 1;
1375                out_sg = sg2;
1376            }
1377        }
1378        /*
1379         * If host wants to see the guest header as is, we can
1380         * pass it on unchanged. Otherwise, copy just the parts
1381         * that host is interested in.
1382         */
1383        assert(n->host_hdr_len <= n->guest_hdr_len);
1384        if (n->host_hdr_len != n->guest_hdr_len) {
1385            unsigned sg_num = iov_copy(sg, ARRAY_SIZE(sg),
1386                                       out_sg, out_num,
1387                                       0, n->host_hdr_len);
1388            sg_num += iov_copy(sg + sg_num, ARRAY_SIZE(sg) - sg_num,
1389                             out_sg, out_num,
1390                             n->guest_hdr_len, -1);
1391            out_num = sg_num;
1392            out_sg = sg;
1393        }
1394
1395        ret = qemu_sendv_packet_async(qemu_get_subqueue(n->nic, queue_index),
1396                                      out_sg, out_num, virtio_net_tx_complete);
1397        if (ret == 0) {
1398            virtio_queue_set_notification(q->tx_vq, 0);
1399            q->async_tx.elem = elem;
1400            return -EBUSY;
1401        }
1402
1403drop:
1404        virtqueue_push(q->tx_vq, elem, 0);
1405        virtio_notify(vdev, q->tx_vq);
1406        g_free(elem);
1407
1408        if (++num_packets >= n->tx_burst) {
1409            break;
1410        }
1411    }
1412    return num_packets;
1413}
1414
1415static void virtio_net_handle_tx_timer(VirtIODevice *vdev, VirtQueue *vq)
1416{
1417    VirtIONet *n = VIRTIO_NET(vdev);
1418    VirtIONetQueue *q = &n->vqs[vq2q(virtio_get_queue_index(vq))];
1419
1420    if (unlikely((n->status & VIRTIO_NET_S_LINK_UP) == 0)) {
1421        virtio_net_drop_tx_queue_data(vdev, vq);
1422        return;
1423    }
1424
1425    /* This happens when device was stopped but VCPU wasn't. */
1426    if (!vdev->vm_running) {
1427        q->tx_waiting = 1;
1428        return;
1429    }
1430
1431    if (q->tx_waiting) {
1432        virtio_queue_set_notification(vq, 1);
1433        timer_del(q->tx_timer);
1434        q->tx_waiting = 0;
1435        if (virtio_net_flush_tx(q) == -EINVAL) {
1436            return;
1437        }
1438    } else {
1439        timer_mod(q->tx_timer,
1440                       qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
1441        q->tx_waiting = 1;
1442        virtio_queue_set_notification(vq, 0);
1443    }
1444}
1445
1446static void virtio_net_handle_tx_bh(VirtIODevice *vdev, VirtQueue *vq)
1447{
1448    VirtIONet *n = VIRTIO_NET(vdev);
1449    VirtIONetQueue *q = &n->vqs[vq2q(virtio_get_queue_index(vq))];
1450
1451    if (unlikely((n->status & VIRTIO_NET_S_LINK_UP) == 0)) {
1452        virtio_net_drop_tx_queue_data(vdev, vq);
1453        return;
1454    }
1455
1456    if (unlikely(q->tx_waiting)) {
1457        return;
1458    }
1459    q->tx_waiting = 1;
1460    /* This happens when device was stopped but VCPU wasn't. */
1461    if (!vdev->vm_running) {
1462        return;
1463    }
1464    virtio_queue_set_notification(vq, 0);
1465    qemu_bh_schedule(q->tx_bh);
1466}
1467
1468static void virtio_net_tx_timer(void *opaque)
1469{
1470    VirtIONetQueue *q = opaque;
1471    VirtIONet *n = q->n;
1472    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1473    /* This happens when device was stopped but BH wasn't. */
1474    if (!vdev->vm_running) {
1475        /* Make sure tx waiting is set, so we'll run when restarted. */
1476        assert(q->tx_waiting);
1477        return;
1478    }
1479
1480    q->tx_waiting = 0;
1481
1482    /* Just in case the driver is not ready on more */
1483    if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1484        return;
1485    }
1486
1487    virtio_queue_set_notification(q->tx_vq, 1);
1488    virtio_net_flush_tx(q);
1489}
1490
1491static void virtio_net_tx_bh(void *opaque)
1492{
1493    VirtIONetQueue *q = opaque;
1494    VirtIONet *n = q->n;
1495    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1496    int32_t ret;
1497
1498    /* This happens when device was stopped but BH wasn't. */
1499    if (!vdev->vm_running) {
1500        /* Make sure tx waiting is set, so we'll run when restarted. */
1501        assert(q->tx_waiting);
1502        return;
1503    }
1504
1505    q->tx_waiting = 0;
1506
1507    /* Just in case the driver is not ready on more */
1508    if (unlikely(!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))) {
1509        return;
1510    }
1511
1512    ret = virtio_net_flush_tx(q);
1513    if (ret == -EBUSY || ret == -EINVAL) {
1514        return; /* Notification re-enable handled by tx_complete or device
1515                 * broken */
1516    }
1517
1518    /* If we flush a full burst of packets, assume there are
1519     * more coming and immediately reschedule */
1520    if (ret >= n->tx_burst) {
1521        qemu_bh_schedule(q->tx_bh);
1522        q->tx_waiting = 1;
1523        return;
1524    }
1525
1526    /* If less than a full burst, re-enable notification and flush
1527     * anything that may have come in while we weren't looking.  If
1528     * we find something, assume the guest is still active and reschedule */
1529    virtio_queue_set_notification(q->tx_vq, 1);
1530    ret = virtio_net_flush_tx(q);
1531    if (ret == -EINVAL) {
1532        return;
1533    } else if (ret > 0) {
1534        virtio_queue_set_notification(q->tx_vq, 0);
1535        qemu_bh_schedule(q->tx_bh);
1536        q->tx_waiting = 1;
1537    }
1538}
1539
1540static void virtio_net_add_queue(VirtIONet *n, int index)
1541{
1542    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1543
1544    n->vqs[index].rx_vq = virtio_add_queue(vdev, n->net_conf.rx_queue_size,
1545                                           virtio_net_handle_rx);
1546
1547    if (n->net_conf.tx && !strcmp(n->net_conf.tx, "timer")) {
1548        n->vqs[index].tx_vq =
1549            virtio_add_queue(vdev, n->net_conf.tx_queue_size,
1550                             virtio_net_handle_tx_timer);
1551        n->vqs[index].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
1552                                              virtio_net_tx_timer,
1553                                              &n->vqs[index]);
1554    } else {
1555        n->vqs[index].tx_vq =
1556            virtio_add_queue(vdev, n->net_conf.tx_queue_size,
1557                             virtio_net_handle_tx_bh);
1558        n->vqs[index].tx_bh = qemu_bh_new(virtio_net_tx_bh, &n->vqs[index]);
1559    }
1560
1561    n->vqs[index].tx_waiting = 0;
1562    n->vqs[index].n = n;
1563}
1564
1565static void virtio_net_del_queue(VirtIONet *n, int index)
1566{
1567    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1568    VirtIONetQueue *q = &n->vqs[index];
1569    NetClientState *nc = qemu_get_subqueue(n->nic, index);
1570
1571    qemu_purge_queued_packets(nc);
1572
1573    virtio_del_queue(vdev, index * 2);
1574    if (q->tx_timer) {
1575        timer_del(q->tx_timer);
1576        timer_free(q->tx_timer);
1577        q->tx_timer = NULL;
1578    } else {
1579        qemu_bh_delete(q->tx_bh);
1580        q->tx_bh = NULL;
1581    }
1582    q->tx_waiting = 0;
1583    virtio_del_queue(vdev, index * 2 + 1);
1584}
1585
1586static void virtio_net_change_num_queues(VirtIONet *n, int new_max_queues)
1587{
1588    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1589    int old_num_queues = virtio_get_num_queues(vdev);
1590    int new_num_queues = new_max_queues * 2 + 1;
1591    int i;
1592
1593    assert(old_num_queues >= 3);
1594    assert(old_num_queues % 2 == 1);
1595
1596    if (old_num_queues == new_num_queues) {
1597        return;
1598    }
1599
1600    /*
1601     * We always need to remove and add ctrl vq if
1602     * old_num_queues != new_num_queues. Remove ctrl_vq first,
1603     * and then we only enter one of the following too loops.
1604     */
1605    virtio_del_queue(vdev, old_num_queues - 1);
1606
1607    for (i = new_num_queues - 1; i < old_num_queues - 1; i += 2) {
1608        /* new_num_queues < old_num_queues */
1609        virtio_net_del_queue(n, i / 2);
1610    }
1611
1612    for (i = old_num_queues - 1; i < new_num_queues - 1; i += 2) {
1613        /* new_num_queues > old_num_queues */
1614        virtio_net_add_queue(n, i / 2);
1615    }
1616
1617    /* add ctrl_vq last */
1618    n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);
1619}
1620
1621static void virtio_net_set_multiqueue(VirtIONet *n, int multiqueue)
1622{
1623    int max = multiqueue ? n->max_queues : 1;
1624
1625    n->multiqueue = multiqueue;
1626    virtio_net_change_num_queues(n, max);
1627
1628    virtio_net_set_queues(n);
1629}
1630
1631static int virtio_net_post_load_device(void *opaque, int version_id)
1632{
1633    VirtIONet *n = opaque;
1634    VirtIODevice *vdev = VIRTIO_DEVICE(n);
1635    int i, link_down;
1636
1637    virtio_net_set_mrg_rx_bufs(n, n->mergeable_rx_bufs,
1638                               virtio_vdev_has_feature(vdev,
1639                                                       VIRTIO_F_VERSION_1));
1640
1641    /* MAC_TABLE_ENTRIES may be different from the saved image */
1642    if (n->mac_table.in_use > MAC_TABLE_ENTRIES) {
1643        n->mac_table.in_use = 0;
1644    }
1645
1646    if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)) {
1647        n->curr_guest_offloads = virtio_net_supported_guest_offloads(n);
1648    }
1649
1650    if (peer_has_vnet_hdr(n)) {
1651        virtio_net_apply_guest_offloads(n);
1652    }
1653
1654    virtio_net_set_queues(n);
1655
1656    /* Find the first multicast entry in the saved MAC filter */
1657    for (i = 0; i < n->mac_table.in_use; i++) {
1658        if (n->mac_table.macs[i * ETH_ALEN] & 1) {
1659            break;
1660        }
1661    }
1662    n->mac_table.first_multi = i;
1663
1664    /* nc.link_down can't be migrated, so infer link_down according
1665     * to link status bit in n->status */
1666    link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0;
1667    for (i = 0; i < n->max_queues; i++) {
1668        qemu_get_subqueue(n->nic, i)->link_down = link_down;
1669    }
1670
1671    if (virtio_vdev_has_feature(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE) &&
1672        virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) {
1673        n->announce_counter = SELF_ANNOUNCE_ROUNDS;
1674        timer_mod(n->announce_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL));
1675    }
1676
1677    return 0;
1678}
1679
1680/* tx_waiting field of a VirtIONetQueue */
1681static const VMStateDescription vmstate_virtio_net_queue_tx_waiting = {
1682    .name = "virtio-net-queue-tx_waiting",
1683    .fields = (VMStateField[]) {
1684        VMSTATE_UINT32(tx_waiting, VirtIONetQueue),
1685        VMSTATE_END_OF_LIST()
1686   },
1687};
1688
1689static bool max_queues_gt_1(void *opaque, int version_id)
1690{
1691    return VIRTIO_NET(opaque)->max_queues > 1;
1692}
1693
1694static bool has_ctrl_guest_offloads(void *opaque, int version_id)
1695{
1696    return virtio_vdev_has_feature(VIRTIO_DEVICE(opaque),
1697                                   VIRTIO_NET_F_CTRL_GUEST_OFFLOADS);
1698}
1699
1700static bool mac_table_fits(void *opaque, int version_id)
1701{
1702    return VIRTIO_NET(opaque)->mac_table.in_use <= MAC_TABLE_ENTRIES;
1703}
1704
1705static bool mac_table_doesnt_fit(void *opaque, int version_id)
1706{
1707    return !mac_table_fits(opaque, version_id);
1708}
1709
1710/* This temporary type is shared by all the WITH_TMP methods
1711 * although only some fields are used by each.
1712 */
1713struct VirtIONetMigTmp {
1714    VirtIONet      *parent;
1715    VirtIONetQueue *vqs_1;
1716    uint16_t        curr_queues_1;
1717    uint8_t         has_ufo;
1718    uint32_t        has_vnet_hdr;
1719};
1720
1721/* The 2nd and subsequent tx_waiting flags are loaded later than
1722 * the 1st entry in the queues and only if there's more than one
1723 * entry.  We use the tmp mechanism to calculate a temporary
1724 * pointer and count and also validate the count.
1725 */
1726
1727static int virtio_net_tx_waiting_pre_save(void *opaque)
1728{
1729    struct VirtIONetMigTmp *tmp = opaque;
1730
1731    tmp->vqs_1 = tmp->parent->vqs + 1;
1732    tmp->curr_queues_1 = tmp->parent->curr_queues - 1;
1733    if (tmp->parent->curr_queues == 0) {
1734        tmp->curr_queues_1 = 0;
1735    }
1736
1737    return 0;
1738}
1739
1740static int virtio_net_tx_waiting_pre_load(void *opaque)
1741{
1742    struct VirtIONetMigTmp *tmp = opaque;
1743
1744    /* Reuse the pointer setup from save */
1745    virtio_net_tx_waiting_pre_save(opaque);
1746
1747    if (tmp->parent->curr_queues > tmp->parent->max_queues) {
1748        error_report("virtio-net: curr_queues %x > max_queues %x",
1749            tmp->parent->curr_queues, tmp->parent->max_queues);
1750
1751        return -EINVAL;
1752    }
1753
1754    return 0; /* all good */
1755}
1756
1757static const VMStateDescription vmstate_virtio_net_tx_waiting = {
1758    .name      = "virtio-net-tx_waiting",
1759    .pre_load  = virtio_net_tx_waiting_pre_load,
1760    .pre_save  = virtio_net_tx_waiting_pre_save,
1761    .fields    = (VMStateField[]) {
1762        VMSTATE_STRUCT_VARRAY_POINTER_UINT16(vqs_1, struct VirtIONetMigTmp,
1763                                     curr_queues_1,
1764                                     vmstate_virtio_net_queue_tx_waiting,
1765                                     struct VirtIONetQueue),
1766        VMSTATE_END_OF_LIST()
1767    },
1768};
1769
1770/* the 'has_ufo' flag is just tested; if the incoming stream has the
1771 * flag set we need to check that we have it
1772 */
1773static int virtio_net_ufo_post_load(void *opaque, int version_id)
1774{
1775    struct VirtIONetMigTmp *tmp = opaque;
1776
1777    if (tmp->has_ufo && !peer_has_ufo(tmp->parent)) {
1778        error_report("virtio-net: saved image requires TUN_F_UFO support");
1779        return -EINVAL;
1780    }
1781
1782    return 0;
1783}
1784
1785static int virtio_net_ufo_pre_save(void *opaque)
1786{
1787    struct VirtIONetMigTmp *tmp = opaque;
1788
1789    tmp->has_ufo = tmp->parent->has_ufo;
1790
1791    return 0;
1792}
1793
1794static const VMStateDescription vmstate_virtio_net_has_ufo = {
1795    .name      = "virtio-net-ufo",
1796    .post_load = virtio_net_ufo_post_load,
1797    .pre_save  = virtio_net_ufo_pre_save,
1798    .fields    = (VMStateField[]) {
1799        VMSTATE_UINT8(has_ufo, struct VirtIONetMigTmp),
1800        VMSTATE_END_OF_LIST()
1801    },
1802};
1803
1804/* the 'has_vnet_hdr' flag is just tested; if the incoming stream has the
1805 * flag set we need to check that we have it
1806 */
1807static int virtio_net_vnet_post_load(void *opaque, int version_id)
1808{
1809    struct VirtIONetMigTmp *tmp = opaque;
1810
1811    if (tmp->has_vnet_hdr && !peer_has_vnet_hdr(tmp->parent)) {
1812        error_report("virtio-net: saved image requires vnet_hdr=on");
1813        return -EINVAL;
1814    }
1815
1816    return 0;
1817}
1818
1819static int virtio_net_vnet_pre_save(void *opaque)
1820{
1821    struct VirtIONetMigTmp *tmp = opaque;
1822
1823    tmp->has_vnet_hdr = tmp->parent->has_vnet_hdr;
1824
1825    return 0;
1826}
1827
1828static const VMStateDescription vmstate_virtio_net_has_vnet = {
1829    .name      = "virtio-net-vnet",
1830    .post_load = virtio_net_vnet_post_load,
1831    .pre_save  = virtio_net_vnet_pre_save,
1832    .fields    = (VMStateField[]) {
1833        VMSTATE_UINT32(has_vnet_hdr, struct VirtIONetMigTmp),
1834        VMSTATE_END_OF_LIST()
1835    },
1836};
1837
1838static const VMStateDescription vmstate_virtio_net_device = {
1839    .name = "virtio-net-device",
1840    .version_id = VIRTIO_NET_VM_VERSION,
1841    .minimum_version_id = VIRTIO_NET_VM_VERSION,
1842    .post_load = virtio_net_post_load_device,
1843    .fields = (VMStateField[]) {
1844        VMSTATE_UINT8_ARRAY(mac, VirtIONet, ETH_ALEN),
1845        VMSTATE_STRUCT_POINTER(vqs, VirtIONet,
1846                               vmstate_virtio_net_queue_tx_waiting,
1847                               VirtIONetQueue),
1848        VMSTATE_UINT32(mergeable_rx_bufs, VirtIONet),
1849        VMSTATE_UINT16(status, VirtIONet),
1850        VMSTATE_UINT8(promisc, VirtIONet),
1851        VMSTATE_UINT8(allmulti, VirtIONet),
1852        VMSTATE_UINT32(mac_table.in_use, VirtIONet),
1853
1854        /* Guarded pair: If it fits we load it, else we throw it away
1855         * - can happen if source has a larger MAC table.; post-load
1856         *  sets flags in this case.
1857         */
1858        VMSTATE_VBUFFER_MULTIPLY(mac_table.macs, VirtIONet,
1859                                0, mac_table_fits, mac_table.in_use,
1860                                 ETH_ALEN),
1861        VMSTATE_UNUSED_VARRAY_UINT32(VirtIONet, mac_table_doesnt_fit, 0,
1862                                     mac_table.in_use, ETH_ALEN),
1863
1864        /* Note: This is an array of uint32's that's always been saved as a
1865         * buffer; hold onto your endiannesses; it's actually used as a bitmap
1866         * but based on the uint.
1867         */
1868        VMSTATE_BUFFER_POINTER_UNSAFE(vlans, VirtIONet, 0, MAX_VLAN >> 3),
1869        VMSTATE_WITH_TMP(VirtIONet, struct VirtIONetMigTmp,
1870                         vmstate_virtio_net_has_vnet),
1871        VMSTATE_UINT8(mac_table.multi_overflow, VirtIONet),
1872        VMSTATE_UINT8(mac_table.uni_overflow, VirtIONet),
1873        VMSTATE_UINT8(alluni, VirtIONet),
1874        VMSTATE_UINT8(nomulti, VirtIONet),
1875        VMSTATE_UINT8(nouni, VirtIONet),
1876        VMSTATE_UINT8(nobcast, VirtIONet),
1877        VMSTATE_WITH_TMP(VirtIONet, struct VirtIONetMigTmp,
1878                         vmstate_virtio_net_has_ufo),
1879        VMSTATE_SINGLE_TEST(max_queues, VirtIONet, max_queues_gt_1, 0,
1880                            vmstate_info_uint16_equal, uint16_t),
1881        VMSTATE_UINT16_TEST(curr_queues, VirtIONet, max_queues_gt_1),
1882        VMSTATE_WITH_TMP(VirtIONet, struct VirtIONetMigTmp,
1883                         vmstate_virtio_net_tx_waiting),
1884        VMSTATE_UINT64_TEST(curr_guest_offloads, VirtIONet,
1885                            has_ctrl_guest_offloads),
1886        VMSTATE_END_OF_LIST()
1887   },
1888};
1889
1890static NetClientInfo net_virtio_info = {
1891    .type = NET_CLIENT_DRIVER_NIC,
1892    .size = sizeof(NICState),
1893    .can_receive = virtio_net_can_receive,
1894    .receive = virtio_net_receive,
1895    .link_status_changed = virtio_net_set_link_status,
1896    .query_rx_filter = virtio_net_query_rxfilter,
1897};
1898
1899static bool virtio_net_guest_notifier_pending(VirtIODevice *vdev, int idx)
1900{
1901    VirtIONet *n = VIRTIO_NET(vdev);
1902    NetClientState *nc = qemu_get_subqueue(n->nic, vq2q(idx));
1903    assert(n->vhost_started);
1904    return vhost_net_virtqueue_pending(get_vhost_net(nc->peer), idx);
1905}
1906
1907static void virtio_net_guest_notifier_mask(VirtIODevice *vdev, int idx,
1908                                           bool mask)
1909{
1910    VirtIONet *n = VIRTIO_NET(vdev);
1911    NetClientState *nc = qemu_get_subqueue(n->nic, vq2q(idx));
1912    assert(n->vhost_started);
1913    vhost_net_virtqueue_mask(get_vhost_net(nc->peer),
1914                             vdev, idx, mask);
1915}
1916
1917static void virtio_net_set_config_size(VirtIONet *n, uint64_t host_features)
1918{
1919    int i, config_size = 0;
1920    virtio_add_feature(&host_features, VIRTIO_NET_F_MAC);
1921
1922    for (i = 0; feature_sizes[i].flags != 0; i++) {
1923        if (host_features & feature_sizes[i].flags) {
1924            config_size = MAX(feature_sizes[i].end, config_size);
1925        }
1926    }
1927    n->config_size = config_size;
1928}
1929
1930void virtio_net_set_netclient_name(VirtIONet *n, const char *name,
1931                                   const char *type)
1932{
1933    /*
1934     * The name can be NULL, the netclient name will be type.x.
1935     */
1936    assert(type != NULL);
1937
1938    g_free(n->netclient_name);
1939    g_free(n->netclient_type);
1940    n->netclient_name = g_strdup(name);
1941    n->netclient_type = g_strdup(type);
1942}
1943
1944static void virtio_net_device_realize(DeviceState *dev, Error **errp)
1945{
1946    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1947    VirtIONet *n = VIRTIO_NET(dev);
1948    NetClientState *nc;
1949    int i;
1950
1951    if (n->net_conf.mtu) {
1952        n->host_features |= (0x1 << VIRTIO_NET_F_MTU);
1953    }
1954
1955    virtio_net_set_config_size(n, n->host_features);
1956    virtio_init(vdev, "virtio-net", VIRTIO_ID_NET, n->config_size);
1957
1958    /*
1959     * We set a lower limit on RX queue size to what it always was.
1960     * Guests that want a smaller ring can always resize it without
1961     * help from us (using virtio 1 and up).
1962     */
1963    if (n->net_conf.rx_queue_size < VIRTIO_NET_RX_QUEUE_MIN_SIZE ||
1964        n->net_conf.rx_queue_size > VIRTQUEUE_MAX_SIZE ||
1965        !is_power_of_2(n->net_conf.rx_queue_size)) {
1966        error_setg(errp, "Invalid rx_queue_size (= %" PRIu16 "), "
1967                   "must be a power of 2 between %d and %d.",
1968                   n->net_conf.rx_queue_size, VIRTIO_NET_RX_QUEUE_MIN_SIZE,
1969                   VIRTQUEUE_MAX_SIZE);
1970        virtio_cleanup(vdev);
1971        return;
1972    }
1973
1974    if (n->net_conf.tx_queue_size < VIRTIO_NET_TX_QUEUE_MIN_SIZE ||
1975        n->net_conf.tx_queue_size > VIRTQUEUE_MAX_SIZE ||
1976        !is_power_of_2(n->net_conf.tx_queue_size)) {
1977        error_setg(errp, "Invalid tx_queue_size (= %" PRIu16 "), "
1978                   "must be a power of 2 between %d and %d",
1979                   n->net_conf.tx_queue_size, VIRTIO_NET_TX_QUEUE_MIN_SIZE,
1980                   VIRTQUEUE_MAX_SIZE);
1981        virtio_cleanup(vdev);
1982        return;
1983    }
1984
1985    n->max_queues = MAX(n->nic_conf.peers.queues, 1);
1986    if (n->max_queues * 2 + 1 > VIRTIO_QUEUE_MAX) {
1987        error_setg(errp, "Invalid number of queues (= %" PRIu32 "), "
1988                   "must be a positive integer less than %d.",
1989                   n->max_queues, (VIRTIO_QUEUE_MAX - 1) / 2);
1990        virtio_cleanup(vdev);
1991        return;
1992    }
1993    n->vqs = g_malloc0(sizeof(VirtIONetQueue) * n->max_queues);
1994    n->curr_queues = 1;
1995    n->tx_timeout = n->net_conf.txtimer;
1996
1997    if (n->net_conf.tx && strcmp(n->net_conf.tx, "timer")
1998                       && strcmp(n->net_conf.tx, "bh")) {
1999        error_report("virtio-net: "
2000                     "Unknown option tx=%s, valid options: \"timer\" \"bh\"",
2001                     n->net_conf.tx);
2002        error_report("Defaulting to \"bh\"");
2003    }
2004
2005    n->net_conf.tx_queue_size = MIN(virtio_net_max_tx_queue_size(n),
2006                                    n->net_conf.tx_queue_size);
2007
2008    for (i = 0; i < n->max_queues; i++) {
2009        virtio_net_add_queue(n, i);
2010    }
2011
2012    n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);
2013    qemu_macaddr_default_if_unset(&n->nic_conf.macaddr);
2014    memcpy(&n->mac[0], &n->nic_conf.macaddr, sizeof(n->mac));
2015    n->status = VIRTIO_NET_S_LINK_UP;
2016    n->announce_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
2017                                     virtio_net_announce_timer, n);
2018
2019    if (n->netclient_type) {
2020        /*
2021         * Happen when virtio_net_set_netclient_name has been called.
2022         */
2023        n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,
2024                              n->netclient_type, n->netclient_name, n);
2025    } else {
2026        n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,
2027                              object_get_typename(OBJECT(dev)), dev->id, n);
2028    }
2029
2030    peer_test_vnet_hdr(n);
2031    if (peer_has_vnet_hdr(n)) {
2032        for (i = 0; i < n->max_queues; i++) {
2033            qemu_using_vnet_hdr(qemu_get_subqueue(n->nic, i)->peer, true);
2034        }
2035        n->host_hdr_len = sizeof(struct virtio_net_hdr);
2036    } else {
2037        n->host_hdr_len = 0;
2038    }
2039
2040    qemu_format_nic_info_str(qemu_get_queue(n->nic), n->nic_conf.macaddr.a);
2041
2042    n->vqs[0].tx_waiting = 0;
2043    n->tx_burst = n->net_conf.txburst;
2044    virtio_net_set_mrg_rx_bufs(n, 0, 0);
2045    n->promisc = 1; /* for compatibility */
2046
2047    n->mac_table.macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN);
2048
2049    n->vlans = g_malloc0(MAX_VLAN >> 3);
2050
2051    nc = qemu_get_queue(n->nic);
2052    nc->rxfilter_notify_enabled = 1;
2053
2054    n->qdev = dev;
2055}
2056
2057static void virtio_net_device_unrealize(DeviceState *dev, Error **errp)
2058{
2059    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
2060    VirtIONet *n = VIRTIO_NET(dev);
2061    int i, max_queues;
2062
2063    /* This will stop vhost backend if appropriate. */
2064    virtio_net_set_status(vdev, 0);
2065
2066    g_free(n->netclient_name);
2067    n->netclient_name = NULL;
2068    g_free(n->netclient_type);
2069    n->netclient_type = NULL;
2070
2071    g_free(n->mac_table.macs);
2072    g_free(n->vlans);
2073
2074    max_queues = n->multiqueue ? n->max_queues : 1;
2075    for (i = 0; i < max_queues; i++) {
2076        virtio_net_del_queue(n, i);
2077    }
2078
2079    timer_del(n->announce_timer);
2080    timer_free(n->announce_timer);
2081    g_free(n->vqs);
2082    qemu_del_nic(n->nic);
2083    virtio_cleanup(vdev);
2084}
2085
2086static void virtio_net_instance_init(Object *obj)
2087{
2088    VirtIONet *n = VIRTIO_NET(obj);
2089
2090    /*
2091     * The default config_size is sizeof(struct virtio_net_config).
2092     * Can be overriden with virtio_net_set_config_size.
2093     */
2094    n->config_size = sizeof(struct virtio_net_config);
2095    device_add_bootindex_property(obj, &n->nic_conf.bootindex,
2096                                  "bootindex", "/ethernet-phy@0",
2097                                  DEVICE(n), NULL);
2098}
2099
2100static int virtio_net_pre_save(void *opaque)
2101{
2102    VirtIONet *n = opaque;
2103
2104    /* At this point, backend must be stopped, otherwise
2105     * it might keep writing to memory. */
2106    assert(!n->vhost_started);
2107
2108    return 0;
2109}
2110
2111static const VMStateDescription vmstate_virtio_net = {
2112    .name = "virtio-net",
2113    .minimum_version_id = VIRTIO_NET_VM_VERSION,
2114    .version_id = VIRTIO_NET_VM_VERSION,
2115    .fields = (VMStateField[]) {
2116        VMSTATE_VIRTIO_DEVICE,
2117        VMSTATE_END_OF_LIST()
2118    },
2119    .pre_save = virtio_net_pre_save,
2120};
2121
2122static Property virtio_net_properties[] = {
2123    DEFINE_PROP_BIT("csum", VirtIONet, host_features, VIRTIO_NET_F_CSUM, true),
2124    DEFINE_PROP_BIT("guest_csum", VirtIONet, host_features,
2125                    VIRTIO_NET_F_GUEST_CSUM, true),
2126    DEFINE_PROP_BIT("gso", VirtIONet, host_features, VIRTIO_NET_F_GSO, true),
2127    DEFINE_PROP_BIT("guest_tso4", VirtIONet, host_features,
2128                    VIRTIO_NET_F_GUEST_TSO4, true),
2129    DEFINE_PROP_BIT("guest_tso6", VirtIONet, host_features,
2130                    VIRTIO_NET_F_GUEST_TSO6, true),
2131    DEFINE_PROP_BIT("guest_ecn", VirtIONet, host_features,
2132                    VIRTIO_NET_F_GUEST_ECN, true),
2133    DEFINE_PROP_BIT("guest_ufo", VirtIONet, host_features,
2134                    VIRTIO_NET_F_GUEST_UFO, true),
2135    DEFINE_PROP_BIT("guest_announce", VirtIONet, host_features,
2136                    VIRTIO_NET_F_GUEST_ANNOUNCE, true),
2137    DEFINE_PROP_BIT("host_tso4", VirtIONet, host_features,
2138                    VIRTIO_NET_F_HOST_TSO4, true),
2139    DEFINE_PROP_BIT("host_tso6", VirtIONet, host_features,
2140                    VIRTIO_NET_F_HOST_TSO6, true),
2141    DEFINE_PROP_BIT("host_ecn", VirtIONet, host_features,
2142                    VIRTIO_NET_F_HOST_ECN, true),
2143    DEFINE_PROP_BIT("host_ufo", VirtIONet, host_features,
2144                    VIRTIO_NET_F_HOST_UFO, true),
2145    DEFINE_PROP_BIT("mrg_rxbuf", VirtIONet, host_features,
2146                    VIRTIO_NET_F_MRG_RXBUF, true),
2147    DEFINE_PROP_BIT("status", VirtIONet, host_features,
2148                    VIRTIO_NET_F_STATUS, true),
2149    DEFINE_PROP_BIT("ctrl_vq", VirtIONet, host_features,
2150                    VIRTIO_NET_F_CTRL_VQ, true),
2151    DEFINE_PROP_BIT("ctrl_rx", VirtIONet, host_features,
2152                    VIRTIO_NET_F_CTRL_RX, true),
2153    DEFINE_PROP_BIT("ctrl_vlan", VirtIONet, host_features,
2154                    VIRTIO_NET_F_CTRL_VLAN, true),
2155    DEFINE_PROP_BIT("ctrl_rx_extra", VirtIONet, host_features,
2156                    VIRTIO_NET_F_CTRL_RX_EXTRA, true),
2157    DEFINE_PROP_BIT("ctrl_mac_addr", VirtIONet, host_features,
2158                    VIRTIO_NET_F_CTRL_MAC_ADDR, true),
2159    DEFINE_PROP_BIT("ctrl_guest_offloads", VirtIONet, host_features,
2160                    VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, true),
2161    DEFINE_PROP_BIT("mq", VirtIONet, host_features, VIRTIO_NET_F_MQ, false),
2162    DEFINE_NIC_PROPERTIES(VirtIONet, nic_conf),
2163    DEFINE_PROP_UINT32("x-txtimer", VirtIONet, net_conf.txtimer,
2164                       TX_TIMER_INTERVAL),
2165    DEFINE_PROP_INT32("x-txburst", VirtIONet, net_conf.txburst, TX_BURST),
2166    DEFINE_PROP_STRING("tx", VirtIONet, net_conf.tx),
2167    DEFINE_PROP_UINT16("rx_queue_size", VirtIONet, net_conf.rx_queue_size,
2168                       VIRTIO_NET_RX_QUEUE_DEFAULT_SIZE),
2169    DEFINE_PROP_UINT16("tx_queue_size", VirtIONet, net_conf.tx_queue_size,
2170                       VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE),
2171    DEFINE_PROP_UINT16("host_mtu", VirtIONet, net_conf.mtu, 0),
2172    DEFINE_PROP_BOOL("x-mtu-bypass-backend", VirtIONet, mtu_bypass_backend,
2173                     true),
2174    DEFINE_PROP_END_OF_LIST(),
2175};
2176
2177static void virtio_net_class_init(ObjectClass *klass, void *data)
2178{
2179    DeviceClass *dc = DEVICE_CLASS(klass);
2180    VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
2181
2182    dc->props = virtio_net_properties;
2183    dc->vmsd = &vmstate_virtio_net;
2184    set_bit(DEVICE_CATEGORY_NETWORK, dc->categories);
2185    vdc->realize = virtio_net_device_realize;
2186    vdc->unrealize = virtio_net_device_unrealize;
2187    vdc->get_config = virtio_net_get_config;
2188    vdc->set_config = virtio_net_set_config;
2189    vdc->get_features = virtio_net_get_features;
2190    vdc->set_features = virtio_net_set_features;
2191    vdc->bad_features = virtio_net_bad_features;
2192    vdc->reset = virtio_net_reset;
2193    vdc->set_status = virtio_net_set_status;
2194    vdc->guest_notifier_mask = virtio_net_guest_notifier_mask;
2195    vdc->guest_notifier_pending = virtio_net_guest_notifier_pending;
2196    vdc->legacy_features |= (0x1 << VIRTIO_NET_F_GSO);
2197    vdc->vmsd = &vmstate_virtio_net_device;
2198}
2199
2200static const TypeInfo virtio_net_info = {
2201    .name = TYPE_VIRTIO_NET,
2202    .parent = TYPE_VIRTIO_DEVICE,
2203    .instance_size = sizeof(VirtIONet),
2204    .instance_init = virtio_net_instance_init,
2205    .class_init = virtio_net_class_init,
2206};
2207
2208static void virtio_register_types(void)
2209{
2210    type_register_static(&virtio_net_info);
2211}
2212
2213type_init(virtio_register_types)
2214