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