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