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