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