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