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