linux/drivers/net/virtio_net.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/* A network driver using virtio.
   3 *
   4 * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
   5 */
   6//#define DEBUG
   7#include <linux/netdevice.h>
   8#include <linux/etherdevice.h>
   9#include <linux/ethtool.h>
  10#include <linux/module.h>
  11#include <linux/virtio.h>
  12#include <linux/virtio_net.h>
  13#include <linux/bpf.h>
  14#include <linux/bpf_trace.h>
  15#include <linux/scatterlist.h>
  16#include <linux/if_vlan.h>
  17#include <linux/slab.h>
  18#include <linux/cpu.h>
  19#include <linux/average.h>
  20#include <linux/filter.h>
  21#include <linux/kernel.h>
  22#include <net/route.h>
  23#include <net/xdp.h>
  24#include <net/net_failover.h>
  25
  26static int napi_weight = NAPI_POLL_WEIGHT;
  27module_param(napi_weight, int, 0444);
  28
  29static bool csum = true, gso = true, napi_tx = true;
  30module_param(csum, bool, 0444);
  31module_param(gso, bool, 0444);
  32module_param(napi_tx, bool, 0644);
  33
  34/* FIXME: MTU in config. */
  35#define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
  36#define GOOD_COPY_LEN   128
  37
  38#define VIRTNET_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
  39
  40/* Amount of XDP headroom to prepend to packets for use by xdp_adjust_head */
  41#define VIRTIO_XDP_HEADROOM 256
  42
  43/* Separating two types of XDP xmit */
  44#define VIRTIO_XDP_TX           BIT(0)
  45#define VIRTIO_XDP_REDIR        BIT(1)
  46
  47#define VIRTIO_XDP_FLAG BIT(0)
  48
  49/* RX packet size EWMA. The average packet size is used to determine the packet
  50 * buffer size when refilling RX rings. As the entire RX ring may be refilled
  51 * at once, the weight is chosen so that the EWMA will be insensitive to short-
  52 * term, transient changes in packet size.
  53 */
  54DECLARE_EWMA(pkt_len, 0, 64)
  55
  56#define VIRTNET_DRIVER_VERSION "1.0.0"
  57
  58static const unsigned long guest_offloads[] = {
  59        VIRTIO_NET_F_GUEST_TSO4,
  60        VIRTIO_NET_F_GUEST_TSO6,
  61        VIRTIO_NET_F_GUEST_ECN,
  62        VIRTIO_NET_F_GUEST_UFO,
  63        VIRTIO_NET_F_GUEST_CSUM
  64};
  65
  66#define GUEST_OFFLOAD_GRO_HW_MASK ((1ULL << VIRTIO_NET_F_GUEST_TSO4) | \
  67                                (1ULL << VIRTIO_NET_F_GUEST_TSO6) | \
  68                                (1ULL << VIRTIO_NET_F_GUEST_ECN)  | \
  69                                (1ULL << VIRTIO_NET_F_GUEST_UFO))
  70
  71struct virtnet_stat_desc {
  72        char desc[ETH_GSTRING_LEN];
  73        size_t offset;
  74};
  75
  76struct virtnet_sq_stats {
  77        struct u64_stats_sync syncp;
  78        u64 packets;
  79        u64 bytes;
  80        u64 xdp_tx;
  81        u64 xdp_tx_drops;
  82        u64 kicks;
  83};
  84
  85struct virtnet_rq_stats {
  86        struct u64_stats_sync syncp;
  87        u64 packets;
  88        u64 bytes;
  89        u64 drops;
  90        u64 xdp_packets;
  91        u64 xdp_tx;
  92        u64 xdp_redirects;
  93        u64 xdp_drops;
  94        u64 kicks;
  95};
  96
  97#define VIRTNET_SQ_STAT(m)      offsetof(struct virtnet_sq_stats, m)
  98#define VIRTNET_RQ_STAT(m)      offsetof(struct virtnet_rq_stats, m)
  99
 100static const struct virtnet_stat_desc virtnet_sq_stats_desc[] = {
 101        { "packets",            VIRTNET_SQ_STAT(packets) },
 102        { "bytes",              VIRTNET_SQ_STAT(bytes) },
 103        { "xdp_tx",             VIRTNET_SQ_STAT(xdp_tx) },
 104        { "xdp_tx_drops",       VIRTNET_SQ_STAT(xdp_tx_drops) },
 105        { "kicks",              VIRTNET_SQ_STAT(kicks) },
 106};
 107
 108static const struct virtnet_stat_desc virtnet_rq_stats_desc[] = {
 109        { "packets",            VIRTNET_RQ_STAT(packets) },
 110        { "bytes",              VIRTNET_RQ_STAT(bytes) },
 111        { "drops",              VIRTNET_RQ_STAT(drops) },
 112        { "xdp_packets",        VIRTNET_RQ_STAT(xdp_packets) },
 113        { "xdp_tx",             VIRTNET_RQ_STAT(xdp_tx) },
 114        { "xdp_redirects",      VIRTNET_RQ_STAT(xdp_redirects) },
 115        { "xdp_drops",          VIRTNET_RQ_STAT(xdp_drops) },
 116        { "kicks",              VIRTNET_RQ_STAT(kicks) },
 117};
 118
 119#define VIRTNET_SQ_STATS_LEN    ARRAY_SIZE(virtnet_sq_stats_desc)
 120#define VIRTNET_RQ_STATS_LEN    ARRAY_SIZE(virtnet_rq_stats_desc)
 121
 122/* Internal representation of a send virtqueue */
 123struct send_queue {
 124        /* Virtqueue associated with this send _queue */
 125        struct virtqueue *vq;
 126
 127        /* TX: fragments + linear part + virtio header */
 128        struct scatterlist sg[MAX_SKB_FRAGS + 2];
 129
 130        /* Name of the send queue: output.$index */
 131        char name[40];
 132
 133        struct virtnet_sq_stats stats;
 134
 135        struct napi_struct napi;
 136};
 137
 138/* Internal representation of a receive virtqueue */
 139struct receive_queue {
 140        /* Virtqueue associated with this receive_queue */
 141        struct virtqueue *vq;
 142
 143        struct napi_struct napi;
 144
 145        struct bpf_prog __rcu *xdp_prog;
 146
 147        struct virtnet_rq_stats stats;
 148
 149        /* Chain pages by the private ptr. */
 150        struct page *pages;
 151
 152        /* Average packet length for mergeable receive buffers. */
 153        struct ewma_pkt_len mrg_avg_pkt_len;
 154
 155        /* Page frag for packet buffer allocation. */
 156        struct page_frag alloc_frag;
 157
 158        /* RX: fragments + linear part + virtio header */
 159        struct scatterlist sg[MAX_SKB_FRAGS + 2];
 160
 161        /* Min single buffer size for mergeable buffers case. */
 162        unsigned int min_buf_len;
 163
 164        /* Name of this receive queue: input.$index */
 165        char name[40];
 166
 167        struct xdp_rxq_info xdp_rxq;
 168};
 169
 170/* Control VQ buffers: protected by the rtnl lock */
 171struct control_buf {
 172        struct virtio_net_ctrl_hdr hdr;
 173        virtio_net_ctrl_ack status;
 174        struct virtio_net_ctrl_mq mq;
 175        u8 promisc;
 176        u8 allmulti;
 177        __virtio16 vid;
 178        __virtio64 offloads;
 179};
 180
 181struct virtnet_info {
 182        struct virtio_device *vdev;
 183        struct virtqueue *cvq;
 184        struct net_device *dev;
 185        struct send_queue *sq;
 186        struct receive_queue *rq;
 187        unsigned int status;
 188
 189        /* Max # of queue pairs supported by the device */
 190        u16 max_queue_pairs;
 191
 192        /* # of queue pairs currently used by the driver */
 193        u16 curr_queue_pairs;
 194
 195        /* # of XDP queue pairs currently used by the driver */
 196        u16 xdp_queue_pairs;
 197
 198        /* xdp_queue_pairs may be 0, when xdp is already loaded. So add this. */
 199        bool xdp_enabled;
 200
 201        /* I like... big packets and I cannot lie! */
 202        bool big_packets;
 203
 204        /* Host will merge rx buffers for big packets (shake it! shake it!) */
 205        bool mergeable_rx_bufs;
 206
 207        /* Has control virtqueue */
 208        bool has_cvq;
 209
 210        /* Host can handle any s/g split between our header and packet data */
 211        bool any_header_sg;
 212
 213        /* Packet virtio header size */
 214        u8 hdr_len;
 215
 216        /* Work struct for refilling if we run low on memory. */
 217        struct delayed_work refill;
 218
 219        /* Work struct for config space updates */
 220        struct work_struct config_work;
 221
 222        /* Does the affinity hint is set for virtqueues? */
 223        bool affinity_hint_set;
 224
 225        /* CPU hotplug instances for online & dead */
 226        struct hlist_node node;
 227        struct hlist_node node_dead;
 228
 229        struct control_buf *ctrl;
 230
 231        /* Ethtool settings */
 232        u8 duplex;
 233        u32 speed;
 234
 235        unsigned long guest_offloads;
 236        unsigned long guest_offloads_capable;
 237
 238        /* failover when STANDBY feature enabled */
 239        struct failover *failover;
 240};
 241
 242struct padded_vnet_hdr {
 243        struct virtio_net_hdr_mrg_rxbuf hdr;
 244        /*
 245         * hdr is in a separate sg buffer, and data sg buffer shares same page
 246         * with this header sg. This padding makes next sg 16 byte aligned
 247         * after the header.
 248         */
 249        char padding[4];
 250};
 251
 252static bool is_xdp_frame(void *ptr)
 253{
 254        return (unsigned long)ptr & VIRTIO_XDP_FLAG;
 255}
 256
 257static void *xdp_to_ptr(struct xdp_frame *ptr)
 258{
 259        return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
 260}
 261
 262static struct xdp_frame *ptr_to_xdp(void *ptr)
 263{
 264        return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
 265}
 266
 267/* Converting between virtqueue no. and kernel tx/rx queue no.
 268 * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
 269 */
 270static int vq2txq(struct virtqueue *vq)
 271{
 272        return (vq->index - 1) / 2;
 273}
 274
 275static int txq2vq(int txq)
 276{
 277        return txq * 2 + 1;
 278}
 279
 280static int vq2rxq(struct virtqueue *vq)
 281{
 282        return vq->index / 2;
 283}
 284
 285static int rxq2vq(int rxq)
 286{
 287        return rxq * 2;
 288}
 289
 290static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
 291{
 292        return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
 293}
 294
 295/*
 296 * private is used to chain pages for big packets, put the whole
 297 * most recent used list in the beginning for reuse
 298 */
 299static void give_pages(struct receive_queue *rq, struct page *page)
 300{
 301        struct page *end;
 302
 303        /* Find end of list, sew whole thing into vi->rq.pages. */
 304        for (end = page; end->private; end = (struct page *)end->private);
 305        end->private = (unsigned long)rq->pages;
 306        rq->pages = page;
 307}
 308
 309static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
 310{
 311        struct page *p = rq->pages;
 312
 313        if (p) {
 314                rq->pages = (struct page *)p->private;
 315                /* clear private here, it is used to chain pages */
 316                p->private = 0;
 317        } else
 318                p = alloc_page(gfp_mask);
 319        return p;
 320}
 321
 322static void virtqueue_napi_schedule(struct napi_struct *napi,
 323                                    struct virtqueue *vq)
 324{
 325        if (napi_schedule_prep(napi)) {
 326                virtqueue_disable_cb(vq);
 327                __napi_schedule(napi);
 328        }
 329}
 330
 331static void virtqueue_napi_complete(struct napi_struct *napi,
 332                                    struct virtqueue *vq, int processed)
 333{
 334        int opaque;
 335
 336        opaque = virtqueue_enable_cb_prepare(vq);
 337        if (napi_complete_done(napi, processed)) {
 338                if (unlikely(virtqueue_poll(vq, opaque)))
 339                        virtqueue_napi_schedule(napi, vq);
 340        } else {
 341                virtqueue_disable_cb(vq);
 342        }
 343}
 344
 345static void skb_xmit_done(struct virtqueue *vq)
 346{
 347        struct virtnet_info *vi = vq->vdev->priv;
 348        struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
 349
 350        /* Suppress further interrupts. */
 351        virtqueue_disable_cb(vq);
 352
 353        if (napi->weight)
 354                virtqueue_napi_schedule(napi, vq);
 355        else
 356                /* We were probably waiting for more output buffers. */
 357                netif_wake_subqueue(vi->dev, vq2txq(vq));
 358}
 359
 360#define MRG_CTX_HEADER_SHIFT 22
 361static void *mergeable_len_to_ctx(unsigned int truesize,
 362                                  unsigned int headroom)
 363{
 364        return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
 365}
 366
 367static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
 368{
 369        return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
 370}
 371
 372static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
 373{
 374        return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
 375}
 376
 377/* Called from bottom half context */
 378static struct sk_buff *page_to_skb(struct virtnet_info *vi,
 379                                   struct receive_queue *rq,
 380                                   struct page *page, unsigned int offset,
 381                                   unsigned int len, unsigned int truesize,
 382                                   bool hdr_valid, unsigned int metasize,
 383                                   unsigned int headroom)
 384{
 385        struct sk_buff *skb;
 386        struct virtio_net_hdr_mrg_rxbuf *hdr;
 387        unsigned int copy, hdr_len, hdr_padded_len;
 388        struct page *page_to_free = NULL;
 389        int tailroom, shinfo_size;
 390        char *p, *hdr_p, *buf;
 391
 392        p = page_address(page) + offset;
 393        hdr_p = p;
 394
 395        hdr_len = vi->hdr_len;
 396        if (vi->mergeable_rx_bufs)
 397                hdr_padded_len = sizeof(*hdr);
 398        else
 399                hdr_padded_len = sizeof(struct padded_vnet_hdr);
 400
 401        /* If headroom is not 0, there is an offset between the beginning of the
 402         * data and the allocated space, otherwise the data and the allocated
 403         * space are aligned.
 404         *
 405         * Buffers with headroom use PAGE_SIZE as alloc size, see
 406         * add_recvbuf_mergeable() + get_mergeable_buf_len()
 407         */
 408        truesize = headroom ? PAGE_SIZE : truesize;
 409        tailroom = truesize - len - headroom - (hdr_padded_len - hdr_len);
 410        buf = p - headroom;
 411
 412        len -= hdr_len;
 413        offset += hdr_padded_len;
 414        p += hdr_padded_len;
 415
 416        shinfo_size = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
 417
 418        /* copy small packet so we can reuse these pages */
 419        if (!NET_IP_ALIGN && len > GOOD_COPY_LEN && tailroom >= shinfo_size) {
 420                skb = build_skb(buf, truesize);
 421                if (unlikely(!skb))
 422                        return NULL;
 423
 424                skb_reserve(skb, p - buf);
 425                skb_put(skb, len);
 426
 427                page = (struct page *)page->private;
 428                if (page)
 429                        give_pages(rq, page);
 430                goto ok;
 431        }
 432
 433        /* copy small packet so we can reuse these pages for small data */
 434        skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
 435        if (unlikely(!skb))
 436                return NULL;
 437
 438        /* Copy all frame if it fits skb->head, otherwise
 439         * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
 440         */
 441        if (len <= skb_tailroom(skb))
 442                copy = len;
 443        else
 444                copy = ETH_HLEN + metasize;
 445        skb_put_data(skb, p, copy);
 446
 447        len -= copy;
 448        offset += copy;
 449
 450        if (vi->mergeable_rx_bufs) {
 451                if (len)
 452                        skb_add_rx_frag(skb, 0, page, offset, len, truesize);
 453                else
 454                        page_to_free = page;
 455                goto ok;
 456        }
 457
 458        /*
 459         * Verify that we can indeed put this data into a skb.
 460         * This is here to handle cases when the device erroneously
 461         * tries to receive more than is possible. This is usually
 462         * the case of a broken device.
 463         */
 464        if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
 465                net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
 466                dev_kfree_skb(skb);
 467                return NULL;
 468        }
 469        BUG_ON(offset >= PAGE_SIZE);
 470        while (len) {
 471                unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
 472                skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
 473                                frag_size, truesize);
 474                len -= frag_size;
 475                page = (struct page *)page->private;
 476                offset = 0;
 477        }
 478
 479        if (page)
 480                give_pages(rq, page);
 481
 482ok:
 483        /* hdr_valid means no XDP, so we can copy the vnet header */
 484        if (hdr_valid) {
 485                hdr = skb_vnet_hdr(skb);
 486                memcpy(hdr, hdr_p, hdr_len);
 487        }
 488        if (page_to_free)
 489                put_page(page_to_free);
 490
 491        if (metasize) {
 492                __skb_pull(skb, metasize);
 493                skb_metadata_set(skb, metasize);
 494        }
 495
 496        return skb;
 497}
 498
 499static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
 500                                   struct send_queue *sq,
 501                                   struct xdp_frame *xdpf)
 502{
 503        struct virtio_net_hdr_mrg_rxbuf *hdr;
 504        int err;
 505
 506        if (unlikely(xdpf->headroom < vi->hdr_len))
 507                return -EOVERFLOW;
 508
 509        /* Make room for virtqueue hdr (also change xdpf->headroom?) */
 510        xdpf->data -= vi->hdr_len;
 511        /* Zero header and leave csum up to XDP layers */
 512        hdr = xdpf->data;
 513        memset(hdr, 0, vi->hdr_len);
 514        xdpf->len   += vi->hdr_len;
 515
 516        sg_init_one(sq->sg, xdpf->data, xdpf->len);
 517
 518        err = virtqueue_add_outbuf(sq->vq, sq->sg, 1, xdp_to_ptr(xdpf),
 519                                   GFP_ATOMIC);
 520        if (unlikely(err))
 521                return -ENOSPC; /* Caller handle free/refcnt */
 522
 523        return 0;
 524}
 525
 526/* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
 527 * the current cpu, so it does not need to be locked.
 528 *
 529 * Here we use marco instead of inline functions because we have to deal with
 530 * three issues at the same time: 1. the choice of sq. 2. judge and execute the
 531 * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
 532 * functions to perfectly solve these three problems at the same time.
 533 */
 534#define virtnet_xdp_get_sq(vi) ({                                       \
 535        int cpu = smp_processor_id();                                   \
 536        struct netdev_queue *txq;                                       \
 537        typeof(vi) v = (vi);                                            \
 538        unsigned int qp;                                                \
 539                                                                        \
 540        if (v->curr_queue_pairs > nr_cpu_ids) {                         \
 541                qp = v->curr_queue_pairs - v->xdp_queue_pairs;          \
 542                qp += cpu;                                              \
 543                txq = netdev_get_tx_queue(v->dev, qp);                  \
 544                __netif_tx_acquire(txq);                                \
 545        } else {                                                        \
 546                qp = cpu % v->curr_queue_pairs;                         \
 547                txq = netdev_get_tx_queue(v->dev, qp);                  \
 548                __netif_tx_lock(txq, cpu);                              \
 549        }                                                               \
 550        v->sq + qp;                                                     \
 551})
 552
 553#define virtnet_xdp_put_sq(vi, q) {                                     \
 554        struct netdev_queue *txq;                                       \
 555        typeof(vi) v = (vi);                                            \
 556                                                                        \
 557        txq = netdev_get_tx_queue(v->dev, (q) - v->sq);                 \
 558        if (v->curr_queue_pairs > nr_cpu_ids)                           \
 559                __netif_tx_release(txq);                                \
 560        else                                                            \
 561                __netif_tx_unlock(txq);                                 \
 562}
 563
 564static int virtnet_xdp_xmit(struct net_device *dev,
 565                            int n, struct xdp_frame **frames, u32 flags)
 566{
 567        struct virtnet_info *vi = netdev_priv(dev);
 568        struct receive_queue *rq = vi->rq;
 569        struct bpf_prog *xdp_prog;
 570        struct send_queue *sq;
 571        unsigned int len;
 572        int packets = 0;
 573        int bytes = 0;
 574        int nxmit = 0;
 575        int kicks = 0;
 576        void *ptr;
 577        int ret;
 578        int i;
 579
 580        /* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
 581         * indicate XDP resources have been successfully allocated.
 582         */
 583        xdp_prog = rcu_access_pointer(rq->xdp_prog);
 584        if (!xdp_prog)
 585                return -ENXIO;
 586
 587        sq = virtnet_xdp_get_sq(vi);
 588
 589        if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
 590                ret = -EINVAL;
 591                goto out;
 592        }
 593
 594        /* Free up any pending old buffers before queueing new ones. */
 595        while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
 596                if (likely(is_xdp_frame(ptr))) {
 597                        struct xdp_frame *frame = ptr_to_xdp(ptr);
 598
 599                        bytes += frame->len;
 600                        xdp_return_frame(frame);
 601                } else {
 602                        struct sk_buff *skb = ptr;
 603
 604                        bytes += skb->len;
 605                        napi_consume_skb(skb, false);
 606                }
 607                packets++;
 608        }
 609
 610        for (i = 0; i < n; i++) {
 611                struct xdp_frame *xdpf = frames[i];
 612
 613                if (__virtnet_xdp_xmit_one(vi, sq, xdpf))
 614                        break;
 615                nxmit++;
 616        }
 617        ret = nxmit;
 618
 619        if (flags & XDP_XMIT_FLUSH) {
 620                if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
 621                        kicks = 1;
 622        }
 623out:
 624        u64_stats_update_begin(&sq->stats.syncp);
 625        sq->stats.bytes += bytes;
 626        sq->stats.packets += packets;
 627        sq->stats.xdp_tx += n;
 628        sq->stats.xdp_tx_drops += n - nxmit;
 629        sq->stats.kicks += kicks;
 630        u64_stats_update_end(&sq->stats.syncp);
 631
 632        virtnet_xdp_put_sq(vi, sq);
 633        return ret;
 634}
 635
 636static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
 637{
 638        return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
 639}
 640
 641/* We copy the packet for XDP in the following cases:
 642 *
 643 * 1) Packet is scattered across multiple rx buffers.
 644 * 2) Headroom space is insufficient.
 645 *
 646 * This is inefficient but it's a temporary condition that
 647 * we hit right after XDP is enabled and until queue is refilled
 648 * with large buffers with sufficient headroom - so it should affect
 649 * at most queue size packets.
 650 * Afterwards, the conditions to enable
 651 * XDP should preclude the underlying device from sending packets
 652 * across multiple buffers (num_buf > 1), and we make sure buffers
 653 * have enough headroom.
 654 */
 655static struct page *xdp_linearize_page(struct receive_queue *rq,
 656                                       u16 *num_buf,
 657                                       struct page *p,
 658                                       int offset,
 659                                       int page_off,
 660                                       unsigned int *len)
 661{
 662        struct page *page = alloc_page(GFP_ATOMIC);
 663
 664        if (!page)
 665                return NULL;
 666
 667        memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
 668        page_off += *len;
 669
 670        while (--*num_buf) {
 671                int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
 672                unsigned int buflen;
 673                void *buf;
 674                int off;
 675
 676                buf = virtqueue_get_buf(rq->vq, &buflen);
 677                if (unlikely(!buf))
 678                        goto err_buf;
 679
 680                p = virt_to_head_page(buf);
 681                off = buf - page_address(p);
 682
 683                /* guard against a misconfigured or uncooperative backend that
 684                 * is sending packet larger than the MTU.
 685                 */
 686                if ((page_off + buflen + tailroom) > PAGE_SIZE) {
 687                        put_page(p);
 688                        goto err_buf;
 689                }
 690
 691                memcpy(page_address(page) + page_off,
 692                       page_address(p) + off, buflen);
 693                page_off += buflen;
 694                put_page(p);
 695        }
 696
 697        /* Headroom does not contribute to packet length */
 698        *len = page_off - VIRTIO_XDP_HEADROOM;
 699        return page;
 700err_buf:
 701        __free_pages(page, 0);
 702        return NULL;
 703}
 704
 705static struct sk_buff *receive_small(struct net_device *dev,
 706                                     struct virtnet_info *vi,
 707                                     struct receive_queue *rq,
 708                                     void *buf, void *ctx,
 709                                     unsigned int len,
 710                                     unsigned int *xdp_xmit,
 711                                     struct virtnet_rq_stats *stats)
 712{
 713        struct sk_buff *skb;
 714        struct bpf_prog *xdp_prog;
 715        unsigned int xdp_headroom = (unsigned long)ctx;
 716        unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
 717        unsigned int headroom = vi->hdr_len + header_offset;
 718        unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
 719                              SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
 720        struct page *page = virt_to_head_page(buf);
 721        unsigned int delta = 0;
 722        struct page *xdp_page;
 723        int err;
 724        unsigned int metasize = 0;
 725
 726        len -= vi->hdr_len;
 727        stats->bytes += len;
 728
 729        if (unlikely(len > GOOD_PACKET_LEN)) {
 730                pr_debug("%s: rx error: len %u exceeds max size %d\n",
 731                         dev->name, len, GOOD_PACKET_LEN);
 732                dev->stats.rx_length_errors++;
 733                goto err_len;
 734        }
 735        rcu_read_lock();
 736        xdp_prog = rcu_dereference(rq->xdp_prog);
 737        if (xdp_prog) {
 738                struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
 739                struct xdp_frame *xdpf;
 740                struct xdp_buff xdp;
 741                void *orig_data;
 742                u32 act;
 743
 744                if (unlikely(hdr->hdr.gso_type))
 745                        goto err_xdp;
 746
 747                if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
 748                        int offset = buf - page_address(page) + header_offset;
 749                        unsigned int tlen = len + vi->hdr_len;
 750                        u16 num_buf = 1;
 751
 752                        xdp_headroom = virtnet_get_headroom(vi);
 753                        header_offset = VIRTNET_RX_PAD + xdp_headroom;
 754                        headroom = vi->hdr_len + header_offset;
 755                        buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
 756                                 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
 757                        xdp_page = xdp_linearize_page(rq, &num_buf, page,
 758                                                      offset, header_offset,
 759                                                      &tlen);
 760                        if (!xdp_page)
 761                                goto err_xdp;
 762
 763                        buf = page_address(xdp_page);
 764                        put_page(page);
 765                        page = xdp_page;
 766                }
 767
 768                xdp_init_buff(&xdp, buflen, &rq->xdp_rxq);
 769                xdp_prepare_buff(&xdp, buf + VIRTNET_RX_PAD + vi->hdr_len,
 770                                 xdp_headroom, len, true);
 771                orig_data = xdp.data;
 772                act = bpf_prog_run_xdp(xdp_prog, &xdp);
 773                stats->xdp_packets++;
 774
 775                switch (act) {
 776                case XDP_PASS:
 777                        /* Recalculate length in case bpf program changed it */
 778                        delta = orig_data - xdp.data;
 779                        len = xdp.data_end - xdp.data;
 780                        metasize = xdp.data - xdp.data_meta;
 781                        break;
 782                case XDP_TX:
 783                        stats->xdp_tx++;
 784                        xdpf = xdp_convert_buff_to_frame(&xdp);
 785                        if (unlikely(!xdpf))
 786                                goto err_xdp;
 787                        err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
 788                        if (unlikely(!err)) {
 789                                xdp_return_frame_rx_napi(xdpf);
 790                        } else if (unlikely(err < 0)) {
 791                                trace_xdp_exception(vi->dev, xdp_prog, act);
 792                                goto err_xdp;
 793                        }
 794                        *xdp_xmit |= VIRTIO_XDP_TX;
 795                        rcu_read_unlock();
 796                        goto xdp_xmit;
 797                case XDP_REDIRECT:
 798                        stats->xdp_redirects++;
 799                        err = xdp_do_redirect(dev, &xdp, xdp_prog);
 800                        if (err)
 801                                goto err_xdp;
 802                        *xdp_xmit |= VIRTIO_XDP_REDIR;
 803                        rcu_read_unlock();
 804                        goto xdp_xmit;
 805                default:
 806                        bpf_warn_invalid_xdp_action(act);
 807                        fallthrough;
 808                case XDP_ABORTED:
 809                        trace_xdp_exception(vi->dev, xdp_prog, act);
 810                        goto err_xdp;
 811                case XDP_DROP:
 812                        goto err_xdp;
 813                }
 814        }
 815        rcu_read_unlock();
 816
 817        skb = build_skb(buf, buflen);
 818        if (!skb) {
 819                put_page(page);
 820                goto err;
 821        }
 822        skb_reserve(skb, headroom - delta);
 823        skb_put(skb, len);
 824        if (!xdp_prog) {
 825                buf += header_offset;
 826                memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
 827        } /* keep zeroed vnet hdr since XDP is loaded */
 828
 829        if (metasize)
 830                skb_metadata_set(skb, metasize);
 831
 832err:
 833        return skb;
 834
 835err_xdp:
 836        rcu_read_unlock();
 837        stats->xdp_drops++;
 838err_len:
 839        stats->drops++;
 840        put_page(page);
 841xdp_xmit:
 842        return NULL;
 843}
 844
 845static struct sk_buff *receive_big(struct net_device *dev,
 846                                   struct virtnet_info *vi,
 847                                   struct receive_queue *rq,
 848                                   void *buf,
 849                                   unsigned int len,
 850                                   struct virtnet_rq_stats *stats)
 851{
 852        struct page *page = buf;
 853        struct sk_buff *skb =
 854                page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, true, 0, 0);
 855
 856        stats->bytes += len - vi->hdr_len;
 857        if (unlikely(!skb))
 858                goto err;
 859
 860        return skb;
 861
 862err:
 863        stats->drops++;
 864        give_pages(rq, page);
 865        return NULL;
 866}
 867
 868static struct sk_buff *receive_mergeable(struct net_device *dev,
 869                                         struct virtnet_info *vi,
 870                                         struct receive_queue *rq,
 871                                         void *buf,
 872                                         void *ctx,
 873                                         unsigned int len,
 874                                         unsigned int *xdp_xmit,
 875                                         struct virtnet_rq_stats *stats)
 876{
 877        struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
 878        u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
 879        struct page *page = virt_to_head_page(buf);
 880        int offset = buf - page_address(page);
 881        struct sk_buff *head_skb, *curr_skb;
 882        struct bpf_prog *xdp_prog;
 883        unsigned int truesize = mergeable_ctx_to_truesize(ctx);
 884        unsigned int headroom = mergeable_ctx_to_headroom(ctx);
 885        unsigned int metasize = 0;
 886        unsigned int frame_sz;
 887        int err;
 888
 889        head_skb = NULL;
 890        stats->bytes += len - vi->hdr_len;
 891
 892        if (unlikely(len > truesize)) {
 893                pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
 894                         dev->name, len, (unsigned long)ctx);
 895                dev->stats.rx_length_errors++;
 896                goto err_skb;
 897        }
 898        rcu_read_lock();
 899        xdp_prog = rcu_dereference(rq->xdp_prog);
 900        if (xdp_prog) {
 901                struct xdp_frame *xdpf;
 902                struct page *xdp_page;
 903                struct xdp_buff xdp;
 904                void *data;
 905                u32 act;
 906
 907                /* Transient failure which in theory could occur if
 908                 * in-flight packets from before XDP was enabled reach
 909                 * the receive path after XDP is loaded.
 910                 */
 911                if (unlikely(hdr->hdr.gso_type))
 912                        goto err_xdp;
 913
 914                /* Buffers with headroom use PAGE_SIZE as alloc size,
 915                 * see add_recvbuf_mergeable() + get_mergeable_buf_len()
 916                 */
 917                frame_sz = headroom ? PAGE_SIZE : truesize;
 918
 919                /* This happens when rx buffer size is underestimated
 920                 * or headroom is not enough because of the buffer
 921                 * was refilled before XDP is set. This should only
 922                 * happen for the first several packets, so we don't
 923                 * care much about its performance.
 924                 */
 925                if (unlikely(num_buf > 1 ||
 926                             headroom < virtnet_get_headroom(vi))) {
 927                        /* linearize data for XDP */
 928                        xdp_page = xdp_linearize_page(rq, &num_buf,
 929                                                      page, offset,
 930                                                      VIRTIO_XDP_HEADROOM,
 931                                                      &len);
 932                        frame_sz = PAGE_SIZE;
 933
 934                        if (!xdp_page)
 935                                goto err_xdp;
 936                        offset = VIRTIO_XDP_HEADROOM;
 937                } else {
 938                        xdp_page = page;
 939                }
 940
 941                /* Allow consuming headroom but reserve enough space to push
 942                 * the descriptor on if we get an XDP_TX return code.
 943                 */
 944                data = page_address(xdp_page) + offset;
 945                xdp_init_buff(&xdp, frame_sz - vi->hdr_len, &rq->xdp_rxq);
 946                xdp_prepare_buff(&xdp, data - VIRTIO_XDP_HEADROOM + vi->hdr_len,
 947                                 VIRTIO_XDP_HEADROOM, len - vi->hdr_len, true);
 948
 949                act = bpf_prog_run_xdp(xdp_prog, &xdp);
 950                stats->xdp_packets++;
 951
 952                switch (act) {
 953                case XDP_PASS:
 954                        metasize = xdp.data - xdp.data_meta;
 955
 956                        /* recalculate offset to account for any header
 957                         * adjustments and minus the metasize to copy the
 958                         * metadata in page_to_skb(). Note other cases do not
 959                         * build an skb and avoid using offset
 960                         */
 961                        offset = xdp.data - page_address(xdp_page) -
 962                                 vi->hdr_len - metasize;
 963
 964                        /* recalculate len if xdp.data, xdp.data_end or
 965                         * xdp.data_meta were adjusted
 966                         */
 967                        len = xdp.data_end - xdp.data + vi->hdr_len + metasize;
 968                        /* We can only create skb based on xdp_page. */
 969                        if (unlikely(xdp_page != page)) {
 970                                rcu_read_unlock();
 971                                put_page(page);
 972                                head_skb = page_to_skb(vi, rq, xdp_page, offset,
 973                                                       len, PAGE_SIZE, false,
 974                                                       metasize,
 975                                                       VIRTIO_XDP_HEADROOM);
 976                                return head_skb;
 977                        }
 978                        break;
 979                case XDP_TX:
 980                        stats->xdp_tx++;
 981                        xdpf = xdp_convert_buff_to_frame(&xdp);
 982                        if (unlikely(!xdpf))
 983                                goto err_xdp;
 984                        err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
 985                        if (unlikely(!err)) {
 986                                xdp_return_frame_rx_napi(xdpf);
 987                        } else if (unlikely(err < 0)) {
 988                                trace_xdp_exception(vi->dev, xdp_prog, act);
 989                                if (unlikely(xdp_page != page))
 990                                        put_page(xdp_page);
 991                                goto err_xdp;
 992                        }
 993                        *xdp_xmit |= VIRTIO_XDP_TX;
 994                        if (unlikely(xdp_page != page))
 995                                put_page(page);
 996                        rcu_read_unlock();
 997                        goto xdp_xmit;
 998                case XDP_REDIRECT:
 999                        stats->xdp_redirects++;
1000                        err = xdp_do_redirect(dev, &xdp, xdp_prog);
1001                        if (err) {
1002                                if (unlikely(xdp_page != page))
1003                                        put_page(xdp_page);
1004                                goto err_xdp;
1005                        }
1006                        *xdp_xmit |= VIRTIO_XDP_REDIR;
1007                        if (unlikely(xdp_page != page))
1008                                put_page(page);
1009                        rcu_read_unlock();
1010                        goto xdp_xmit;
1011                default:
1012                        bpf_warn_invalid_xdp_action(act);
1013                        fallthrough;
1014                case XDP_ABORTED:
1015                        trace_xdp_exception(vi->dev, xdp_prog, act);
1016                        fallthrough;
1017                case XDP_DROP:
1018                        if (unlikely(xdp_page != page))
1019                                __free_pages(xdp_page, 0);
1020                        goto err_xdp;
1021                }
1022        }
1023        rcu_read_unlock();
1024
1025        head_skb = page_to_skb(vi, rq, page, offset, len, truesize, !xdp_prog,
1026                               metasize, headroom);
1027        curr_skb = head_skb;
1028
1029        if (unlikely(!curr_skb))
1030                goto err_skb;
1031        while (--num_buf) {
1032                int num_skb_frags;
1033
1034                buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1035                if (unlikely(!buf)) {
1036                        pr_debug("%s: rx error: %d buffers out of %d missing\n",
1037                                 dev->name, num_buf,
1038                                 virtio16_to_cpu(vi->vdev,
1039                                                 hdr->num_buffers));
1040                        dev->stats.rx_length_errors++;
1041                        goto err_buf;
1042                }
1043
1044                stats->bytes += len;
1045                page = virt_to_head_page(buf);
1046
1047                truesize = mergeable_ctx_to_truesize(ctx);
1048                if (unlikely(len > truesize)) {
1049                        pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1050                                 dev->name, len, (unsigned long)ctx);
1051                        dev->stats.rx_length_errors++;
1052                        goto err_skb;
1053                }
1054
1055                num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1056                if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1057                        struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1058
1059                        if (unlikely(!nskb))
1060                                goto err_skb;
1061                        if (curr_skb == head_skb)
1062                                skb_shinfo(curr_skb)->frag_list = nskb;
1063                        else
1064                                curr_skb->next = nskb;
1065                        curr_skb = nskb;
1066                        head_skb->truesize += nskb->truesize;
1067                        num_skb_frags = 0;
1068                }
1069                if (curr_skb != head_skb) {
1070                        head_skb->data_len += len;
1071                        head_skb->len += len;
1072                        head_skb->truesize += truesize;
1073                }
1074                offset = buf - page_address(page);
1075                if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1076                        put_page(page);
1077                        skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1078                                             len, truesize);
1079                } else {
1080                        skb_add_rx_frag(curr_skb, num_skb_frags, page,
1081                                        offset, len, truesize);
1082                }
1083        }
1084
1085        ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1086        return head_skb;
1087
1088err_xdp:
1089        rcu_read_unlock();
1090        stats->xdp_drops++;
1091err_skb:
1092        put_page(page);
1093        while (num_buf-- > 1) {
1094                buf = virtqueue_get_buf(rq->vq, &len);
1095                if (unlikely(!buf)) {
1096                        pr_debug("%s: rx error: %d buffers missing\n",
1097                                 dev->name, num_buf);
1098                        dev->stats.rx_length_errors++;
1099                        break;
1100                }
1101                stats->bytes += len;
1102                page = virt_to_head_page(buf);
1103                put_page(page);
1104        }
1105err_buf:
1106        stats->drops++;
1107        dev_kfree_skb(head_skb);
1108xdp_xmit:
1109        return NULL;
1110}
1111
1112static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1113                        void *buf, unsigned int len, void **ctx,
1114                        unsigned int *xdp_xmit,
1115                        struct virtnet_rq_stats *stats)
1116{
1117        struct net_device *dev = vi->dev;
1118        struct sk_buff *skb;
1119        struct virtio_net_hdr_mrg_rxbuf *hdr;
1120
1121        if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1122                pr_debug("%s: short packet %i\n", dev->name, len);
1123                dev->stats.rx_length_errors++;
1124                if (vi->mergeable_rx_bufs) {
1125                        put_page(virt_to_head_page(buf));
1126                } else if (vi->big_packets) {
1127                        give_pages(rq, buf);
1128                } else {
1129                        put_page(virt_to_head_page(buf));
1130                }
1131                return;
1132        }
1133
1134        if (vi->mergeable_rx_bufs)
1135                skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1136                                        stats);
1137        else if (vi->big_packets)
1138                skb = receive_big(dev, vi, rq, buf, len, stats);
1139        else
1140                skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1141
1142        if (unlikely(!skb))
1143                return;
1144
1145        hdr = skb_vnet_hdr(skb);
1146
1147        if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
1148                skb->ip_summed = CHECKSUM_UNNECESSARY;
1149
1150        if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1151                                  virtio_is_little_endian(vi->vdev))) {
1152                net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1153                                     dev->name, hdr->hdr.gso_type,
1154                                     hdr->hdr.gso_size);
1155                goto frame_err;
1156        }
1157
1158        skb_record_rx_queue(skb, vq2rxq(rq->vq));
1159        skb->protocol = eth_type_trans(skb, dev);
1160        pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1161                 ntohs(skb->protocol), skb->len, skb->pkt_type);
1162
1163        napi_gro_receive(&rq->napi, skb);
1164        return;
1165
1166frame_err:
1167        dev->stats.rx_frame_errors++;
1168        dev_kfree_skb(skb);
1169}
1170
1171/* Unlike mergeable buffers, all buffers are allocated to the
1172 * same size, except for the headroom. For this reason we do
1173 * not need to use  mergeable_len_to_ctx here - it is enough
1174 * to store the headroom as the context ignoring the truesize.
1175 */
1176static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1177                             gfp_t gfp)
1178{
1179        struct page_frag *alloc_frag = &rq->alloc_frag;
1180        char *buf;
1181        unsigned int xdp_headroom = virtnet_get_headroom(vi);
1182        void *ctx = (void *)(unsigned long)xdp_headroom;
1183        int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1184        int err;
1185
1186        len = SKB_DATA_ALIGN(len) +
1187              SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1188        if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
1189                return -ENOMEM;
1190
1191        buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1192        get_page(alloc_frag->page);
1193        alloc_frag->offset += len;
1194        sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1195                    vi->hdr_len + GOOD_PACKET_LEN);
1196        err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1197        if (err < 0)
1198                put_page(virt_to_head_page(buf));
1199        return err;
1200}
1201
1202static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1203                           gfp_t gfp)
1204{
1205        struct page *first, *list = NULL;
1206        char *p;
1207        int i, err, offset;
1208
1209        sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
1210
1211        /* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
1212        for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
1213                first = get_a_page(rq, gfp);
1214                if (!first) {
1215                        if (list)
1216                                give_pages(rq, list);
1217                        return -ENOMEM;
1218                }
1219                sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1220
1221                /* chain new page in list head to match sg */
1222                first->private = (unsigned long)list;
1223                list = first;
1224        }
1225
1226        first = get_a_page(rq, gfp);
1227        if (!first) {
1228                give_pages(rq, list);
1229                return -ENOMEM;
1230        }
1231        p = page_address(first);
1232
1233        /* rq->sg[0], rq->sg[1] share the same page */
1234        /* a separated rq->sg[0] for header - required in case !any_header_sg */
1235        sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1236
1237        /* rq->sg[1] for data packet, from offset */
1238        offset = sizeof(struct padded_vnet_hdr);
1239        sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1240
1241        /* chain first in list head */
1242        first->private = (unsigned long)list;
1243        err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
1244                                  first, gfp);
1245        if (err < 0)
1246                give_pages(rq, first);
1247
1248        return err;
1249}
1250
1251static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1252                                          struct ewma_pkt_len *avg_pkt_len,
1253                                          unsigned int room)
1254{
1255        const size_t hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1256        unsigned int len;
1257
1258        if (room)
1259                return PAGE_SIZE - room;
1260
1261        len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1262                                rq->min_buf_len, PAGE_SIZE - hdr_len);
1263
1264        return ALIGN(len, L1_CACHE_BYTES);
1265}
1266
1267static int add_recvbuf_mergeable(struct virtnet_info *vi,
1268                                 struct receive_queue *rq, gfp_t gfp)
1269{
1270        struct page_frag *alloc_frag = &rq->alloc_frag;
1271        unsigned int headroom = virtnet_get_headroom(vi);
1272        unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1273        unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1274        char *buf;
1275        void *ctx;
1276        int err;
1277        unsigned int len, hole;
1278
1279        /* Extra tailroom is needed to satisfy XDP's assumption. This
1280         * means rx frags coalescing won't work, but consider we've
1281         * disabled GSO for XDP, it won't be a big issue.
1282         */
1283        len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1284        if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
1285                return -ENOMEM;
1286
1287        buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1288        buf += headroom; /* advance address leaving hole at front of pkt */
1289        get_page(alloc_frag->page);
1290        alloc_frag->offset += len + room;
1291        hole = alloc_frag->size - alloc_frag->offset;
1292        if (hole < len + room) {
1293                /* To avoid internal fragmentation, if there is very likely not
1294                 * enough space for another buffer, add the remaining space to
1295                 * the current buffer.
1296                 */
1297                len += hole;
1298                alloc_frag->offset += hole;
1299        }
1300
1301        sg_init_one(rq->sg, buf, len);
1302        ctx = mergeable_len_to_ctx(len, headroom);
1303        err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1304        if (err < 0)
1305                put_page(virt_to_head_page(buf));
1306
1307        return err;
1308}
1309
1310/*
1311 * Returns false if we couldn't fill entirely (OOM).
1312 *
1313 * Normally run in the receive path, but can also be run from ndo_open
1314 * before we're receiving packets, or from refill_work which is
1315 * careful to disable receiving (using napi_disable).
1316 */
1317static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1318                          gfp_t gfp)
1319{
1320        int err;
1321        bool oom;
1322
1323        do {
1324                if (vi->mergeable_rx_bufs)
1325                        err = add_recvbuf_mergeable(vi, rq, gfp);
1326                else if (vi->big_packets)
1327                        err = add_recvbuf_big(vi, rq, gfp);
1328                else
1329                        err = add_recvbuf_small(vi, rq, gfp);
1330
1331                oom = err == -ENOMEM;
1332                if (err)
1333                        break;
1334        } while (rq->vq->num_free);
1335        if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
1336                unsigned long flags;
1337
1338                flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1339                rq->stats.kicks++;
1340                u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1341        }
1342
1343        return !oom;
1344}
1345
1346static void skb_recv_done(struct virtqueue *rvq)
1347{
1348        struct virtnet_info *vi = rvq->vdev->priv;
1349        struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1350
1351        virtqueue_napi_schedule(&rq->napi, rvq);
1352}
1353
1354static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
1355{
1356        napi_enable(napi);
1357
1358        /* If all buffers were filled by other side before we napi_enabled, we
1359         * won't get another interrupt, so process any outstanding packets now.
1360         * Call local_bh_enable after to trigger softIRQ processing.
1361         */
1362        local_bh_disable();
1363        virtqueue_napi_schedule(napi, vq);
1364        local_bh_enable();
1365}
1366
1367static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1368                                   struct virtqueue *vq,
1369                                   struct napi_struct *napi)
1370{
1371        if (!napi->weight)
1372                return;
1373
1374        /* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1375         * enable the feature if this is likely affine with the transmit path.
1376         */
1377        if (!vi->affinity_hint_set) {
1378                napi->weight = 0;
1379                return;
1380        }
1381
1382        return virtnet_napi_enable(vq, napi);
1383}
1384
1385static void virtnet_napi_tx_disable(struct napi_struct *napi)
1386{
1387        if (napi->weight)
1388                napi_disable(napi);
1389}
1390
1391static void refill_work(struct work_struct *work)
1392{
1393        struct virtnet_info *vi =
1394                container_of(work, struct virtnet_info, refill.work);
1395        bool still_empty;
1396        int i;
1397
1398        for (i = 0; i < vi->curr_queue_pairs; i++) {
1399                struct receive_queue *rq = &vi->rq[i];
1400
1401                napi_disable(&rq->napi);
1402                still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1403                virtnet_napi_enable(rq->vq, &rq->napi);
1404
1405                /* In theory, this can happen: if we don't get any buffers in
1406                 * we will *never* try to fill again.
1407                 */
1408                if (still_empty)
1409                        schedule_delayed_work(&vi->refill, HZ/2);
1410        }
1411}
1412
1413static int virtnet_receive(struct receive_queue *rq, int budget,
1414                           unsigned int *xdp_xmit)
1415{
1416        struct virtnet_info *vi = rq->vq->vdev->priv;
1417        struct virtnet_rq_stats stats = {};
1418        unsigned int len;
1419        void *buf;
1420        int i;
1421
1422        if (!vi->big_packets || vi->mergeable_rx_bufs) {
1423                void *ctx;
1424
1425                while (stats.packets < budget &&
1426                       (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1427                        receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1428                        stats.packets++;
1429                }
1430        } else {
1431                while (stats.packets < budget &&
1432                       (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1433                        receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1434                        stats.packets++;
1435                }
1436        }
1437
1438        if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1439                if (!try_fill_recv(vi, rq, GFP_ATOMIC))
1440                        schedule_delayed_work(&vi->refill, 0);
1441        }
1442
1443        u64_stats_update_begin(&rq->stats.syncp);
1444        for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1445                size_t offset = virtnet_rq_stats_desc[i].offset;
1446                u64 *item;
1447
1448                item = (u64 *)((u8 *)&rq->stats + offset);
1449                *item += *(u64 *)((u8 *)&stats + offset);
1450        }
1451        u64_stats_update_end(&rq->stats.syncp);
1452
1453        return stats.packets;
1454}
1455
1456static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
1457{
1458        unsigned int len;
1459        unsigned int packets = 0;
1460        unsigned int bytes = 0;
1461        void *ptr;
1462
1463        while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
1464                if (likely(!is_xdp_frame(ptr))) {
1465                        struct sk_buff *skb = ptr;
1466
1467                        pr_debug("Sent skb %p\n", skb);
1468
1469                        bytes += skb->len;
1470                        napi_consume_skb(skb, in_napi);
1471                } else {
1472                        struct xdp_frame *frame = ptr_to_xdp(ptr);
1473
1474                        bytes += frame->len;
1475                        xdp_return_frame(frame);
1476                }
1477                packets++;
1478        }
1479
1480        /* Avoid overhead when no packets have been processed
1481         * happens when called speculatively from start_xmit.
1482         */
1483        if (!packets)
1484                return;
1485
1486        u64_stats_update_begin(&sq->stats.syncp);
1487        sq->stats.bytes += bytes;
1488        sq->stats.packets += packets;
1489        u64_stats_update_end(&sq->stats.syncp);
1490}
1491
1492static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
1493{
1494        if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
1495                return false;
1496        else if (q < vi->curr_queue_pairs)
1497                return true;
1498        else
1499                return false;
1500}
1501
1502static void virtnet_poll_cleantx(struct receive_queue *rq)
1503{
1504        struct virtnet_info *vi = rq->vq->vdev->priv;
1505        unsigned int index = vq2rxq(rq->vq);
1506        struct send_queue *sq = &vi->sq[index];
1507        struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
1508
1509        if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
1510                return;
1511
1512        if (__netif_tx_trylock(txq)) {
1513                do {
1514                        virtqueue_disable_cb(sq->vq);
1515                        free_old_xmit_skbs(sq, true);
1516                } while (unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1517
1518                if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1519                        netif_tx_wake_queue(txq);
1520
1521                __netif_tx_unlock(txq);
1522        }
1523}
1524
1525static int virtnet_poll(struct napi_struct *napi, int budget)
1526{
1527        struct receive_queue *rq =
1528                container_of(napi, struct receive_queue, napi);
1529        struct virtnet_info *vi = rq->vq->vdev->priv;
1530        struct send_queue *sq;
1531        unsigned int received;
1532        unsigned int xdp_xmit = 0;
1533
1534        virtnet_poll_cleantx(rq);
1535
1536        received = virtnet_receive(rq, budget, &xdp_xmit);
1537
1538        /* Out of packets? */
1539        if (received < budget)
1540                virtqueue_napi_complete(napi, rq->vq, received);
1541
1542        if (xdp_xmit & VIRTIO_XDP_REDIR)
1543                xdp_do_flush();
1544
1545        if (xdp_xmit & VIRTIO_XDP_TX) {
1546                sq = virtnet_xdp_get_sq(vi);
1547                if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1548                        u64_stats_update_begin(&sq->stats.syncp);
1549                        sq->stats.kicks++;
1550                        u64_stats_update_end(&sq->stats.syncp);
1551                }
1552                virtnet_xdp_put_sq(vi, sq);
1553        }
1554
1555        return received;
1556}
1557
1558static int virtnet_open(struct net_device *dev)
1559{
1560        struct virtnet_info *vi = netdev_priv(dev);
1561        int i, err;
1562
1563        for (i = 0; i < vi->max_queue_pairs; i++) {
1564                if (i < vi->curr_queue_pairs)
1565                        /* Make sure we have some buffers: if oom use wq. */
1566                        if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1567                                schedule_delayed_work(&vi->refill, 0);
1568
1569                err = xdp_rxq_info_reg(&vi->rq[i].xdp_rxq, dev, i, vi->rq[i].napi.napi_id);
1570                if (err < 0)
1571                        return err;
1572
1573                err = xdp_rxq_info_reg_mem_model(&vi->rq[i].xdp_rxq,
1574                                                 MEM_TYPE_PAGE_SHARED, NULL);
1575                if (err < 0) {
1576                        xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1577                        return err;
1578                }
1579
1580                virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1581                virtnet_napi_tx_enable(vi, vi->sq[i].vq, &vi->sq[i].napi);
1582        }
1583
1584        return 0;
1585}
1586
1587static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1588{
1589        struct send_queue *sq = container_of(napi, struct send_queue, napi);
1590        struct virtnet_info *vi = sq->vq->vdev->priv;
1591        unsigned int index = vq2txq(sq->vq);
1592        struct netdev_queue *txq;
1593        int opaque;
1594        bool done;
1595
1596        if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
1597                /* We don't need to enable cb for XDP */
1598                napi_complete_done(napi, 0);
1599                return 0;
1600        }
1601
1602        txq = netdev_get_tx_queue(vi->dev, index);
1603        __netif_tx_lock(txq, raw_smp_processor_id());
1604        virtqueue_disable_cb(sq->vq);
1605        free_old_xmit_skbs(sq, true);
1606
1607        if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1608                netif_tx_wake_queue(txq);
1609
1610        opaque = virtqueue_enable_cb_prepare(sq->vq);
1611
1612        done = napi_complete_done(napi, 0);
1613
1614        if (!done)
1615                virtqueue_disable_cb(sq->vq);
1616
1617        __netif_tx_unlock(txq);
1618
1619        if (done) {
1620                if (unlikely(virtqueue_poll(sq->vq, opaque))) {
1621                        if (napi_schedule_prep(napi)) {
1622                                __netif_tx_lock(txq, raw_smp_processor_id());
1623                                virtqueue_disable_cb(sq->vq);
1624                                __netif_tx_unlock(txq);
1625                                __napi_schedule(napi);
1626                        }
1627                }
1628        }
1629
1630        return 0;
1631}
1632
1633static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1634{
1635        struct virtio_net_hdr_mrg_rxbuf *hdr;
1636        const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1637        struct virtnet_info *vi = sq->vq->vdev->priv;
1638        int num_sg;
1639        unsigned hdr_len = vi->hdr_len;
1640        bool can_push;
1641
1642        pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1643
1644        can_push = vi->any_header_sg &&
1645                !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1646                !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1647        /* Even if we can, don't push here yet as this would skew
1648         * csum_start offset below. */
1649        if (can_push)
1650                hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1651        else
1652                hdr = skb_vnet_hdr(skb);
1653
1654        if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1655                                    virtio_is_little_endian(vi->vdev), false,
1656                                    0))
1657                return -EPROTO;
1658
1659        if (vi->mergeable_rx_bufs)
1660                hdr->num_buffers = 0;
1661
1662        sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1663        if (can_push) {
1664                __skb_push(skb, hdr_len);
1665                num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1666                if (unlikely(num_sg < 0))
1667                        return num_sg;
1668                /* Pull header back to avoid skew in tx bytes calculations. */
1669                __skb_pull(skb, hdr_len);
1670        } else {
1671                sg_set_buf(sq->sg, hdr, hdr_len);
1672                num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
1673                if (unlikely(num_sg < 0))
1674                        return num_sg;
1675                num_sg++;
1676        }
1677        return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1678}
1679
1680static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1681{
1682        struct virtnet_info *vi = netdev_priv(dev);
1683        int qnum = skb_get_queue_mapping(skb);
1684        struct send_queue *sq = &vi->sq[qnum];
1685        int err;
1686        struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1687        bool kick = !netdev_xmit_more();
1688        bool use_napi = sq->napi.weight;
1689
1690        /* Free up any pending old buffers before queueing new ones. */
1691        do {
1692                if (use_napi)
1693                        virtqueue_disable_cb(sq->vq);
1694
1695                free_old_xmit_skbs(sq, false);
1696
1697        } while (use_napi && kick &&
1698               unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1699
1700        /* timestamp packet in software */
1701        skb_tx_timestamp(skb);
1702
1703        /* Try to transmit */
1704        err = xmit_skb(sq, skb);
1705
1706        /* This should not happen! */
1707        if (unlikely(err)) {
1708                dev->stats.tx_fifo_errors++;
1709                if (net_ratelimit())
1710                        dev_warn(&dev->dev,
1711                                 "Unexpected TXQ (%d) queue failure: %d\n",
1712                                 qnum, err);
1713                dev->stats.tx_dropped++;
1714                dev_kfree_skb_any(skb);
1715                return NETDEV_TX_OK;
1716        }
1717
1718        /* Don't wait up for transmitted skbs to be freed. */
1719        if (!use_napi) {
1720                skb_orphan(skb);
1721                nf_reset_ct(skb);
1722        }
1723
1724        /* If running out of space, stop queue to avoid getting packets that we
1725         * are then unable to transmit.
1726         * An alternative would be to force queuing layer to requeue the skb by
1727         * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
1728         * returned in a normal path of operation: it means that driver is not
1729         * maintaining the TX queue stop/start state properly, and causes
1730         * the stack to do a non-trivial amount of useless work.
1731         * Since most packets only take 1 or 2 ring slots, stopping the queue
1732         * early means 16 slots are typically wasted.
1733         */
1734        if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1735                netif_stop_subqueue(dev, qnum);
1736                if (!use_napi &&
1737                    unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1738                        /* More just got used, free them then recheck. */
1739                        free_old_xmit_skbs(sq, false);
1740                        if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1741                                netif_start_subqueue(dev, qnum);
1742                                virtqueue_disable_cb(sq->vq);
1743                        }
1744                }
1745        }
1746
1747        if (kick || netif_xmit_stopped(txq)) {
1748                if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1749                        u64_stats_update_begin(&sq->stats.syncp);
1750                        sq->stats.kicks++;
1751                        u64_stats_update_end(&sq->stats.syncp);
1752                }
1753        }
1754
1755        return NETDEV_TX_OK;
1756}
1757
1758/*
1759 * Send command via the control virtqueue and check status.  Commands
1760 * supported by the hypervisor, as indicated by feature bits, should
1761 * never fail unless improperly formatted.
1762 */
1763static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1764                                 struct scatterlist *out)
1765{
1766        struct scatterlist *sgs[4], hdr, stat;
1767        unsigned out_num = 0, tmp;
1768        int ret;
1769
1770        /* Caller should know better */
1771        BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1772
1773        vi->ctrl->status = ~0;
1774        vi->ctrl->hdr.class = class;
1775        vi->ctrl->hdr.cmd = cmd;
1776        /* Add header */
1777        sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
1778        sgs[out_num++] = &hdr;
1779
1780        if (out)
1781                sgs[out_num++] = out;
1782
1783        /* Add return status. */
1784        sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
1785        sgs[out_num] = &stat;
1786
1787        BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1788        ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1789        if (ret < 0) {
1790                dev_warn(&vi->vdev->dev,
1791                         "Failed to add sgs for command vq: %d\n.", ret);
1792                return false;
1793        }
1794
1795        if (unlikely(!virtqueue_kick(vi->cvq)))
1796                return vi->ctrl->status == VIRTIO_NET_OK;
1797
1798        /* Spin for a response, the kick causes an ioport write, trapping
1799         * into the hypervisor, so the request should be handled immediately.
1800         */
1801        while (!virtqueue_get_buf(vi->cvq, &tmp) &&
1802               !virtqueue_is_broken(vi->cvq))
1803                cpu_relax();
1804
1805        return vi->ctrl->status == VIRTIO_NET_OK;
1806}
1807
1808static int virtnet_set_mac_address(struct net_device *dev, void *p)
1809{
1810        struct virtnet_info *vi = netdev_priv(dev);
1811        struct virtio_device *vdev = vi->vdev;
1812        int ret;
1813        struct sockaddr *addr;
1814        struct scatterlist sg;
1815
1816        if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
1817                return -EOPNOTSUPP;
1818
1819        addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
1820        if (!addr)
1821                return -ENOMEM;
1822
1823        ret = eth_prepare_mac_addr_change(dev, addr);
1824        if (ret)
1825                goto out;
1826
1827        if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1828                sg_init_one(&sg, addr->sa_data, dev->addr_len);
1829                if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1830                                          VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
1831                        dev_warn(&vdev->dev,
1832                                 "Failed to set mac address by vq command.\n");
1833                        ret = -EINVAL;
1834                        goto out;
1835                }
1836        } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
1837                   !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1838                unsigned int i;
1839
1840                /* Naturally, this has an atomicity problem. */
1841                for (i = 0; i < dev->addr_len; i++)
1842                        virtio_cwrite8(vdev,
1843                                       offsetof(struct virtio_net_config, mac) +
1844                                       i, addr->sa_data[i]);
1845        }
1846
1847        eth_commit_mac_addr_change(dev, p);
1848        ret = 0;
1849
1850out:
1851        kfree(addr);
1852        return ret;
1853}
1854
1855static void virtnet_stats(struct net_device *dev,
1856                          struct rtnl_link_stats64 *tot)
1857{
1858        struct virtnet_info *vi = netdev_priv(dev);
1859        unsigned int start;
1860        int i;
1861
1862        for (i = 0; i < vi->max_queue_pairs; i++) {
1863                u64 tpackets, tbytes, rpackets, rbytes, rdrops;
1864                struct receive_queue *rq = &vi->rq[i];
1865                struct send_queue *sq = &vi->sq[i];
1866
1867                do {
1868                        start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
1869                        tpackets = sq->stats.packets;
1870                        tbytes   = sq->stats.bytes;
1871                } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
1872
1873                do {
1874                        start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
1875                        rpackets = rq->stats.packets;
1876                        rbytes   = rq->stats.bytes;
1877                        rdrops   = rq->stats.drops;
1878                } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
1879
1880                tot->rx_packets += rpackets;
1881                tot->tx_packets += tpackets;
1882                tot->rx_bytes   += rbytes;
1883                tot->tx_bytes   += tbytes;
1884                tot->rx_dropped += rdrops;
1885        }
1886
1887        tot->tx_dropped = dev->stats.tx_dropped;
1888        tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
1889        tot->rx_length_errors = dev->stats.rx_length_errors;
1890        tot->rx_frame_errors = dev->stats.rx_frame_errors;
1891}
1892
1893static void virtnet_ack_link_announce(struct virtnet_info *vi)
1894{
1895        rtnl_lock();
1896        if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
1897                                  VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
1898                dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
1899        rtnl_unlock();
1900}
1901
1902static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1903{
1904        struct scatterlist sg;
1905        struct net_device *dev = vi->dev;
1906
1907        if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
1908                return 0;
1909
1910        vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
1911        sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
1912
1913        if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
1914                                  VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
1915                dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
1916                         queue_pairs);
1917                return -EINVAL;
1918        } else {
1919                vi->curr_queue_pairs = queue_pairs;
1920                /* virtnet_open() will refill when device is going to up. */
1921                if (dev->flags & IFF_UP)
1922                        schedule_delayed_work(&vi->refill, 0);
1923        }
1924
1925        return 0;
1926}
1927
1928static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1929{
1930        int err;
1931
1932        rtnl_lock();
1933        err = _virtnet_set_queues(vi, queue_pairs);
1934        rtnl_unlock();
1935        return err;
1936}
1937
1938static int virtnet_close(struct net_device *dev)
1939{
1940        struct virtnet_info *vi = netdev_priv(dev);
1941        int i;
1942
1943        /* Make sure refill_work doesn't re-enable napi! */
1944        cancel_delayed_work_sync(&vi->refill);
1945
1946        for (i = 0; i < vi->max_queue_pairs; i++) {
1947                xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1948                napi_disable(&vi->rq[i].napi);
1949                virtnet_napi_tx_disable(&vi->sq[i].napi);
1950        }
1951
1952        return 0;
1953}
1954
1955static void virtnet_set_rx_mode(struct net_device *dev)
1956{
1957        struct virtnet_info *vi = netdev_priv(dev);
1958        struct scatterlist sg[2];
1959        struct virtio_net_ctrl_mac *mac_data;
1960        struct netdev_hw_addr *ha;
1961        int uc_count;
1962        int mc_count;
1963        void *buf;
1964        int i;
1965
1966        /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
1967        if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
1968                return;
1969
1970        vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
1971        vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
1972
1973        sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
1974
1975        if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1976                                  VIRTIO_NET_CTRL_RX_PROMISC, sg))
1977                dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
1978                         vi->ctrl->promisc ? "en" : "dis");
1979
1980        sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
1981
1982        if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1983                                  VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
1984                dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
1985                         vi->ctrl->allmulti ? "en" : "dis");
1986
1987        uc_count = netdev_uc_count(dev);
1988        mc_count = netdev_mc_count(dev);
1989        /* MAC filter - use one buffer for both lists */
1990        buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
1991                      (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
1992        mac_data = buf;
1993        if (!buf)
1994                return;
1995
1996        sg_init_table(sg, 2);
1997
1998        /* Store the unicast list and count in the front of the buffer */
1999        mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2000        i = 0;
2001        netdev_for_each_uc_addr(ha, dev)
2002                memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2003
2004        sg_set_buf(&sg[0], mac_data,
2005                   sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2006
2007        /* multicast list and count fill the end */
2008        mac_data = (void *)&mac_data->macs[uc_count][0];
2009
2010        mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2011        i = 0;
2012        netdev_for_each_mc_addr(ha, dev)
2013                memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2014
2015        sg_set_buf(&sg[1], mac_data,
2016                   sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2017
2018        if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2019                                  VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2020                dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2021
2022        kfree(buf);
2023}
2024
2025static int virtnet_vlan_rx_add_vid(struct net_device *dev,
2026                                   __be16 proto, u16 vid)
2027{
2028        struct virtnet_info *vi = netdev_priv(dev);
2029        struct scatterlist sg;
2030
2031        vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2032        sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2033
2034        if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2035                                  VIRTIO_NET_CTRL_VLAN_ADD, &sg))
2036                dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
2037        return 0;
2038}
2039
2040static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
2041                                    __be16 proto, u16 vid)
2042{
2043        struct virtnet_info *vi = netdev_priv(dev);
2044        struct scatterlist sg;
2045
2046        vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2047        sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2048
2049        if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2050                                  VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2051                dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2052        return 0;
2053}
2054
2055static void virtnet_clean_affinity(struct virtnet_info *vi)
2056{
2057        int i;
2058
2059        if (vi->affinity_hint_set) {
2060                for (i = 0; i < vi->max_queue_pairs; i++) {
2061                        virtqueue_set_affinity(vi->rq[i].vq, NULL);
2062                        virtqueue_set_affinity(vi->sq[i].vq, NULL);
2063                }
2064
2065                vi->affinity_hint_set = false;
2066        }
2067}
2068
2069static void virtnet_set_affinity(struct virtnet_info *vi)
2070{
2071        cpumask_var_t mask;
2072        int stragglers;
2073        int group_size;
2074        int i, j, cpu;
2075        int num_cpu;
2076        int stride;
2077
2078        if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2079                virtnet_clean_affinity(vi);
2080                return;
2081        }
2082
2083        num_cpu = num_online_cpus();
2084        stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2085        stragglers = num_cpu >= vi->curr_queue_pairs ?
2086                        num_cpu % vi->curr_queue_pairs :
2087                        0;
2088        cpu = cpumask_next(-1, cpu_online_mask);
2089
2090        for (i = 0; i < vi->curr_queue_pairs; i++) {
2091                group_size = stride + (i < stragglers ? 1 : 0);
2092
2093                for (j = 0; j < group_size; j++) {
2094                        cpumask_set_cpu(cpu, mask);
2095                        cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2096                                                nr_cpu_ids, false);
2097                }
2098                virtqueue_set_affinity(vi->rq[i].vq, mask);
2099                virtqueue_set_affinity(vi->sq[i].vq, mask);
2100                __netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2101                cpumask_clear(mask);
2102        }
2103
2104        vi->affinity_hint_set = true;
2105        free_cpumask_var(mask);
2106}
2107
2108static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2109{
2110        struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2111                                                   node);
2112        virtnet_set_affinity(vi);
2113        return 0;
2114}
2115
2116static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2117{
2118        struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2119                                                   node_dead);
2120        virtnet_set_affinity(vi);
2121        return 0;
2122}
2123
2124static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2125{
2126        struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2127                                                   node);
2128
2129        virtnet_clean_affinity(vi);
2130        return 0;
2131}
2132
2133static enum cpuhp_state virtionet_online;
2134
2135static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2136{
2137        int ret;
2138
2139        ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2140        if (ret)
2141                return ret;
2142        ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2143                                               &vi->node_dead);
2144        if (!ret)
2145                return ret;
2146        cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2147        return ret;
2148}
2149
2150static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2151{
2152        cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2153        cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2154                                            &vi->node_dead);
2155}
2156
2157static void virtnet_get_ringparam(struct net_device *dev,
2158                                struct ethtool_ringparam *ring)
2159{
2160        struct virtnet_info *vi = netdev_priv(dev);
2161
2162        ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2163        ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2164        ring->rx_pending = ring->rx_max_pending;
2165        ring->tx_pending = ring->tx_max_pending;
2166}
2167
2168
2169static void virtnet_get_drvinfo(struct net_device *dev,
2170                                struct ethtool_drvinfo *info)
2171{
2172        struct virtnet_info *vi = netdev_priv(dev);
2173        struct virtio_device *vdev = vi->vdev;
2174
2175        strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2176        strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2177        strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2178
2179}
2180
2181/* TODO: Eliminate OOO packets during switching */
2182static int virtnet_set_channels(struct net_device *dev,
2183                                struct ethtool_channels *channels)
2184{
2185        struct virtnet_info *vi = netdev_priv(dev);
2186        u16 queue_pairs = channels->combined_count;
2187        int err;
2188
2189        /* We don't support separate rx/tx channels.
2190         * We don't allow setting 'other' channels.
2191         */
2192        if (channels->rx_count || channels->tx_count || channels->other_count)
2193                return -EINVAL;
2194
2195        if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2196                return -EINVAL;
2197
2198        /* For now we don't support modifying channels while XDP is loaded
2199         * also when XDP is loaded all RX queues have XDP programs so we only
2200         * need to check a single RX queue.
2201         */
2202        if (vi->rq[0].xdp_prog)
2203                return -EINVAL;
2204
2205        cpus_read_lock();
2206        err = _virtnet_set_queues(vi, queue_pairs);
2207        if (err) {
2208                cpus_read_unlock();
2209                goto err;
2210        }
2211        virtnet_set_affinity(vi);
2212        cpus_read_unlock();
2213
2214        netif_set_real_num_tx_queues(dev, queue_pairs);
2215        netif_set_real_num_rx_queues(dev, queue_pairs);
2216 err:
2217        return err;
2218}
2219
2220static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2221{
2222        struct virtnet_info *vi = netdev_priv(dev);
2223        unsigned int i, j;
2224        u8 *p = data;
2225
2226        switch (stringset) {
2227        case ETH_SS_STATS:
2228                for (i = 0; i < vi->curr_queue_pairs; i++) {
2229                        for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
2230                                ethtool_sprintf(&p, "rx_queue_%u_%s", i,
2231                                                virtnet_rq_stats_desc[j].desc);
2232                }
2233
2234                for (i = 0; i < vi->curr_queue_pairs; i++) {
2235                        for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
2236                                ethtool_sprintf(&p, "tx_queue_%u_%s", i,
2237                                                virtnet_sq_stats_desc[j].desc);
2238                }
2239                break;
2240        }
2241}
2242
2243static int virtnet_get_sset_count(struct net_device *dev, int sset)
2244{
2245        struct virtnet_info *vi = netdev_priv(dev);
2246
2247        switch (sset) {
2248        case ETH_SS_STATS:
2249                return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2250                                               VIRTNET_SQ_STATS_LEN);
2251        default:
2252                return -EOPNOTSUPP;
2253        }
2254}
2255
2256static void virtnet_get_ethtool_stats(struct net_device *dev,
2257                                      struct ethtool_stats *stats, u64 *data)
2258{
2259        struct virtnet_info *vi = netdev_priv(dev);
2260        unsigned int idx = 0, start, i, j;
2261        const u8 *stats_base;
2262        size_t offset;
2263
2264        for (i = 0; i < vi->curr_queue_pairs; i++) {
2265                struct receive_queue *rq = &vi->rq[i];
2266
2267                stats_base = (u8 *)&rq->stats;
2268                do {
2269                        start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2270                        for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2271                                offset = virtnet_rq_stats_desc[j].offset;
2272                                data[idx + j] = *(u64 *)(stats_base + offset);
2273                        }
2274                } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2275                idx += VIRTNET_RQ_STATS_LEN;
2276        }
2277
2278        for (i = 0; i < vi->curr_queue_pairs; i++) {
2279                struct send_queue *sq = &vi->sq[i];
2280
2281                stats_base = (u8 *)&sq->stats;
2282                do {
2283                        start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2284                        for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2285                                offset = virtnet_sq_stats_desc[j].offset;
2286                                data[idx + j] = *(u64 *)(stats_base + offset);
2287                        }
2288                } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2289                idx += VIRTNET_SQ_STATS_LEN;
2290        }
2291}
2292
2293static void virtnet_get_channels(struct net_device *dev,
2294                                 struct ethtool_channels *channels)
2295{
2296        struct virtnet_info *vi = netdev_priv(dev);
2297
2298        channels->combined_count = vi->curr_queue_pairs;
2299        channels->max_combined = vi->max_queue_pairs;
2300        channels->max_other = 0;
2301        channels->rx_count = 0;
2302        channels->tx_count = 0;
2303        channels->other_count = 0;
2304}
2305
2306static int virtnet_set_link_ksettings(struct net_device *dev,
2307                                      const struct ethtool_link_ksettings *cmd)
2308{
2309        struct virtnet_info *vi = netdev_priv(dev);
2310
2311        return ethtool_virtdev_set_link_ksettings(dev, cmd,
2312                                                  &vi->speed, &vi->duplex);
2313}
2314
2315static int virtnet_get_link_ksettings(struct net_device *dev,
2316                                      struct ethtool_link_ksettings *cmd)
2317{
2318        struct virtnet_info *vi = netdev_priv(dev);
2319
2320        cmd->base.speed = vi->speed;
2321        cmd->base.duplex = vi->duplex;
2322        cmd->base.port = PORT_OTHER;
2323
2324        return 0;
2325}
2326
2327static int virtnet_set_coalesce(struct net_device *dev,
2328                                struct ethtool_coalesce *ec,
2329                                struct kernel_ethtool_coalesce *kernel_coal,
2330                                struct netlink_ext_ack *extack)
2331{
2332        struct virtnet_info *vi = netdev_priv(dev);
2333        int i, napi_weight;
2334
2335        if (ec->tx_max_coalesced_frames > 1 ||
2336            ec->rx_max_coalesced_frames != 1)
2337                return -EINVAL;
2338
2339        napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
2340        if (napi_weight ^ vi->sq[0].napi.weight) {
2341                if (dev->flags & IFF_UP)
2342                        return -EBUSY;
2343                for (i = 0; i < vi->max_queue_pairs; i++)
2344                        vi->sq[i].napi.weight = napi_weight;
2345        }
2346
2347        return 0;
2348}
2349
2350static int virtnet_get_coalesce(struct net_device *dev,
2351                                struct ethtool_coalesce *ec,
2352                                struct kernel_ethtool_coalesce *kernel_coal,
2353                                struct netlink_ext_ack *extack)
2354{
2355        struct ethtool_coalesce ec_default = {
2356                .cmd = ETHTOOL_GCOALESCE,
2357                .rx_max_coalesced_frames = 1,
2358        };
2359        struct virtnet_info *vi = netdev_priv(dev);
2360
2361        memcpy(ec, &ec_default, sizeof(ec_default));
2362
2363        if (vi->sq[0].napi.weight)
2364                ec->tx_max_coalesced_frames = 1;
2365
2366        return 0;
2367}
2368
2369static void virtnet_init_settings(struct net_device *dev)
2370{
2371        struct virtnet_info *vi = netdev_priv(dev);
2372
2373        vi->speed = SPEED_UNKNOWN;
2374        vi->duplex = DUPLEX_UNKNOWN;
2375}
2376
2377static void virtnet_update_settings(struct virtnet_info *vi)
2378{
2379        u32 speed;
2380        u8 duplex;
2381
2382        if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
2383                return;
2384
2385        virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
2386
2387        if (ethtool_validate_speed(speed))
2388                vi->speed = speed;
2389
2390        virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
2391
2392        if (ethtool_validate_duplex(duplex))
2393                vi->duplex = duplex;
2394}
2395
2396static const struct ethtool_ops virtnet_ethtool_ops = {
2397        .supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES,
2398        .get_drvinfo = virtnet_get_drvinfo,
2399        .get_link = ethtool_op_get_link,
2400        .get_ringparam = virtnet_get_ringparam,
2401        .get_strings = virtnet_get_strings,
2402        .get_sset_count = virtnet_get_sset_count,
2403        .get_ethtool_stats = virtnet_get_ethtool_stats,
2404        .set_channels = virtnet_set_channels,
2405        .get_channels = virtnet_get_channels,
2406        .get_ts_info = ethtool_op_get_ts_info,
2407        .get_link_ksettings = virtnet_get_link_ksettings,
2408        .set_link_ksettings = virtnet_set_link_ksettings,
2409        .set_coalesce = virtnet_set_coalesce,
2410        .get_coalesce = virtnet_get_coalesce,
2411};
2412
2413static void virtnet_freeze_down(struct virtio_device *vdev)
2414{
2415        struct virtnet_info *vi = vdev->priv;
2416        int i;
2417
2418        /* Make sure no work handler is accessing the device */
2419        flush_work(&vi->config_work);
2420
2421        netif_tx_lock_bh(vi->dev);
2422        netif_device_detach(vi->dev);
2423        netif_tx_unlock_bh(vi->dev);
2424        cancel_delayed_work_sync(&vi->refill);
2425
2426        if (netif_running(vi->dev)) {
2427                for (i = 0; i < vi->max_queue_pairs; i++) {
2428                        napi_disable(&vi->rq[i].napi);
2429                        virtnet_napi_tx_disable(&vi->sq[i].napi);
2430                }
2431        }
2432}
2433
2434static int init_vqs(struct virtnet_info *vi);
2435
2436static int virtnet_restore_up(struct virtio_device *vdev)
2437{
2438        struct virtnet_info *vi = vdev->priv;
2439        int err, i;
2440
2441        err = init_vqs(vi);
2442        if (err)
2443                return err;
2444
2445        virtio_device_ready(vdev);
2446
2447        if (netif_running(vi->dev)) {
2448                for (i = 0; i < vi->curr_queue_pairs; i++)
2449                        if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
2450                                schedule_delayed_work(&vi->refill, 0);
2451
2452                for (i = 0; i < vi->max_queue_pairs; i++) {
2453                        virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2454                        virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2455                                               &vi->sq[i].napi);
2456                }
2457        }
2458
2459        netif_tx_lock_bh(vi->dev);
2460        netif_device_attach(vi->dev);
2461        netif_tx_unlock_bh(vi->dev);
2462        return err;
2463}
2464
2465static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
2466{
2467        struct scatterlist sg;
2468        vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
2469
2470        sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
2471
2472        if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
2473                                  VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
2474                dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
2475                return -EINVAL;
2476        }
2477
2478        return 0;
2479}
2480
2481static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
2482{
2483        u64 offloads = 0;
2484
2485        if (!vi->guest_offloads)
2486                return 0;
2487
2488        return virtnet_set_guest_offloads(vi, offloads);
2489}
2490
2491static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
2492{
2493        u64 offloads = vi->guest_offloads;
2494
2495        if (!vi->guest_offloads)
2496                return 0;
2497
2498        return virtnet_set_guest_offloads(vi, offloads);
2499}
2500
2501static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
2502                           struct netlink_ext_ack *extack)
2503{
2504        unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
2505        struct virtnet_info *vi = netdev_priv(dev);
2506        struct bpf_prog *old_prog;
2507        u16 xdp_qp = 0, curr_qp;
2508        int i, err;
2509
2510        if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
2511            && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
2512                virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
2513                virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
2514                virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
2515                virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM))) {
2516                NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
2517                return -EOPNOTSUPP;
2518        }
2519
2520        if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
2521                NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
2522                return -EINVAL;
2523        }
2524
2525        if (dev->mtu > max_sz) {
2526                NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
2527                netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
2528                return -EINVAL;
2529        }
2530
2531        curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
2532        if (prog)
2533                xdp_qp = nr_cpu_ids;
2534
2535        /* XDP requires extra queues for XDP_TX */
2536        if (curr_qp + xdp_qp > vi->max_queue_pairs) {
2537                netdev_warn(dev, "XDP request %i queues but max is %i. XDP_TX and XDP_REDIRECT will operate in a slower locked tx mode.\n",
2538                            curr_qp + xdp_qp, vi->max_queue_pairs);
2539                xdp_qp = 0;
2540        }
2541
2542        old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
2543        if (!prog && !old_prog)
2544                return 0;
2545
2546        if (prog)
2547                bpf_prog_add(prog, vi->max_queue_pairs - 1);
2548
2549        /* Make sure NAPI is not using any XDP TX queues for RX. */
2550        if (netif_running(dev)) {
2551                for (i = 0; i < vi->max_queue_pairs; i++) {
2552                        napi_disable(&vi->rq[i].napi);
2553                        virtnet_napi_tx_disable(&vi->sq[i].napi);
2554                }
2555        }
2556
2557        if (!prog) {
2558                for (i = 0; i < vi->max_queue_pairs; i++) {
2559                        rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
2560                        if (i == 0)
2561                                virtnet_restore_guest_offloads(vi);
2562                }
2563                synchronize_net();
2564        }
2565
2566        err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
2567        if (err)
2568                goto err;
2569        netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
2570        vi->xdp_queue_pairs = xdp_qp;
2571
2572        if (prog) {
2573                vi->xdp_enabled = true;
2574                for (i = 0; i < vi->max_queue_pairs; i++) {
2575                        rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
2576                        if (i == 0 && !old_prog)
2577                                virtnet_clear_guest_offloads(vi);
2578                }
2579        } else {
2580                vi->xdp_enabled = false;
2581        }
2582
2583        for (i = 0; i < vi->max_queue_pairs; i++) {
2584                if (old_prog)
2585                        bpf_prog_put(old_prog);
2586                if (netif_running(dev)) {
2587                        virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2588                        virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2589                                               &vi->sq[i].napi);
2590                }
2591        }
2592
2593        return 0;
2594
2595err:
2596        if (!prog) {
2597                virtnet_clear_guest_offloads(vi);
2598                for (i = 0; i < vi->max_queue_pairs; i++)
2599                        rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
2600        }
2601
2602        if (netif_running(dev)) {
2603                for (i = 0; i < vi->max_queue_pairs; i++) {
2604                        virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2605                        virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2606                                               &vi->sq[i].napi);
2607                }
2608        }
2609        if (prog)
2610                bpf_prog_sub(prog, vi->max_queue_pairs - 1);
2611        return err;
2612}
2613
2614static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
2615{
2616        switch (xdp->command) {
2617        case XDP_SETUP_PROG:
2618                return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
2619        default:
2620                return -EINVAL;
2621        }
2622}
2623
2624static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
2625                                      size_t len)
2626{
2627        struct virtnet_info *vi = netdev_priv(dev);
2628        int ret;
2629
2630        if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2631                return -EOPNOTSUPP;
2632
2633        ret = snprintf(buf, len, "sby");
2634        if (ret >= len)
2635                return -EOPNOTSUPP;
2636
2637        return 0;
2638}
2639
2640static int virtnet_set_features(struct net_device *dev,
2641                                netdev_features_t features)
2642{
2643        struct virtnet_info *vi = netdev_priv(dev);
2644        u64 offloads;
2645        int err;
2646
2647        if ((dev->features ^ features) & NETIF_F_GRO_HW) {
2648                if (vi->xdp_enabled)
2649                        return -EBUSY;
2650
2651                if (features & NETIF_F_GRO_HW)
2652                        offloads = vi->guest_offloads_capable;
2653                else
2654                        offloads = vi->guest_offloads_capable &
2655                                   ~GUEST_OFFLOAD_GRO_HW_MASK;
2656
2657                err = virtnet_set_guest_offloads(vi, offloads);
2658                if (err)
2659                        return err;
2660                vi->guest_offloads = offloads;
2661        }
2662
2663        return 0;
2664}
2665
2666static const struct net_device_ops virtnet_netdev = {
2667        .ndo_open            = virtnet_open,
2668        .ndo_stop            = virtnet_close,
2669        .ndo_start_xmit      = start_xmit,
2670        .ndo_validate_addr   = eth_validate_addr,
2671        .ndo_set_mac_address = virtnet_set_mac_address,
2672        .ndo_set_rx_mode     = virtnet_set_rx_mode,
2673        .ndo_get_stats64     = virtnet_stats,
2674        .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
2675        .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
2676        .ndo_bpf                = virtnet_xdp,
2677        .ndo_xdp_xmit           = virtnet_xdp_xmit,
2678        .ndo_features_check     = passthru_features_check,
2679        .ndo_get_phys_port_name = virtnet_get_phys_port_name,
2680        .ndo_set_features       = virtnet_set_features,
2681};
2682
2683static void virtnet_config_changed_work(struct work_struct *work)
2684{
2685        struct virtnet_info *vi =
2686                container_of(work, struct virtnet_info, config_work);
2687        u16 v;
2688
2689        if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
2690                                 struct virtio_net_config, status, &v) < 0)
2691                return;
2692
2693        if (v & VIRTIO_NET_S_ANNOUNCE) {
2694                netdev_notify_peers(vi->dev);
2695                virtnet_ack_link_announce(vi);
2696        }
2697
2698        /* Ignore unknown (future) status bits */
2699        v &= VIRTIO_NET_S_LINK_UP;
2700
2701        if (vi->status == v)
2702                return;
2703
2704        vi->status = v;
2705
2706        if (vi->status & VIRTIO_NET_S_LINK_UP) {
2707                virtnet_update_settings(vi);
2708                netif_carrier_on(vi->dev);
2709                netif_tx_wake_all_queues(vi->dev);
2710        } else {
2711                netif_carrier_off(vi->dev);
2712                netif_tx_stop_all_queues(vi->dev);
2713        }
2714}
2715
2716static void virtnet_config_changed(struct virtio_device *vdev)
2717{
2718        struct virtnet_info *vi = vdev->priv;
2719
2720        schedule_work(&vi->config_work);
2721}
2722
2723static void virtnet_free_queues(struct virtnet_info *vi)
2724{
2725        int i;
2726
2727        for (i = 0; i < vi->max_queue_pairs; i++) {
2728                __netif_napi_del(&vi->rq[i].napi);
2729                __netif_napi_del(&vi->sq[i].napi);
2730        }
2731
2732        /* We called __netif_napi_del(),
2733         * we need to respect an RCU grace period before freeing vi->rq
2734         */
2735        synchronize_net();
2736
2737        kfree(vi->rq);
2738        kfree(vi->sq);
2739        kfree(vi->ctrl);
2740}
2741
2742static void _free_receive_bufs(struct virtnet_info *vi)
2743{
2744        struct bpf_prog *old_prog;
2745        int i;
2746
2747        for (i = 0; i < vi->max_queue_pairs; i++) {
2748                while (vi->rq[i].pages)
2749                        __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
2750
2751                old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
2752                RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
2753                if (old_prog)
2754                        bpf_prog_put(old_prog);
2755        }
2756}
2757
2758static void free_receive_bufs(struct virtnet_info *vi)
2759{
2760        rtnl_lock();
2761        _free_receive_bufs(vi);
2762        rtnl_unlock();
2763}
2764
2765static void free_receive_page_frags(struct virtnet_info *vi)
2766{
2767        int i;
2768        for (i = 0; i < vi->max_queue_pairs; i++)
2769                if (vi->rq[i].alloc_frag.page)
2770                        put_page(vi->rq[i].alloc_frag.page);
2771}
2772
2773static void free_unused_bufs(struct virtnet_info *vi)
2774{
2775        void *buf;
2776        int i;
2777
2778        for (i = 0; i < vi->max_queue_pairs; i++) {
2779                struct virtqueue *vq = vi->sq[i].vq;
2780                while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2781                        if (!is_xdp_frame(buf))
2782                                dev_kfree_skb(buf);
2783                        else
2784                                xdp_return_frame(ptr_to_xdp(buf));
2785                }
2786        }
2787
2788        for (i = 0; i < vi->max_queue_pairs; i++) {
2789                struct virtqueue *vq = vi->rq[i].vq;
2790
2791                while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2792                        if (vi->mergeable_rx_bufs) {
2793                                put_page(virt_to_head_page(buf));
2794                        } else if (vi->big_packets) {
2795                                give_pages(&vi->rq[i], buf);
2796                        } else {
2797                                put_page(virt_to_head_page(buf));
2798                        }
2799                }
2800        }
2801}
2802
2803static void virtnet_del_vqs(struct virtnet_info *vi)
2804{
2805        struct virtio_device *vdev = vi->vdev;
2806
2807        virtnet_clean_affinity(vi);
2808
2809        vdev->config->del_vqs(vdev);
2810
2811        virtnet_free_queues(vi);
2812}
2813
2814/* How large should a single buffer be so a queue full of these can fit at
2815 * least one full packet?
2816 * Logic below assumes the mergeable buffer header is used.
2817 */
2818static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
2819{
2820        const unsigned int hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2821        unsigned int rq_size = virtqueue_get_vring_size(vq);
2822        unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
2823        unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
2824        unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
2825
2826        return max(max(min_buf_len, hdr_len) - hdr_len,
2827                   (unsigned int)GOOD_PACKET_LEN);
2828}
2829
2830static int virtnet_find_vqs(struct virtnet_info *vi)
2831{
2832        vq_callback_t **callbacks;
2833        struct virtqueue **vqs;
2834        int ret = -ENOMEM;
2835        int i, total_vqs;
2836        const char **names;
2837        bool *ctx;
2838
2839        /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
2840         * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
2841         * possible control vq.
2842         */
2843        total_vqs = vi->max_queue_pairs * 2 +
2844                    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
2845
2846        /* Allocate space for find_vqs parameters */
2847        vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
2848        if (!vqs)
2849                goto err_vq;
2850        callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
2851        if (!callbacks)
2852                goto err_callback;
2853        names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
2854        if (!names)
2855                goto err_names;
2856        if (!vi->big_packets || vi->mergeable_rx_bufs) {
2857                ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
2858                if (!ctx)
2859                        goto err_ctx;
2860        } else {
2861                ctx = NULL;
2862        }
2863
2864        /* Parameters for control virtqueue, if any */
2865        if (vi->has_cvq) {
2866                callbacks[total_vqs - 1] = NULL;
2867                names[total_vqs - 1] = "control";
2868        }
2869
2870        /* Allocate/initialize parameters for send/receive virtqueues */
2871        for (i = 0; i < vi->max_queue_pairs; i++) {
2872                callbacks[rxq2vq(i)] = skb_recv_done;
2873                callbacks[txq2vq(i)] = skb_xmit_done;
2874                sprintf(vi->rq[i].name, "input.%d", i);
2875                sprintf(vi->sq[i].name, "output.%d", i);
2876                names[rxq2vq(i)] = vi->rq[i].name;
2877                names[txq2vq(i)] = vi->sq[i].name;
2878                if (ctx)
2879                        ctx[rxq2vq(i)] = true;
2880        }
2881
2882        ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
2883                                  names, ctx, NULL);
2884        if (ret)
2885                goto err_find;
2886
2887        if (vi->has_cvq) {
2888                vi->cvq = vqs[total_vqs - 1];
2889                if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
2890                        vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
2891        }
2892
2893        for (i = 0; i < vi->max_queue_pairs; i++) {
2894                vi->rq[i].vq = vqs[rxq2vq(i)];
2895                vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
2896                vi->sq[i].vq = vqs[txq2vq(i)];
2897        }
2898
2899        /* run here: ret == 0. */
2900
2901
2902err_find:
2903        kfree(ctx);
2904err_ctx:
2905        kfree(names);
2906err_names:
2907        kfree(callbacks);
2908err_callback:
2909        kfree(vqs);
2910err_vq:
2911        return ret;
2912}
2913
2914static int virtnet_alloc_queues(struct virtnet_info *vi)
2915{
2916        int i;
2917
2918        if (vi->has_cvq) {
2919                vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
2920                if (!vi->ctrl)
2921                        goto err_ctrl;
2922        } else {
2923                vi->ctrl = NULL;
2924        }
2925        vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
2926        if (!vi->sq)
2927                goto err_sq;
2928        vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
2929        if (!vi->rq)
2930                goto err_rq;
2931
2932        INIT_DELAYED_WORK(&vi->refill, refill_work);
2933        for (i = 0; i < vi->max_queue_pairs; i++) {
2934                vi->rq[i].pages = NULL;
2935                netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
2936                               napi_weight);
2937                netif_tx_napi_add(vi->dev, &vi->sq[i].napi, virtnet_poll_tx,
2938                                  napi_tx ? napi_weight : 0);
2939
2940                sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
2941                ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
2942                sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
2943
2944                u64_stats_init(&vi->rq[i].stats.syncp);
2945                u64_stats_init(&vi->sq[i].stats.syncp);
2946        }
2947
2948        return 0;
2949
2950err_rq:
2951        kfree(vi->sq);
2952err_sq:
2953        kfree(vi->ctrl);
2954err_ctrl:
2955        return -ENOMEM;
2956}
2957
2958static int init_vqs(struct virtnet_info *vi)
2959{
2960        int ret;
2961
2962        /* Allocate send & receive queues */
2963        ret = virtnet_alloc_queues(vi);
2964        if (ret)
2965                goto err;
2966
2967        ret = virtnet_find_vqs(vi);
2968        if (ret)
2969                goto err_free;
2970
2971        cpus_read_lock();
2972        virtnet_set_affinity(vi);
2973        cpus_read_unlock();
2974
2975        return 0;
2976
2977err_free:
2978        virtnet_free_queues(vi);
2979err:
2980        return ret;
2981}
2982
2983#ifdef CONFIG_SYSFS
2984static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
2985                char *buf)
2986{
2987        struct virtnet_info *vi = netdev_priv(queue->dev);
2988        unsigned int queue_index = get_netdev_rx_queue_index(queue);
2989        unsigned int headroom = virtnet_get_headroom(vi);
2990        unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
2991        struct ewma_pkt_len *avg;
2992
2993        BUG_ON(queue_index >= vi->max_queue_pairs);
2994        avg = &vi->rq[queue_index].mrg_avg_pkt_len;
2995        return sprintf(buf, "%u\n",
2996                       get_mergeable_buf_len(&vi->rq[queue_index], avg,
2997                                       SKB_DATA_ALIGN(headroom + tailroom)));
2998}
2999
3000static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
3001        __ATTR_RO(mergeable_rx_buffer_size);
3002
3003static struct attribute *virtio_net_mrg_rx_attrs[] = {
3004        &mergeable_rx_buffer_size_attribute.attr,
3005        NULL
3006};
3007
3008static const struct attribute_group virtio_net_mrg_rx_group = {
3009        .name = "virtio_net",
3010        .attrs = virtio_net_mrg_rx_attrs
3011};
3012#endif
3013
3014static bool virtnet_fail_on_feature(struct virtio_device *vdev,
3015                                    unsigned int fbit,
3016                                    const char *fname, const char *dname)
3017{
3018        if (!virtio_has_feature(vdev, fbit))
3019                return false;
3020
3021        dev_err(&vdev->dev, "device advertises feature %s but not %s",
3022                fname, dname);
3023
3024        return true;
3025}
3026
3027#define VIRTNET_FAIL_ON(vdev, fbit, dbit)                       \
3028        virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
3029
3030static bool virtnet_validate_features(struct virtio_device *vdev)
3031{
3032        if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
3033            (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
3034                             "VIRTIO_NET_F_CTRL_VQ") ||
3035             VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
3036                             "VIRTIO_NET_F_CTRL_VQ") ||
3037             VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
3038                             "VIRTIO_NET_F_CTRL_VQ") ||
3039             VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
3040             VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
3041                             "VIRTIO_NET_F_CTRL_VQ"))) {
3042                return false;
3043        }
3044
3045        return true;
3046}
3047
3048#define MIN_MTU ETH_MIN_MTU
3049#define MAX_MTU ETH_MAX_MTU
3050
3051static int virtnet_validate(struct virtio_device *vdev)
3052{
3053        if (!vdev->config->get) {
3054                dev_err(&vdev->dev, "%s failure: config access disabled\n",
3055                        __func__);
3056                return -EINVAL;
3057        }
3058
3059        if (!virtnet_validate_features(vdev))
3060                return -EINVAL;
3061
3062        if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3063                int mtu = virtio_cread16(vdev,
3064                                         offsetof(struct virtio_net_config,
3065                                                  mtu));
3066                if (mtu < MIN_MTU)
3067                        __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3068        }
3069
3070        return 0;
3071}
3072
3073static int virtnet_probe(struct virtio_device *vdev)
3074{
3075        int i, err = -ENOMEM;
3076        struct net_device *dev;
3077        struct virtnet_info *vi;
3078        u16 max_queue_pairs;
3079        int mtu;
3080
3081        /* Find if host supports multiqueue virtio_net device */
3082        err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
3083                                   struct virtio_net_config,
3084                                   max_virtqueue_pairs, &max_queue_pairs);
3085
3086        /* We need at least 2 queue's */
3087        if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
3088            max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
3089            !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3090                max_queue_pairs = 1;
3091
3092        /* Allocate ourselves a network device with room for our info */
3093        dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
3094        if (!dev)
3095                return -ENOMEM;
3096
3097        /* Set up network device as normal. */
3098        dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
3099                           IFF_TX_SKB_NO_LINEAR;
3100        dev->netdev_ops = &virtnet_netdev;
3101        dev->features = NETIF_F_HIGHDMA;
3102
3103        dev->ethtool_ops = &virtnet_ethtool_ops;
3104        SET_NETDEV_DEV(dev, &vdev->dev);
3105
3106        /* Do we support "hardware" checksums? */
3107        if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
3108                /* This opens up the world of extra features. */
3109                dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3110                if (csum)
3111                        dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3112
3113                if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
3114                        dev->hw_features |= NETIF_F_TSO
3115                                | NETIF_F_TSO_ECN | NETIF_F_TSO6;
3116                }
3117                /* Individual feature bits: what can host handle? */
3118                if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
3119                        dev->hw_features |= NETIF_F_TSO;
3120                if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
3121                        dev->hw_features |= NETIF_F_TSO6;
3122                if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
3123                        dev->hw_features |= NETIF_F_TSO_ECN;
3124
3125                dev->features |= NETIF_F_GSO_ROBUST;
3126
3127                if (gso)
3128                        dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
3129                /* (!csum && gso) case will be fixed by register_netdev() */
3130        }
3131        if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
3132                dev->features |= NETIF_F_RXCSUM;
3133        if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3134            virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3135                dev->features |= NETIF_F_GRO_HW;
3136        if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3137                dev->hw_features |= NETIF_F_GRO_HW;
3138
3139        dev->vlan_features = dev->features;
3140
3141        /* MTU range: 68 - 65535 */
3142        dev->min_mtu = MIN_MTU;
3143        dev->max_mtu = MAX_MTU;
3144
3145        /* Configuration may specify what MAC to use.  Otherwise random. */
3146        if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
3147                virtio_cread_bytes(vdev,
3148                                   offsetof(struct virtio_net_config, mac),
3149                                   dev->dev_addr, dev->addr_len);
3150        else
3151                eth_hw_addr_random(dev);
3152
3153        /* Set up our device-specific information */
3154        vi = netdev_priv(dev);
3155        vi->dev = dev;
3156        vi->vdev = vdev;
3157        vdev->priv = vi;
3158
3159        INIT_WORK(&vi->config_work, virtnet_config_changed_work);
3160
3161        /* If we can receive ANY GSO packets, we must allocate large ones. */
3162        if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3163            virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3164            virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
3165            virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
3166                vi->big_packets = true;
3167
3168        if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
3169                vi->mergeable_rx_bufs = true;
3170
3171        if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
3172            virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3173                vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
3174        else
3175                vi->hdr_len = sizeof(struct virtio_net_hdr);
3176
3177        if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
3178            virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3179                vi->any_header_sg = true;
3180
3181        if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3182                vi->has_cvq = true;
3183
3184        if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3185                mtu = virtio_cread16(vdev,
3186                                     offsetof(struct virtio_net_config,
3187                                              mtu));
3188                if (mtu < dev->min_mtu) {
3189                        /* Should never trigger: MTU was previously validated
3190                         * in virtnet_validate.
3191                         */
3192                        dev_err(&vdev->dev,
3193                                "device MTU appears to have changed it is now %d < %d",
3194                                mtu, dev->min_mtu);
3195                        err = -EINVAL;
3196                        goto free;
3197                }
3198
3199                dev->mtu = mtu;
3200                dev->max_mtu = mtu;
3201
3202                /* TODO: size buffers correctly in this case. */
3203                if (dev->mtu > ETH_DATA_LEN)
3204                        vi->big_packets = true;
3205        }
3206
3207        if (vi->any_header_sg)
3208                dev->needed_headroom = vi->hdr_len;
3209
3210        /* Enable multiqueue by default */
3211        if (num_online_cpus() >= max_queue_pairs)
3212                vi->curr_queue_pairs = max_queue_pairs;
3213        else
3214                vi->curr_queue_pairs = num_online_cpus();
3215        vi->max_queue_pairs = max_queue_pairs;
3216
3217        /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
3218        err = init_vqs(vi);
3219        if (err)
3220                goto free;
3221
3222#ifdef CONFIG_SYSFS
3223        if (vi->mergeable_rx_bufs)
3224                dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
3225#endif
3226        netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
3227        netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
3228
3229        virtnet_init_settings(dev);
3230
3231        if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
3232                vi->failover = net_failover_create(vi->dev);
3233                if (IS_ERR(vi->failover)) {
3234                        err = PTR_ERR(vi->failover);
3235                        goto free_vqs;
3236                }
3237        }
3238
3239        err = register_netdev(dev);
3240        if (err) {
3241                pr_debug("virtio_net: registering device failed\n");
3242                goto free_failover;
3243        }
3244
3245        virtio_device_ready(vdev);
3246
3247        err = virtnet_cpu_notif_add(vi);
3248        if (err) {
3249                pr_debug("virtio_net: registering cpu notifier failed\n");
3250                goto free_unregister_netdev;
3251        }
3252
3253        virtnet_set_queues(vi, vi->curr_queue_pairs);
3254
3255        /* Assume link up if device can't report link status,
3256           otherwise get link status from config. */
3257        netif_carrier_off(dev);
3258        if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
3259                schedule_work(&vi->config_work);
3260        } else {
3261                vi->status = VIRTIO_NET_S_LINK_UP;
3262                virtnet_update_settings(vi);
3263                netif_carrier_on(dev);
3264        }
3265
3266        for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
3267                if (virtio_has_feature(vi->vdev, guest_offloads[i]))
3268                        set_bit(guest_offloads[i], &vi->guest_offloads);
3269        vi->guest_offloads_capable = vi->guest_offloads;
3270
3271        pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
3272                 dev->name, max_queue_pairs);
3273
3274        return 0;
3275
3276free_unregister_netdev:
3277        vi->vdev->config->reset(vdev);
3278
3279        unregister_netdev(dev);
3280free_failover:
3281        net_failover_destroy(vi->failover);
3282free_vqs:
3283        cancel_delayed_work_sync(&vi->refill);
3284        free_receive_page_frags(vi);
3285        virtnet_del_vqs(vi);
3286free:
3287        free_netdev(dev);
3288        return err;
3289}
3290
3291static void remove_vq_common(struct virtnet_info *vi)
3292{
3293        vi->vdev->config->reset(vi->vdev);
3294
3295        /* Free unused buffers in both send and recv, if any. */
3296        free_unused_bufs(vi);
3297
3298        free_receive_bufs(vi);
3299
3300        free_receive_page_frags(vi);
3301
3302        virtnet_del_vqs(vi);
3303}
3304
3305static void virtnet_remove(struct virtio_device *vdev)
3306{
3307        struct virtnet_info *vi = vdev->priv;
3308
3309        virtnet_cpu_notif_remove(vi);
3310
3311        /* Make sure no work handler is accessing the device. */
3312        flush_work(&vi->config_work);
3313
3314        unregister_netdev(vi->dev);
3315
3316        net_failover_destroy(vi->failover);
3317
3318        remove_vq_common(vi);
3319
3320        free_netdev(vi->dev);
3321}
3322
3323static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
3324{
3325        struct virtnet_info *vi = vdev->priv;
3326
3327        virtnet_cpu_notif_remove(vi);
3328        virtnet_freeze_down(vdev);
3329        remove_vq_common(vi);
3330
3331        return 0;
3332}
3333
3334static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
3335{
3336        struct virtnet_info *vi = vdev->priv;
3337        int err;
3338
3339        err = virtnet_restore_up(vdev);
3340        if (err)
3341                return err;
3342        virtnet_set_queues(vi, vi->curr_queue_pairs);
3343
3344        err = virtnet_cpu_notif_add(vi);
3345        if (err) {
3346                virtnet_freeze_down(vdev);
3347                remove_vq_common(vi);
3348                return err;
3349        }
3350
3351        return 0;
3352}
3353
3354static struct virtio_device_id id_table[] = {
3355        { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
3356        { 0 },
3357};
3358
3359#define VIRTNET_FEATURES \
3360        VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
3361        VIRTIO_NET_F_MAC, \
3362        VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
3363        VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
3364        VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
3365        VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
3366        VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
3367        VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
3368        VIRTIO_NET_F_CTRL_MAC_ADDR, \
3369        VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
3370        VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY
3371
3372static unsigned int features[] = {
3373        VIRTNET_FEATURES,
3374};
3375
3376static unsigned int features_legacy[] = {
3377        VIRTNET_FEATURES,
3378        VIRTIO_NET_F_GSO,
3379        VIRTIO_F_ANY_LAYOUT,
3380};
3381
3382static struct virtio_driver virtio_net_driver = {
3383        .feature_table = features,
3384        .feature_table_size = ARRAY_SIZE(features),
3385        .feature_table_legacy = features_legacy,
3386        .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
3387        .driver.name =  KBUILD_MODNAME,
3388        .driver.owner = THIS_MODULE,
3389        .id_table =     id_table,
3390        .validate =     virtnet_validate,
3391        .probe =        virtnet_probe,
3392        .remove =       virtnet_remove,
3393        .config_changed = virtnet_config_changed,
3394#ifdef CONFIG_PM_SLEEP
3395        .freeze =       virtnet_freeze,
3396        .restore =      virtnet_restore,
3397#endif
3398};
3399
3400static __init int virtio_net_driver_init(void)
3401{
3402        int ret;
3403
3404        ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
3405                                      virtnet_cpu_online,
3406                                      virtnet_cpu_down_prep);
3407        if (ret < 0)
3408                goto out;
3409        virtionet_online = ret;
3410        ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
3411                                      NULL, virtnet_cpu_dead);
3412        if (ret)
3413                goto err_dead;
3414
3415        ret = register_virtio_driver(&virtio_net_driver);
3416        if (ret)
3417                goto err_virtio;
3418        return 0;
3419err_virtio:
3420        cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
3421err_dead:
3422        cpuhp_remove_multi_state(virtionet_online);
3423out:
3424        return ret;
3425}
3426module_init(virtio_net_driver_init);
3427
3428static __exit void virtio_net_driver_exit(void)
3429{
3430        unregister_virtio_driver(&virtio_net_driver);
3431        cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
3432        cpuhp_remove_multi_state(virtionet_online);
3433}
3434module_exit(virtio_net_driver_exit);
3435
3436MODULE_DEVICE_TABLE(virtio, id_table);
3437MODULE_DESCRIPTION("Virtio network driver");
3438MODULE_LICENSE("GPL");
3439