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