wifi: iwlwifi: mei: re-ask for ownership after it was taken by CSME
[linux-block.git] / drivers / net / virtio_net.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* A network driver using virtio.
3  *
4  * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
5  */
6 //#define DEBUG
7 #include <linux/netdevice.h>
8 #include <linux/etherdevice.h>
9 #include <linux/ethtool.h>
10 #include <linux/module.h>
11 #include <linux/virtio.h>
12 #include <linux/virtio_net.h>
13 #include <linux/bpf.h>
14 #include <linux/bpf_trace.h>
15 #include <linux/scatterlist.h>
16 #include <linux/if_vlan.h>
17 #include <linux/slab.h>
18 #include <linux/cpu.h>
19 #include <linux/average.h>
20 #include <linux/filter.h>
21 #include <linux/kernel.h>
22 #include <net/route.h>
23 #include <net/xdp.h>
24 #include <net/net_failover.h>
25
26 static int napi_weight = NAPI_POLL_WEIGHT;
27 module_param(napi_weight, int, 0444);
28
29 static bool csum = true, gso = true, napi_tx = true;
30 module_param(csum, bool, 0444);
31 module_param(gso, bool, 0444);
32 module_param(napi_tx, bool, 0644);
33
34 /* FIXME: MTU in config. */
35 #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
36 #define GOOD_COPY_LEN   128
37
38 #define VIRTNET_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
39
40 /* Amount of XDP headroom to prepend to packets for use by xdp_adjust_head */
41 #define VIRTIO_XDP_HEADROOM 256
42
43 /* Separating two types of XDP xmit */
44 #define VIRTIO_XDP_TX           BIT(0)
45 #define VIRTIO_XDP_REDIR        BIT(1)
46
47 #define VIRTIO_XDP_FLAG BIT(0)
48
49 /* RX packet size EWMA. The average packet size is used to determine the packet
50  * buffer size when refilling RX rings. As the entire RX ring may be refilled
51  * at once, the weight is chosen so that the EWMA will be insensitive to short-
52  * term, transient changes in packet size.
53  */
54 DECLARE_EWMA(pkt_len, 0, 64)
55
56 #define VIRTNET_DRIVER_VERSION "1.0.0"
57
58 static const unsigned long guest_offloads[] = {
59         VIRTIO_NET_F_GUEST_TSO4,
60         VIRTIO_NET_F_GUEST_TSO6,
61         VIRTIO_NET_F_GUEST_ECN,
62         VIRTIO_NET_F_GUEST_UFO,
63         VIRTIO_NET_F_GUEST_CSUM,
64         VIRTIO_NET_F_GUEST_USO4,
65         VIRTIO_NET_F_GUEST_USO6,
66         VIRTIO_NET_F_GUEST_HDRLEN
67 };
68
69 #define GUEST_OFFLOAD_GRO_HW_MASK ((1ULL << VIRTIO_NET_F_GUEST_TSO4) | \
70                                 (1ULL << VIRTIO_NET_F_GUEST_TSO6) | \
71                                 (1ULL << VIRTIO_NET_F_GUEST_ECN)  | \
72                                 (1ULL << VIRTIO_NET_F_GUEST_UFO)  | \
73                                 (1ULL << VIRTIO_NET_F_GUEST_USO4) | \
74                                 (1ULL << VIRTIO_NET_F_GUEST_USO6))
75
76 struct virtnet_stat_desc {
77         char desc[ETH_GSTRING_LEN];
78         size_t offset;
79 };
80
81 struct virtnet_sq_stats {
82         struct u64_stats_sync syncp;
83         u64 packets;
84         u64 bytes;
85         u64 xdp_tx;
86         u64 xdp_tx_drops;
87         u64 kicks;
88         u64 tx_timeouts;
89 };
90
91 struct virtnet_rq_stats {
92         struct u64_stats_sync syncp;
93         u64 packets;
94         u64 bytes;
95         u64 drops;
96         u64 xdp_packets;
97         u64 xdp_tx;
98         u64 xdp_redirects;
99         u64 xdp_drops;
100         u64 kicks;
101 };
102
103 #define VIRTNET_SQ_STAT(m)      offsetof(struct virtnet_sq_stats, m)
104 #define VIRTNET_RQ_STAT(m)      offsetof(struct virtnet_rq_stats, m)
105
106 static const struct virtnet_stat_desc virtnet_sq_stats_desc[] = {
107         { "packets",            VIRTNET_SQ_STAT(packets) },
108         { "bytes",              VIRTNET_SQ_STAT(bytes) },
109         { "xdp_tx",             VIRTNET_SQ_STAT(xdp_tx) },
110         { "xdp_tx_drops",       VIRTNET_SQ_STAT(xdp_tx_drops) },
111         { "kicks",              VIRTNET_SQ_STAT(kicks) },
112         { "tx_timeouts",        VIRTNET_SQ_STAT(tx_timeouts) },
113 };
114
115 static const struct virtnet_stat_desc virtnet_rq_stats_desc[] = {
116         { "packets",            VIRTNET_RQ_STAT(packets) },
117         { "bytes",              VIRTNET_RQ_STAT(bytes) },
118         { "drops",              VIRTNET_RQ_STAT(drops) },
119         { "xdp_packets",        VIRTNET_RQ_STAT(xdp_packets) },
120         { "xdp_tx",             VIRTNET_RQ_STAT(xdp_tx) },
121         { "xdp_redirects",      VIRTNET_RQ_STAT(xdp_redirects) },
122         { "xdp_drops",          VIRTNET_RQ_STAT(xdp_drops) },
123         { "kicks",              VIRTNET_RQ_STAT(kicks) },
124 };
125
126 #define VIRTNET_SQ_STATS_LEN    ARRAY_SIZE(virtnet_sq_stats_desc)
127 #define VIRTNET_RQ_STATS_LEN    ARRAY_SIZE(virtnet_rq_stats_desc)
128
129 /* Internal representation of a send virtqueue */
130 struct send_queue {
131         /* Virtqueue associated with this send _queue */
132         struct virtqueue *vq;
133
134         /* TX: fragments + linear part + virtio header */
135         struct scatterlist sg[MAX_SKB_FRAGS + 2];
136
137         /* Name of the send queue: output.$index */
138         char name[16];
139
140         struct virtnet_sq_stats stats;
141
142         struct napi_struct napi;
143
144         /* Record whether sq is in reset state. */
145         bool reset;
146 };
147
148 /* Internal representation of a receive virtqueue */
149 struct receive_queue {
150         /* Virtqueue associated with this receive_queue */
151         struct virtqueue *vq;
152
153         struct napi_struct napi;
154
155         struct bpf_prog __rcu *xdp_prog;
156
157         struct virtnet_rq_stats stats;
158
159         /* Chain pages by the private ptr. */
160         struct page *pages;
161
162         /* Average packet length for mergeable receive buffers. */
163         struct ewma_pkt_len mrg_avg_pkt_len;
164
165         /* Page frag for packet buffer allocation. */
166         struct page_frag alloc_frag;
167
168         /* RX: fragments + linear part + virtio header */
169         struct scatterlist sg[MAX_SKB_FRAGS + 2];
170
171         /* Min single buffer size for mergeable buffers case. */
172         unsigned int min_buf_len;
173
174         /* Name of this receive queue: input.$index */
175         char name[16];
176
177         struct xdp_rxq_info xdp_rxq;
178 };
179
180 /* This structure can contain rss message with maximum settings for indirection table and keysize
181  * Note, that default structure that describes RSS configuration virtio_net_rss_config
182  * contains same info but can't handle table values.
183  * In any case, structure would be passed to virtio hw through sg_buf split by parts
184  * because table sizes may be differ according to the device configuration.
185  */
186 #define VIRTIO_NET_RSS_MAX_KEY_SIZE     40
187 #define VIRTIO_NET_RSS_MAX_TABLE_LEN    128
188 struct virtio_net_ctrl_rss {
189         u32 hash_types;
190         u16 indirection_table_mask;
191         u16 unclassified_queue;
192         u16 indirection_table[VIRTIO_NET_RSS_MAX_TABLE_LEN];
193         u16 max_tx_vq;
194         u8 hash_key_length;
195         u8 key[VIRTIO_NET_RSS_MAX_KEY_SIZE];
196 };
197
198 /* Control VQ buffers: protected by the rtnl lock */
199 struct control_buf {
200         struct virtio_net_ctrl_hdr hdr;
201         virtio_net_ctrl_ack status;
202         struct virtio_net_ctrl_mq mq;
203         u8 promisc;
204         u8 allmulti;
205         __virtio16 vid;
206         __virtio64 offloads;
207         struct virtio_net_ctrl_rss rss;
208 };
209
210 struct virtnet_info {
211         struct virtio_device *vdev;
212         struct virtqueue *cvq;
213         struct net_device *dev;
214         struct send_queue *sq;
215         struct receive_queue *rq;
216         unsigned int status;
217
218         /* Max # of queue pairs supported by the device */
219         u16 max_queue_pairs;
220
221         /* # of queue pairs currently used by the driver */
222         u16 curr_queue_pairs;
223
224         /* # of XDP queue pairs currently used by the driver */
225         u16 xdp_queue_pairs;
226
227         /* xdp_queue_pairs may be 0, when xdp is already loaded. So add this. */
228         bool xdp_enabled;
229
230         /* I like... big packets and I cannot lie! */
231         bool big_packets;
232
233         /* number of sg entries allocated for big packets */
234         unsigned int big_packets_num_skbfrags;
235
236         /* Host will merge rx buffers for big packets (shake it! shake it!) */
237         bool mergeable_rx_bufs;
238
239         /* Host supports rss and/or hash report */
240         bool has_rss;
241         bool has_rss_hash_report;
242         u8 rss_key_size;
243         u16 rss_indir_table_size;
244         u32 rss_hash_types_supported;
245         u32 rss_hash_types_saved;
246
247         /* Has control virtqueue */
248         bool has_cvq;
249
250         /* Host can handle any s/g split between our header and packet data */
251         bool any_header_sg;
252
253         /* Packet virtio header size */
254         u8 hdr_len;
255
256         /* Work struct for delayed refilling if we run low on memory. */
257         struct delayed_work refill;
258
259         /* Is delayed refill enabled? */
260         bool refill_enabled;
261
262         /* The lock to synchronize the access to refill_enabled */
263         spinlock_t refill_lock;
264
265         /* Work struct for config space updates */
266         struct work_struct config_work;
267
268         /* Does the affinity hint is set for virtqueues? */
269         bool affinity_hint_set;
270
271         /* CPU hotplug instances for online & dead */
272         struct hlist_node node;
273         struct hlist_node node_dead;
274
275         struct control_buf *ctrl;
276
277         /* Ethtool settings */
278         u8 duplex;
279         u32 speed;
280
281         /* Interrupt coalescing settings */
282         u32 tx_usecs;
283         u32 rx_usecs;
284         u32 tx_max_packets;
285         u32 rx_max_packets;
286
287         unsigned long guest_offloads;
288         unsigned long guest_offloads_capable;
289
290         /* failover when STANDBY feature enabled */
291         struct failover *failover;
292 };
293
294 struct padded_vnet_hdr {
295         struct virtio_net_hdr_v1_hash hdr;
296         /*
297          * hdr is in a separate sg buffer, and data sg buffer shares same page
298          * with this header sg. This padding makes next sg 16 byte aligned
299          * after the header.
300          */
301         char padding[12];
302 };
303
304 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf);
305 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf);
306
307 static bool is_xdp_frame(void *ptr)
308 {
309         return (unsigned long)ptr & VIRTIO_XDP_FLAG;
310 }
311
312 static void *xdp_to_ptr(struct xdp_frame *ptr)
313 {
314         return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
315 }
316
317 static struct xdp_frame *ptr_to_xdp(void *ptr)
318 {
319         return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
320 }
321
322 /* Converting between virtqueue no. and kernel tx/rx queue no.
323  * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
324  */
325 static int vq2txq(struct virtqueue *vq)
326 {
327         return (vq->index - 1) / 2;
328 }
329
330 static int txq2vq(int txq)
331 {
332         return txq * 2 + 1;
333 }
334
335 static int vq2rxq(struct virtqueue *vq)
336 {
337         return vq->index / 2;
338 }
339
340 static int rxq2vq(int rxq)
341 {
342         return rxq * 2;
343 }
344
345 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
346 {
347         return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
348 }
349
350 /*
351  * private is used to chain pages for big packets, put the whole
352  * most recent used list in the beginning for reuse
353  */
354 static void give_pages(struct receive_queue *rq, struct page *page)
355 {
356         struct page *end;
357
358         /* Find end of list, sew whole thing into vi->rq.pages. */
359         for (end = page; end->private; end = (struct page *)end->private);
360         end->private = (unsigned long)rq->pages;
361         rq->pages = page;
362 }
363
364 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
365 {
366         struct page *p = rq->pages;
367
368         if (p) {
369                 rq->pages = (struct page *)p->private;
370                 /* clear private here, it is used to chain pages */
371                 p->private = 0;
372         } else
373                 p = alloc_page(gfp_mask);
374         return p;
375 }
376
377 static void enable_delayed_refill(struct virtnet_info *vi)
378 {
379         spin_lock_bh(&vi->refill_lock);
380         vi->refill_enabled = true;
381         spin_unlock_bh(&vi->refill_lock);
382 }
383
384 static void disable_delayed_refill(struct virtnet_info *vi)
385 {
386         spin_lock_bh(&vi->refill_lock);
387         vi->refill_enabled = false;
388         spin_unlock_bh(&vi->refill_lock);
389 }
390
391 static void virtqueue_napi_schedule(struct napi_struct *napi,
392                                     struct virtqueue *vq)
393 {
394         if (napi_schedule_prep(napi)) {
395                 virtqueue_disable_cb(vq);
396                 __napi_schedule(napi);
397         }
398 }
399
400 static void virtqueue_napi_complete(struct napi_struct *napi,
401                                     struct virtqueue *vq, int processed)
402 {
403         int opaque;
404
405         opaque = virtqueue_enable_cb_prepare(vq);
406         if (napi_complete_done(napi, processed)) {
407                 if (unlikely(virtqueue_poll(vq, opaque)))
408                         virtqueue_napi_schedule(napi, vq);
409         } else {
410                 virtqueue_disable_cb(vq);
411         }
412 }
413
414 static void skb_xmit_done(struct virtqueue *vq)
415 {
416         struct virtnet_info *vi = vq->vdev->priv;
417         struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
418
419         /* Suppress further interrupts. */
420         virtqueue_disable_cb(vq);
421
422         if (napi->weight)
423                 virtqueue_napi_schedule(napi, vq);
424         else
425                 /* We were probably waiting for more output buffers. */
426                 netif_wake_subqueue(vi->dev, vq2txq(vq));
427 }
428
429 #define MRG_CTX_HEADER_SHIFT 22
430 static void *mergeable_len_to_ctx(unsigned int truesize,
431                                   unsigned int headroom)
432 {
433         return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
434 }
435
436 static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
437 {
438         return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
439 }
440
441 static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
442 {
443         return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
444 }
445
446 /* Called from bottom half context */
447 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
448                                    struct receive_queue *rq,
449                                    struct page *page, unsigned int offset,
450                                    unsigned int len, unsigned int truesize,
451                                    unsigned int headroom)
452 {
453         struct sk_buff *skb;
454         struct virtio_net_hdr_mrg_rxbuf *hdr;
455         unsigned int copy, hdr_len, hdr_padded_len;
456         struct page *page_to_free = NULL;
457         int tailroom, shinfo_size;
458         char *p, *hdr_p, *buf;
459
460         p = page_address(page) + offset;
461         hdr_p = p;
462
463         hdr_len = vi->hdr_len;
464         if (vi->mergeable_rx_bufs)
465                 hdr_padded_len = hdr_len;
466         else
467                 hdr_padded_len = sizeof(struct padded_vnet_hdr);
468
469         buf = p - headroom;
470         len -= hdr_len;
471         offset += hdr_padded_len;
472         p += hdr_padded_len;
473         tailroom = truesize - headroom  - hdr_padded_len - len;
474
475         shinfo_size = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
476
477         /* copy small packet so we can reuse these pages */
478         if (!NET_IP_ALIGN && len > GOOD_COPY_LEN && tailroom >= shinfo_size) {
479                 skb = build_skb(buf, truesize);
480                 if (unlikely(!skb))
481                         return NULL;
482
483                 skb_reserve(skb, p - buf);
484                 skb_put(skb, len);
485
486                 page = (struct page *)page->private;
487                 if (page)
488                         give_pages(rq, page);
489                 goto ok;
490         }
491
492         /* copy small packet so we can reuse these pages for small data */
493         skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
494         if (unlikely(!skb))
495                 return NULL;
496
497         /* Copy all frame if it fits skb->head, otherwise
498          * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
499          */
500         if (len <= skb_tailroom(skb))
501                 copy = len;
502         else
503                 copy = ETH_HLEN;
504         skb_put_data(skb, p, copy);
505
506         len -= copy;
507         offset += copy;
508
509         if (vi->mergeable_rx_bufs) {
510                 if (len)
511                         skb_add_rx_frag(skb, 0, page, offset, len, truesize);
512                 else
513                         page_to_free = page;
514                 goto ok;
515         }
516
517         /*
518          * Verify that we can indeed put this data into a skb.
519          * This is here to handle cases when the device erroneously
520          * tries to receive more than is possible. This is usually
521          * the case of a broken device.
522          */
523         if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
524                 net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
525                 dev_kfree_skb(skb);
526                 return NULL;
527         }
528         BUG_ON(offset >= PAGE_SIZE);
529         while (len) {
530                 unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
531                 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
532                                 frag_size, truesize);
533                 len -= frag_size;
534                 page = (struct page *)page->private;
535                 offset = 0;
536         }
537
538         if (page)
539                 give_pages(rq, page);
540
541 ok:
542         hdr = skb_vnet_hdr(skb);
543         memcpy(hdr, hdr_p, hdr_len);
544         if (page_to_free)
545                 put_page(page_to_free);
546
547         return skb;
548 }
549
550 static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
551 {
552         unsigned int len;
553         unsigned int packets = 0;
554         unsigned int bytes = 0;
555         void *ptr;
556
557         while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
558                 if (likely(!is_xdp_frame(ptr))) {
559                         struct sk_buff *skb = ptr;
560
561                         pr_debug("Sent skb %p\n", skb);
562
563                         bytes += skb->len;
564                         napi_consume_skb(skb, in_napi);
565                 } else {
566                         struct xdp_frame *frame = ptr_to_xdp(ptr);
567
568                         bytes += xdp_get_frame_len(frame);
569                         xdp_return_frame(frame);
570                 }
571                 packets++;
572         }
573
574         /* Avoid overhead when no packets have been processed
575          * happens when called speculatively from start_xmit.
576          */
577         if (!packets)
578                 return;
579
580         u64_stats_update_begin(&sq->stats.syncp);
581         sq->stats.bytes += bytes;
582         sq->stats.packets += packets;
583         u64_stats_update_end(&sq->stats.syncp);
584 }
585
586 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
587 {
588         if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
589                 return false;
590         else if (q < vi->curr_queue_pairs)
591                 return true;
592         else
593                 return false;
594 }
595
596 static void check_sq_full_and_disable(struct virtnet_info *vi,
597                                       struct net_device *dev,
598                                       struct send_queue *sq)
599 {
600         bool use_napi = sq->napi.weight;
601         int qnum;
602
603         qnum = sq - vi->sq;
604
605         /* If running out of space, stop queue to avoid getting packets that we
606          * are then unable to transmit.
607          * An alternative would be to force queuing layer to requeue the skb by
608          * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
609          * returned in a normal path of operation: it means that driver is not
610          * maintaining the TX queue stop/start state properly, and causes
611          * the stack to do a non-trivial amount of useless work.
612          * Since most packets only take 1 or 2 ring slots, stopping the queue
613          * early means 16 slots are typically wasted.
614          */
615         if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
616                 netif_stop_subqueue(dev, qnum);
617                 if (use_napi) {
618                         if (unlikely(!virtqueue_enable_cb_delayed(sq->vq)))
619                                 virtqueue_napi_schedule(&sq->napi, sq->vq);
620                 } else if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
621                         /* More just got used, free them then recheck. */
622                         free_old_xmit_skbs(sq, false);
623                         if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
624                                 netif_start_subqueue(dev, qnum);
625                                 virtqueue_disable_cb(sq->vq);
626                         }
627                 }
628         }
629 }
630
631 static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
632                                    struct send_queue *sq,
633                                    struct xdp_frame *xdpf)
634 {
635         struct virtio_net_hdr_mrg_rxbuf *hdr;
636         struct skb_shared_info *shinfo;
637         u8 nr_frags = 0;
638         int err, i;
639
640         if (unlikely(xdpf->headroom < vi->hdr_len))
641                 return -EOVERFLOW;
642
643         if (unlikely(xdp_frame_has_frags(xdpf))) {
644                 shinfo = xdp_get_shared_info_from_frame(xdpf);
645                 nr_frags = shinfo->nr_frags;
646         }
647
648         /* In wrapping function virtnet_xdp_xmit(), we need to free
649          * up the pending old buffers, where we need to calculate the
650          * position of skb_shared_info in xdp_get_frame_len() and
651          * xdp_return_frame(), which will involve to xdpf->data and
652          * xdpf->headroom. Therefore, we need to update the value of
653          * headroom synchronously here.
654          */
655         xdpf->headroom -= vi->hdr_len;
656         xdpf->data -= vi->hdr_len;
657         /* Zero header and leave csum up to XDP layers */
658         hdr = xdpf->data;
659         memset(hdr, 0, vi->hdr_len);
660         xdpf->len   += vi->hdr_len;
661
662         sg_init_table(sq->sg, nr_frags + 1);
663         sg_set_buf(sq->sg, xdpf->data, xdpf->len);
664         for (i = 0; i < nr_frags; i++) {
665                 skb_frag_t *frag = &shinfo->frags[i];
666
667                 sg_set_page(&sq->sg[i + 1], skb_frag_page(frag),
668                             skb_frag_size(frag), skb_frag_off(frag));
669         }
670
671         err = virtqueue_add_outbuf(sq->vq, sq->sg, nr_frags + 1,
672                                    xdp_to_ptr(xdpf), GFP_ATOMIC);
673         if (unlikely(err))
674                 return -ENOSPC; /* Caller handle free/refcnt */
675
676         return 0;
677 }
678
679 /* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
680  * the current cpu, so it does not need to be locked.
681  *
682  * Here we use marco instead of inline functions because we have to deal with
683  * three issues at the same time: 1. the choice of sq. 2. judge and execute the
684  * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
685  * functions to perfectly solve these three problems at the same time.
686  */
687 #define virtnet_xdp_get_sq(vi) ({                                       \
688         int cpu = smp_processor_id();                                   \
689         struct netdev_queue *txq;                                       \
690         typeof(vi) v = (vi);                                            \
691         unsigned int qp;                                                \
692                                                                         \
693         if (v->curr_queue_pairs > nr_cpu_ids) {                         \
694                 qp = v->curr_queue_pairs - v->xdp_queue_pairs;          \
695                 qp += cpu;                                              \
696                 txq = netdev_get_tx_queue(v->dev, qp);                  \
697                 __netif_tx_acquire(txq);                                \
698         } else {                                                        \
699                 qp = cpu % v->curr_queue_pairs;                         \
700                 txq = netdev_get_tx_queue(v->dev, qp);                  \
701                 __netif_tx_lock(txq, cpu);                              \
702         }                                                               \
703         v->sq + qp;                                                     \
704 })
705
706 #define virtnet_xdp_put_sq(vi, q) {                                     \
707         struct netdev_queue *txq;                                       \
708         typeof(vi) v = (vi);                                            \
709                                                                         \
710         txq = netdev_get_tx_queue(v->dev, (q) - v->sq);                 \
711         if (v->curr_queue_pairs > nr_cpu_ids)                           \
712                 __netif_tx_release(txq);                                \
713         else                                                            \
714                 __netif_tx_unlock(txq);                                 \
715 }
716
717 static int virtnet_xdp_xmit(struct net_device *dev,
718                             int n, struct xdp_frame **frames, u32 flags)
719 {
720         struct virtnet_info *vi = netdev_priv(dev);
721         struct receive_queue *rq = vi->rq;
722         struct bpf_prog *xdp_prog;
723         struct send_queue *sq;
724         unsigned int len;
725         int packets = 0;
726         int bytes = 0;
727         int nxmit = 0;
728         int kicks = 0;
729         void *ptr;
730         int ret;
731         int i;
732
733         /* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
734          * indicate XDP resources have been successfully allocated.
735          */
736         xdp_prog = rcu_access_pointer(rq->xdp_prog);
737         if (!xdp_prog)
738                 return -ENXIO;
739
740         sq = virtnet_xdp_get_sq(vi);
741
742         if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
743                 ret = -EINVAL;
744                 goto out;
745         }
746
747         /* Free up any pending old buffers before queueing new ones. */
748         while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
749                 if (likely(is_xdp_frame(ptr))) {
750                         struct xdp_frame *frame = ptr_to_xdp(ptr);
751
752                         bytes += xdp_get_frame_len(frame);
753                         xdp_return_frame(frame);
754                 } else {
755                         struct sk_buff *skb = ptr;
756
757                         bytes += skb->len;
758                         napi_consume_skb(skb, false);
759                 }
760                 packets++;
761         }
762
763         for (i = 0; i < n; i++) {
764                 struct xdp_frame *xdpf = frames[i];
765
766                 if (__virtnet_xdp_xmit_one(vi, sq, xdpf))
767                         break;
768                 nxmit++;
769         }
770         ret = nxmit;
771
772         if (!is_xdp_raw_buffer_queue(vi, sq - vi->sq))
773                 check_sq_full_and_disable(vi, dev, sq);
774
775         if (flags & XDP_XMIT_FLUSH) {
776                 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
777                         kicks = 1;
778         }
779 out:
780         u64_stats_update_begin(&sq->stats.syncp);
781         sq->stats.bytes += bytes;
782         sq->stats.packets += packets;
783         sq->stats.xdp_tx += n;
784         sq->stats.xdp_tx_drops += n - nxmit;
785         sq->stats.kicks += kicks;
786         u64_stats_update_end(&sq->stats.syncp);
787
788         virtnet_xdp_put_sq(vi, sq);
789         return ret;
790 }
791
792 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
793 {
794         return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
795 }
796
797 /* We copy the packet for XDP in the following cases:
798  *
799  * 1) Packet is scattered across multiple rx buffers.
800  * 2) Headroom space is insufficient.
801  *
802  * This is inefficient but it's a temporary condition that
803  * we hit right after XDP is enabled and until queue is refilled
804  * with large buffers with sufficient headroom - so it should affect
805  * at most queue size packets.
806  * Afterwards, the conditions to enable
807  * XDP should preclude the underlying device from sending packets
808  * across multiple buffers (num_buf > 1), and we make sure buffers
809  * have enough headroom.
810  */
811 static struct page *xdp_linearize_page(struct receive_queue *rq,
812                                        int *num_buf,
813                                        struct page *p,
814                                        int offset,
815                                        int page_off,
816                                        unsigned int *len)
817 {
818         struct page *page = alloc_page(GFP_ATOMIC);
819
820         if (!page)
821                 return NULL;
822
823         memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
824         page_off += *len;
825
826         while (--*num_buf) {
827                 int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
828                 unsigned int buflen;
829                 void *buf;
830                 int off;
831
832                 buf = virtqueue_get_buf(rq->vq, &buflen);
833                 if (unlikely(!buf))
834                         goto err_buf;
835
836                 p = virt_to_head_page(buf);
837                 off = buf - page_address(p);
838
839                 /* guard against a misconfigured or uncooperative backend that
840                  * is sending packet larger than the MTU.
841                  */
842                 if ((page_off + buflen + tailroom) > PAGE_SIZE) {
843                         put_page(p);
844                         goto err_buf;
845                 }
846
847                 memcpy(page_address(page) + page_off,
848                        page_address(p) + off, buflen);
849                 page_off += buflen;
850                 put_page(p);
851         }
852
853         /* Headroom does not contribute to packet length */
854         *len = page_off - VIRTIO_XDP_HEADROOM;
855         return page;
856 err_buf:
857         __free_pages(page, 0);
858         return NULL;
859 }
860
861 static struct sk_buff *receive_small(struct net_device *dev,
862                                      struct virtnet_info *vi,
863                                      struct receive_queue *rq,
864                                      void *buf, void *ctx,
865                                      unsigned int len,
866                                      unsigned int *xdp_xmit,
867                                      struct virtnet_rq_stats *stats)
868 {
869         struct sk_buff *skb;
870         struct bpf_prog *xdp_prog;
871         unsigned int xdp_headroom = (unsigned long)ctx;
872         unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
873         unsigned int headroom = vi->hdr_len + header_offset;
874         unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
875                               SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
876         struct page *page = virt_to_head_page(buf);
877         unsigned int delta = 0;
878         struct page *xdp_page;
879         int err;
880         unsigned int metasize = 0;
881
882         len -= vi->hdr_len;
883         stats->bytes += len;
884
885         if (unlikely(len > GOOD_PACKET_LEN)) {
886                 pr_debug("%s: rx error: len %u exceeds max size %d\n",
887                          dev->name, len, GOOD_PACKET_LEN);
888                 dev->stats.rx_length_errors++;
889                 goto err;
890         }
891
892         if (likely(!vi->xdp_enabled)) {
893                 xdp_prog = NULL;
894                 goto skip_xdp;
895         }
896
897         rcu_read_lock();
898         xdp_prog = rcu_dereference(rq->xdp_prog);
899         if (xdp_prog) {
900                 struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
901                 struct xdp_frame *xdpf;
902                 struct xdp_buff xdp;
903                 void *orig_data;
904                 u32 act;
905
906                 if (unlikely(hdr->hdr.gso_type))
907                         goto err_xdp;
908
909                 if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
910                         int offset = buf - page_address(page) + header_offset;
911                         unsigned int tlen = len + vi->hdr_len;
912                         int num_buf = 1;
913
914                         xdp_headroom = virtnet_get_headroom(vi);
915                         header_offset = VIRTNET_RX_PAD + xdp_headroom;
916                         headroom = vi->hdr_len + header_offset;
917                         buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
918                                  SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
919                         xdp_page = xdp_linearize_page(rq, &num_buf, page,
920                                                       offset, header_offset,
921                                                       &tlen);
922                         if (!xdp_page)
923                                 goto err_xdp;
924
925                         buf = page_address(xdp_page);
926                         put_page(page);
927                         page = xdp_page;
928                 }
929
930                 xdp_init_buff(&xdp, buflen, &rq->xdp_rxq);
931                 xdp_prepare_buff(&xdp, buf + VIRTNET_RX_PAD + vi->hdr_len,
932                                  xdp_headroom, len, true);
933                 orig_data = xdp.data;
934                 act = bpf_prog_run_xdp(xdp_prog, &xdp);
935                 stats->xdp_packets++;
936
937                 switch (act) {
938                 case XDP_PASS:
939                         /* Recalculate length in case bpf program changed it */
940                         delta = orig_data - xdp.data;
941                         len = xdp.data_end - xdp.data;
942                         metasize = xdp.data - xdp.data_meta;
943                         break;
944                 case XDP_TX:
945                         stats->xdp_tx++;
946                         xdpf = xdp_convert_buff_to_frame(&xdp);
947                         if (unlikely(!xdpf))
948                                 goto err_xdp;
949                         err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
950                         if (unlikely(!err)) {
951                                 xdp_return_frame_rx_napi(xdpf);
952                         } else if (unlikely(err < 0)) {
953                                 trace_xdp_exception(vi->dev, xdp_prog, act);
954                                 goto err_xdp;
955                         }
956                         *xdp_xmit |= VIRTIO_XDP_TX;
957                         rcu_read_unlock();
958                         goto xdp_xmit;
959                 case XDP_REDIRECT:
960                         stats->xdp_redirects++;
961                         err = xdp_do_redirect(dev, &xdp, xdp_prog);
962                         if (err)
963                                 goto err_xdp;
964                         *xdp_xmit |= VIRTIO_XDP_REDIR;
965                         rcu_read_unlock();
966                         goto xdp_xmit;
967                 default:
968                         bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
969                         fallthrough;
970                 case XDP_ABORTED:
971                         trace_xdp_exception(vi->dev, xdp_prog, act);
972                         goto err_xdp;
973                 case XDP_DROP:
974                         goto err_xdp;
975                 }
976         }
977         rcu_read_unlock();
978
979 skip_xdp:
980         skb = build_skb(buf, buflen);
981         if (!skb)
982                 goto err;
983         skb_reserve(skb, headroom - delta);
984         skb_put(skb, len);
985         if (!xdp_prog) {
986                 buf += header_offset;
987                 memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
988         } /* keep zeroed vnet hdr since XDP is loaded */
989
990         if (metasize)
991                 skb_metadata_set(skb, metasize);
992
993         return skb;
994
995 err_xdp:
996         rcu_read_unlock();
997         stats->xdp_drops++;
998 err:
999         stats->drops++;
1000         put_page(page);
1001 xdp_xmit:
1002         return NULL;
1003 }
1004
1005 static struct sk_buff *receive_big(struct net_device *dev,
1006                                    struct virtnet_info *vi,
1007                                    struct receive_queue *rq,
1008                                    void *buf,
1009                                    unsigned int len,
1010                                    struct virtnet_rq_stats *stats)
1011 {
1012         struct page *page = buf;
1013         struct sk_buff *skb =
1014                 page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, 0);
1015
1016         stats->bytes += len - vi->hdr_len;
1017         if (unlikely(!skb))
1018                 goto err;
1019
1020         return skb;
1021
1022 err:
1023         stats->drops++;
1024         give_pages(rq, page);
1025         return NULL;
1026 }
1027
1028 /* Why not use xdp_build_skb_from_frame() ?
1029  * XDP core assumes that xdp frags are PAGE_SIZE in length, while in
1030  * virtio-net there are 2 points that do not match its requirements:
1031  *  1. The size of the prefilled buffer is not fixed before xdp is set.
1032  *  2. xdp_build_skb_from_frame() does more checks that we don't need,
1033  *     like eth_type_trans() (which virtio-net does in receive_buf()).
1034  */
1035 static struct sk_buff *build_skb_from_xdp_buff(struct net_device *dev,
1036                                                struct virtnet_info *vi,
1037                                                struct xdp_buff *xdp,
1038                                                unsigned int xdp_frags_truesz)
1039 {
1040         struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
1041         unsigned int headroom, data_len;
1042         struct sk_buff *skb;
1043         int metasize;
1044         u8 nr_frags;
1045
1046         if (unlikely(xdp->data_end > xdp_data_hard_end(xdp))) {
1047                 pr_debug("Error building skb as missing reserved tailroom for xdp");
1048                 return NULL;
1049         }
1050
1051         if (unlikely(xdp_buff_has_frags(xdp)))
1052                 nr_frags = sinfo->nr_frags;
1053
1054         skb = build_skb(xdp->data_hard_start, xdp->frame_sz);
1055         if (unlikely(!skb))
1056                 return NULL;
1057
1058         headroom = xdp->data - xdp->data_hard_start;
1059         data_len = xdp->data_end - xdp->data;
1060         skb_reserve(skb, headroom);
1061         __skb_put(skb, data_len);
1062
1063         metasize = xdp->data - xdp->data_meta;
1064         metasize = metasize > 0 ? metasize : 0;
1065         if (metasize)
1066                 skb_metadata_set(skb, metasize);
1067
1068         if (unlikely(xdp_buff_has_frags(xdp)))
1069                 xdp_update_skb_shared_info(skb, nr_frags,
1070                                            sinfo->xdp_frags_size,
1071                                            xdp_frags_truesz,
1072                                            xdp_buff_is_frag_pfmemalloc(xdp));
1073
1074         return skb;
1075 }
1076
1077 /* TODO: build xdp in big mode */
1078 static int virtnet_build_xdp_buff_mrg(struct net_device *dev,
1079                                       struct virtnet_info *vi,
1080                                       struct receive_queue *rq,
1081                                       struct xdp_buff *xdp,
1082                                       void *buf,
1083                                       unsigned int len,
1084                                       unsigned int frame_sz,
1085                                       int *num_buf,
1086                                       unsigned int *xdp_frags_truesize,
1087                                       struct virtnet_rq_stats *stats)
1088 {
1089         struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1090         unsigned int headroom, tailroom, room;
1091         unsigned int truesize, cur_frag_size;
1092         struct skb_shared_info *shinfo;
1093         unsigned int xdp_frags_truesz = 0;
1094         struct page *page;
1095         skb_frag_t *frag;
1096         int offset;
1097         void *ctx;
1098
1099         xdp_init_buff(xdp, frame_sz, &rq->xdp_rxq);
1100         xdp_prepare_buff(xdp, buf - VIRTIO_XDP_HEADROOM,
1101                          VIRTIO_XDP_HEADROOM + vi->hdr_len, len - vi->hdr_len, true);
1102
1103         if (!*num_buf)
1104                 return 0;
1105
1106         if (*num_buf > 1) {
1107                 /* If we want to build multi-buffer xdp, we need
1108                  * to specify that the flags of xdp_buff have the
1109                  * XDP_FLAGS_HAS_FRAG bit.
1110                  */
1111                 if (!xdp_buff_has_frags(xdp))
1112                         xdp_buff_set_frags_flag(xdp);
1113
1114                 shinfo = xdp_get_shared_info_from_buff(xdp);
1115                 shinfo->nr_frags = 0;
1116                 shinfo->xdp_frags_size = 0;
1117         }
1118
1119         if (*num_buf > MAX_SKB_FRAGS + 1)
1120                 return -EINVAL;
1121
1122         while (--*num_buf > 0) {
1123                 buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1124                 if (unlikely(!buf)) {
1125                         pr_debug("%s: rx error: %d buffers out of %d missing\n",
1126                                  dev->name, *num_buf,
1127                                  virtio16_to_cpu(vi->vdev, hdr->num_buffers));
1128                         dev->stats.rx_length_errors++;
1129                         return -EINVAL;
1130                 }
1131
1132                 stats->bytes += len;
1133                 page = virt_to_head_page(buf);
1134                 offset = buf - page_address(page);
1135
1136                 truesize = mergeable_ctx_to_truesize(ctx);
1137                 headroom = mergeable_ctx_to_headroom(ctx);
1138                 tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1139                 room = SKB_DATA_ALIGN(headroom + tailroom);
1140
1141                 cur_frag_size = truesize;
1142                 xdp_frags_truesz += cur_frag_size;
1143                 if (unlikely(len > truesize - room || cur_frag_size > PAGE_SIZE)) {
1144                         put_page(page);
1145                         pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1146                                  dev->name, len, (unsigned long)(truesize - room));
1147                         dev->stats.rx_length_errors++;
1148                         return -EINVAL;
1149                 }
1150
1151                 frag = &shinfo->frags[shinfo->nr_frags++];
1152                 __skb_frag_set_page(frag, page);
1153                 skb_frag_off_set(frag, offset);
1154                 skb_frag_size_set(frag, len);
1155                 if (page_is_pfmemalloc(page))
1156                         xdp_buff_set_frag_pfmemalloc(xdp);
1157
1158                 shinfo->xdp_frags_size += len;
1159         }
1160
1161         *xdp_frags_truesize = xdp_frags_truesz;
1162         return 0;
1163 }
1164
1165 static struct sk_buff *receive_mergeable(struct net_device *dev,
1166                                          struct virtnet_info *vi,
1167                                          struct receive_queue *rq,
1168                                          void *buf,
1169                                          void *ctx,
1170                                          unsigned int len,
1171                                          unsigned int *xdp_xmit,
1172                                          struct virtnet_rq_stats *stats)
1173 {
1174         struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1175         int num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
1176         struct page *page = virt_to_head_page(buf);
1177         int offset = buf - page_address(page);
1178         struct sk_buff *head_skb, *curr_skb;
1179         struct bpf_prog *xdp_prog;
1180         unsigned int truesize = mergeable_ctx_to_truesize(ctx);
1181         unsigned int headroom = mergeable_ctx_to_headroom(ctx);
1182         unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1183         unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1184         unsigned int frame_sz, xdp_room;
1185         int err;
1186
1187         head_skb = NULL;
1188         stats->bytes += len - vi->hdr_len;
1189
1190         if (unlikely(len > truesize - room)) {
1191                 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1192                          dev->name, len, (unsigned long)(truesize - room));
1193                 dev->stats.rx_length_errors++;
1194                 goto err_skb;
1195         }
1196
1197         if (likely(!vi->xdp_enabled)) {
1198                 xdp_prog = NULL;
1199                 goto skip_xdp;
1200         }
1201
1202         rcu_read_lock();
1203         xdp_prog = rcu_dereference(rq->xdp_prog);
1204         if (xdp_prog) {
1205                 unsigned int xdp_frags_truesz = 0;
1206                 struct skb_shared_info *shinfo;
1207                 struct xdp_frame *xdpf;
1208                 struct page *xdp_page;
1209                 struct xdp_buff xdp;
1210                 void *data;
1211                 u32 act;
1212                 int i;
1213
1214                 /* Transient failure which in theory could occur if
1215                  * in-flight packets from before XDP was enabled reach
1216                  * the receive path after XDP is loaded.
1217                  */
1218                 if (unlikely(hdr->hdr.gso_type))
1219                         goto err_xdp;
1220
1221                 /* Now XDP core assumes frag size is PAGE_SIZE, but buffers
1222                  * with headroom may add hole in truesize, which
1223                  * make their length exceed PAGE_SIZE. So we disabled the
1224                  * hole mechanism for xdp. See add_recvbuf_mergeable().
1225                  */
1226                 frame_sz = truesize;
1227
1228                 /* This happens when headroom is not enough because
1229                  * of the buffer was prefilled before XDP is set.
1230                  * This should only happen for the first several packets.
1231                  * In fact, vq reset can be used here to help us clean up
1232                  * the prefilled buffers, but many existing devices do not
1233                  * support it, and we don't want to bother users who are
1234                  * using xdp normally.
1235                  */
1236                 if (!xdp_prog->aux->xdp_has_frags &&
1237                     (num_buf > 1 || headroom < virtnet_get_headroom(vi))) {
1238                         /* linearize data for XDP */
1239                         xdp_page = xdp_linearize_page(rq, &num_buf,
1240                                                       page, offset,
1241                                                       VIRTIO_XDP_HEADROOM,
1242                                                       &len);
1243                         frame_sz = PAGE_SIZE;
1244
1245                         if (!xdp_page)
1246                                 goto err_xdp;
1247                         offset = VIRTIO_XDP_HEADROOM;
1248                 } else if (unlikely(headroom < virtnet_get_headroom(vi))) {
1249                         xdp_room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
1250                                                   sizeof(struct skb_shared_info));
1251                         if (len + xdp_room > PAGE_SIZE)
1252                                 goto err_xdp;
1253
1254                         xdp_page = alloc_page(GFP_ATOMIC);
1255                         if (!xdp_page)
1256                                 goto err_xdp;
1257
1258                         memcpy(page_address(xdp_page) + VIRTIO_XDP_HEADROOM,
1259                                page_address(page) + offset, len);
1260                         frame_sz = PAGE_SIZE;
1261                         offset = VIRTIO_XDP_HEADROOM;
1262                 } else {
1263                         xdp_page = page;
1264                 }
1265
1266                 data = page_address(xdp_page) + offset;
1267                 err = virtnet_build_xdp_buff_mrg(dev, vi, rq, &xdp, data, len, frame_sz,
1268                                                  &num_buf, &xdp_frags_truesz, stats);
1269                 if (unlikely(err))
1270                         goto err_xdp_frags;
1271
1272                 act = bpf_prog_run_xdp(xdp_prog, &xdp);
1273                 stats->xdp_packets++;
1274
1275                 switch (act) {
1276                 case XDP_PASS:
1277                         head_skb = build_skb_from_xdp_buff(dev, vi, &xdp, xdp_frags_truesz);
1278                         if (unlikely(!head_skb))
1279                                 goto err_xdp_frags;
1280
1281                         if (unlikely(xdp_page != page))
1282                                 put_page(page);
1283                         rcu_read_unlock();
1284                         return head_skb;
1285                 case XDP_TX:
1286                         stats->xdp_tx++;
1287                         xdpf = xdp_convert_buff_to_frame(&xdp);
1288                         if (unlikely(!xdpf)) {
1289                                 netdev_dbg(dev, "convert buff to frame failed for xdp\n");
1290                                 goto err_xdp_frags;
1291                         }
1292                         err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
1293                         if (unlikely(!err)) {
1294                                 xdp_return_frame_rx_napi(xdpf);
1295                         } else if (unlikely(err < 0)) {
1296                                 trace_xdp_exception(vi->dev, xdp_prog, act);
1297                                 goto err_xdp_frags;
1298                         }
1299                         *xdp_xmit |= VIRTIO_XDP_TX;
1300                         if (unlikely(xdp_page != page))
1301                                 put_page(page);
1302                         rcu_read_unlock();
1303                         goto xdp_xmit;
1304                 case XDP_REDIRECT:
1305                         stats->xdp_redirects++;
1306                         err = xdp_do_redirect(dev, &xdp, xdp_prog);
1307                         if (err)
1308                                 goto err_xdp_frags;
1309                         *xdp_xmit |= VIRTIO_XDP_REDIR;
1310                         if (unlikely(xdp_page != page))
1311                                 put_page(page);
1312                         rcu_read_unlock();
1313                         goto xdp_xmit;
1314                 default:
1315                         bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
1316                         fallthrough;
1317                 case XDP_ABORTED:
1318                         trace_xdp_exception(vi->dev, xdp_prog, act);
1319                         fallthrough;
1320                 case XDP_DROP:
1321                         goto err_xdp_frags;
1322                 }
1323 err_xdp_frags:
1324                 if (unlikely(xdp_page != page))
1325                         __free_pages(xdp_page, 0);
1326
1327                 if (xdp_buff_has_frags(&xdp)) {
1328                         shinfo = xdp_get_shared_info_from_buff(&xdp);
1329                         for (i = 0; i < shinfo->nr_frags; i++) {
1330                                 xdp_page = skb_frag_page(&shinfo->frags[i]);
1331                                 put_page(xdp_page);
1332                         }
1333                 }
1334
1335                 goto err_xdp;
1336         }
1337         rcu_read_unlock();
1338
1339 skip_xdp:
1340         head_skb = page_to_skb(vi, rq, page, offset, len, truesize, headroom);
1341         curr_skb = head_skb;
1342
1343         if (unlikely(!curr_skb))
1344                 goto err_skb;
1345         while (--num_buf) {
1346                 int num_skb_frags;
1347
1348                 buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1349                 if (unlikely(!buf)) {
1350                         pr_debug("%s: rx error: %d buffers out of %d missing\n",
1351                                  dev->name, num_buf,
1352                                  virtio16_to_cpu(vi->vdev,
1353                                                  hdr->num_buffers));
1354                         dev->stats.rx_length_errors++;
1355                         goto err_buf;
1356                 }
1357
1358                 stats->bytes += len;
1359                 page = virt_to_head_page(buf);
1360
1361                 truesize = mergeable_ctx_to_truesize(ctx);
1362                 headroom = mergeable_ctx_to_headroom(ctx);
1363                 tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1364                 room = SKB_DATA_ALIGN(headroom + tailroom);
1365                 if (unlikely(len > truesize - room)) {
1366                         pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1367                                  dev->name, len, (unsigned long)(truesize - room));
1368                         dev->stats.rx_length_errors++;
1369                         goto err_skb;
1370                 }
1371
1372                 num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1373                 if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1374                         struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1375
1376                         if (unlikely(!nskb))
1377                                 goto err_skb;
1378                         if (curr_skb == head_skb)
1379                                 skb_shinfo(curr_skb)->frag_list = nskb;
1380                         else
1381                                 curr_skb->next = nskb;
1382                         curr_skb = nskb;
1383                         head_skb->truesize += nskb->truesize;
1384                         num_skb_frags = 0;
1385                 }
1386                 if (curr_skb != head_skb) {
1387                         head_skb->data_len += len;
1388                         head_skb->len += len;
1389                         head_skb->truesize += truesize;
1390                 }
1391                 offset = buf - page_address(page);
1392                 if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1393                         put_page(page);
1394                         skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1395                                              len, truesize);
1396                 } else {
1397                         skb_add_rx_frag(curr_skb, num_skb_frags, page,
1398                                         offset, len, truesize);
1399                 }
1400         }
1401
1402         ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1403         return head_skb;
1404
1405 err_xdp:
1406         rcu_read_unlock();
1407         stats->xdp_drops++;
1408 err_skb:
1409         put_page(page);
1410         while (num_buf-- > 1) {
1411                 buf = virtqueue_get_buf(rq->vq, &len);
1412                 if (unlikely(!buf)) {
1413                         pr_debug("%s: rx error: %d buffers missing\n",
1414                                  dev->name, num_buf);
1415                         dev->stats.rx_length_errors++;
1416                         break;
1417                 }
1418                 stats->bytes += len;
1419                 page = virt_to_head_page(buf);
1420                 put_page(page);
1421         }
1422 err_buf:
1423         stats->drops++;
1424         dev_kfree_skb(head_skb);
1425 xdp_xmit:
1426         return NULL;
1427 }
1428
1429 static void virtio_skb_set_hash(const struct virtio_net_hdr_v1_hash *hdr_hash,
1430                                 struct sk_buff *skb)
1431 {
1432         enum pkt_hash_types rss_hash_type;
1433
1434         if (!hdr_hash || !skb)
1435                 return;
1436
1437         switch (__le16_to_cpu(hdr_hash->hash_report)) {
1438         case VIRTIO_NET_HASH_REPORT_TCPv4:
1439         case VIRTIO_NET_HASH_REPORT_UDPv4:
1440         case VIRTIO_NET_HASH_REPORT_TCPv6:
1441         case VIRTIO_NET_HASH_REPORT_UDPv6:
1442         case VIRTIO_NET_HASH_REPORT_TCPv6_EX:
1443         case VIRTIO_NET_HASH_REPORT_UDPv6_EX:
1444                 rss_hash_type = PKT_HASH_TYPE_L4;
1445                 break;
1446         case VIRTIO_NET_HASH_REPORT_IPv4:
1447         case VIRTIO_NET_HASH_REPORT_IPv6:
1448         case VIRTIO_NET_HASH_REPORT_IPv6_EX:
1449                 rss_hash_type = PKT_HASH_TYPE_L3;
1450                 break;
1451         case VIRTIO_NET_HASH_REPORT_NONE:
1452         default:
1453                 rss_hash_type = PKT_HASH_TYPE_NONE;
1454         }
1455         skb_set_hash(skb, __le32_to_cpu(hdr_hash->hash_value), rss_hash_type);
1456 }
1457
1458 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1459                         void *buf, unsigned int len, void **ctx,
1460                         unsigned int *xdp_xmit,
1461                         struct virtnet_rq_stats *stats)
1462 {
1463         struct net_device *dev = vi->dev;
1464         struct sk_buff *skb;
1465         struct virtio_net_hdr_mrg_rxbuf *hdr;
1466
1467         if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1468                 pr_debug("%s: short packet %i\n", dev->name, len);
1469                 dev->stats.rx_length_errors++;
1470                 virtnet_rq_free_unused_buf(rq->vq, buf);
1471                 return;
1472         }
1473
1474         if (vi->mergeable_rx_bufs)
1475                 skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1476                                         stats);
1477         else if (vi->big_packets)
1478                 skb = receive_big(dev, vi, rq, buf, len, stats);
1479         else
1480                 skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1481
1482         if (unlikely(!skb))
1483                 return;
1484
1485         hdr = skb_vnet_hdr(skb);
1486         if (dev->features & NETIF_F_RXHASH && vi->has_rss_hash_report)
1487                 virtio_skb_set_hash((const struct virtio_net_hdr_v1_hash *)hdr, skb);
1488
1489         if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
1490                 skb->ip_summed = CHECKSUM_UNNECESSARY;
1491
1492         if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1493                                   virtio_is_little_endian(vi->vdev))) {
1494                 net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1495                                      dev->name, hdr->hdr.gso_type,
1496                                      hdr->hdr.gso_size);
1497                 goto frame_err;
1498         }
1499
1500         skb_record_rx_queue(skb, vq2rxq(rq->vq));
1501         skb->protocol = eth_type_trans(skb, dev);
1502         pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1503                  ntohs(skb->protocol), skb->len, skb->pkt_type);
1504
1505         napi_gro_receive(&rq->napi, skb);
1506         return;
1507
1508 frame_err:
1509         dev->stats.rx_frame_errors++;
1510         dev_kfree_skb(skb);
1511 }
1512
1513 /* Unlike mergeable buffers, all buffers are allocated to the
1514  * same size, except for the headroom. For this reason we do
1515  * not need to use  mergeable_len_to_ctx here - it is enough
1516  * to store the headroom as the context ignoring the truesize.
1517  */
1518 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1519                              gfp_t gfp)
1520 {
1521         struct page_frag *alloc_frag = &rq->alloc_frag;
1522         char *buf;
1523         unsigned int xdp_headroom = virtnet_get_headroom(vi);
1524         void *ctx = (void *)(unsigned long)xdp_headroom;
1525         int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1526         int err;
1527
1528         len = SKB_DATA_ALIGN(len) +
1529               SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1530         if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
1531                 return -ENOMEM;
1532
1533         buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1534         get_page(alloc_frag->page);
1535         alloc_frag->offset += len;
1536         sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1537                     vi->hdr_len + GOOD_PACKET_LEN);
1538         err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1539         if (err < 0)
1540                 put_page(virt_to_head_page(buf));
1541         return err;
1542 }
1543
1544 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1545                            gfp_t gfp)
1546 {
1547         struct page *first, *list = NULL;
1548         char *p;
1549         int i, err, offset;
1550
1551         sg_init_table(rq->sg, vi->big_packets_num_skbfrags + 2);
1552
1553         /* page in rq->sg[vi->big_packets_num_skbfrags + 1] is list tail */
1554         for (i = vi->big_packets_num_skbfrags + 1; i > 1; --i) {
1555                 first = get_a_page(rq, gfp);
1556                 if (!first) {
1557                         if (list)
1558                                 give_pages(rq, list);
1559                         return -ENOMEM;
1560                 }
1561                 sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1562
1563                 /* chain new page in list head to match sg */
1564                 first->private = (unsigned long)list;
1565                 list = first;
1566         }
1567
1568         first = get_a_page(rq, gfp);
1569         if (!first) {
1570                 give_pages(rq, list);
1571                 return -ENOMEM;
1572         }
1573         p = page_address(first);
1574
1575         /* rq->sg[0], rq->sg[1] share the same page */
1576         /* a separated rq->sg[0] for header - required in case !any_header_sg */
1577         sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1578
1579         /* rq->sg[1] for data packet, from offset */
1580         offset = sizeof(struct padded_vnet_hdr);
1581         sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1582
1583         /* chain first in list head */
1584         first->private = (unsigned long)list;
1585         err = virtqueue_add_inbuf(rq->vq, rq->sg, vi->big_packets_num_skbfrags + 2,
1586                                   first, gfp);
1587         if (err < 0)
1588                 give_pages(rq, first);
1589
1590         return err;
1591 }
1592
1593 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1594                                           struct ewma_pkt_len *avg_pkt_len,
1595                                           unsigned int room)
1596 {
1597         struct virtnet_info *vi = rq->vq->vdev->priv;
1598         const size_t hdr_len = vi->hdr_len;
1599         unsigned int len;
1600
1601         if (room)
1602                 return PAGE_SIZE - room;
1603
1604         len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1605                                 rq->min_buf_len, PAGE_SIZE - hdr_len);
1606
1607         return ALIGN(len, L1_CACHE_BYTES);
1608 }
1609
1610 static int add_recvbuf_mergeable(struct virtnet_info *vi,
1611                                  struct receive_queue *rq, gfp_t gfp)
1612 {
1613         struct page_frag *alloc_frag = &rq->alloc_frag;
1614         unsigned int headroom = virtnet_get_headroom(vi);
1615         unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1616         unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1617         char *buf;
1618         void *ctx;
1619         int err;
1620         unsigned int len, hole;
1621
1622         /* Extra tailroom is needed to satisfy XDP's assumption. This
1623          * means rx frags coalescing won't work, but consider we've
1624          * disabled GSO for XDP, it won't be a big issue.
1625          */
1626         len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1627         if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
1628                 return -ENOMEM;
1629
1630         buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1631         buf += headroom; /* advance address leaving hole at front of pkt */
1632         get_page(alloc_frag->page);
1633         alloc_frag->offset += len + room;
1634         hole = alloc_frag->size - alloc_frag->offset;
1635         if (hole < len + room) {
1636                 /* To avoid internal fragmentation, if there is very likely not
1637                  * enough space for another buffer, add the remaining space to
1638                  * the current buffer.
1639                  * XDP core assumes that frame_size of xdp_buff and the length
1640                  * of the frag are PAGE_SIZE, so we disable the hole mechanism.
1641                  */
1642                 if (!headroom)
1643                         len += hole;
1644                 alloc_frag->offset += hole;
1645         }
1646
1647         sg_init_one(rq->sg, buf, len);
1648         ctx = mergeable_len_to_ctx(len + room, headroom);
1649         err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1650         if (err < 0)
1651                 put_page(virt_to_head_page(buf));
1652
1653         return err;
1654 }
1655
1656 /*
1657  * Returns false if we couldn't fill entirely (OOM).
1658  *
1659  * Normally run in the receive path, but can also be run from ndo_open
1660  * before we're receiving packets, or from refill_work which is
1661  * careful to disable receiving (using napi_disable).
1662  */
1663 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1664                           gfp_t gfp)
1665 {
1666         int err;
1667         bool oom;
1668
1669         do {
1670                 if (vi->mergeable_rx_bufs)
1671                         err = add_recvbuf_mergeable(vi, rq, gfp);
1672                 else if (vi->big_packets)
1673                         err = add_recvbuf_big(vi, rq, gfp);
1674                 else
1675                         err = add_recvbuf_small(vi, rq, gfp);
1676
1677                 oom = err == -ENOMEM;
1678                 if (err)
1679                         break;
1680         } while (rq->vq->num_free);
1681         if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
1682                 unsigned long flags;
1683
1684                 flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1685                 rq->stats.kicks++;
1686                 u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1687         }
1688
1689         return !oom;
1690 }
1691
1692 static void skb_recv_done(struct virtqueue *rvq)
1693 {
1694         struct virtnet_info *vi = rvq->vdev->priv;
1695         struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1696
1697         virtqueue_napi_schedule(&rq->napi, rvq);
1698 }
1699
1700 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
1701 {
1702         napi_enable(napi);
1703
1704         /* If all buffers were filled by other side before we napi_enabled, we
1705          * won't get another interrupt, so process any outstanding packets now.
1706          * Call local_bh_enable after to trigger softIRQ processing.
1707          */
1708         local_bh_disable();
1709         virtqueue_napi_schedule(napi, vq);
1710         local_bh_enable();
1711 }
1712
1713 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1714                                    struct virtqueue *vq,
1715                                    struct napi_struct *napi)
1716 {
1717         if (!napi->weight)
1718                 return;
1719
1720         /* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1721          * enable the feature if this is likely affine with the transmit path.
1722          */
1723         if (!vi->affinity_hint_set) {
1724                 napi->weight = 0;
1725                 return;
1726         }
1727
1728         return virtnet_napi_enable(vq, napi);
1729 }
1730
1731 static void virtnet_napi_tx_disable(struct napi_struct *napi)
1732 {
1733         if (napi->weight)
1734                 napi_disable(napi);
1735 }
1736
1737 static void refill_work(struct work_struct *work)
1738 {
1739         struct virtnet_info *vi =
1740                 container_of(work, struct virtnet_info, refill.work);
1741         bool still_empty;
1742         int i;
1743
1744         for (i = 0; i < vi->curr_queue_pairs; i++) {
1745                 struct receive_queue *rq = &vi->rq[i];
1746
1747                 napi_disable(&rq->napi);
1748                 still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1749                 virtnet_napi_enable(rq->vq, &rq->napi);
1750
1751                 /* In theory, this can happen: if we don't get any buffers in
1752                  * we will *never* try to fill again.
1753                  */
1754                 if (still_empty)
1755                         schedule_delayed_work(&vi->refill, HZ/2);
1756         }
1757 }
1758
1759 static int virtnet_receive(struct receive_queue *rq, int budget,
1760                            unsigned int *xdp_xmit)
1761 {
1762         struct virtnet_info *vi = rq->vq->vdev->priv;
1763         struct virtnet_rq_stats stats = {};
1764         unsigned int len;
1765         void *buf;
1766         int i;
1767
1768         if (!vi->big_packets || vi->mergeable_rx_bufs) {
1769                 void *ctx;
1770
1771                 while (stats.packets < budget &&
1772                        (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1773                         receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1774                         stats.packets++;
1775                 }
1776         } else {
1777                 while (stats.packets < budget &&
1778                        (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1779                         receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1780                         stats.packets++;
1781                 }
1782         }
1783
1784         if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1785                 if (!try_fill_recv(vi, rq, GFP_ATOMIC)) {
1786                         spin_lock(&vi->refill_lock);
1787                         if (vi->refill_enabled)
1788                                 schedule_delayed_work(&vi->refill, 0);
1789                         spin_unlock(&vi->refill_lock);
1790                 }
1791         }
1792
1793         u64_stats_update_begin(&rq->stats.syncp);
1794         for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1795                 size_t offset = virtnet_rq_stats_desc[i].offset;
1796                 u64 *item;
1797
1798                 item = (u64 *)((u8 *)&rq->stats + offset);
1799                 *item += *(u64 *)((u8 *)&stats + offset);
1800         }
1801         u64_stats_update_end(&rq->stats.syncp);
1802
1803         return stats.packets;
1804 }
1805
1806 static void virtnet_poll_cleantx(struct receive_queue *rq)
1807 {
1808         struct virtnet_info *vi = rq->vq->vdev->priv;
1809         unsigned int index = vq2rxq(rq->vq);
1810         struct send_queue *sq = &vi->sq[index];
1811         struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
1812
1813         if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
1814                 return;
1815
1816         if (__netif_tx_trylock(txq)) {
1817                 if (sq->reset) {
1818                         __netif_tx_unlock(txq);
1819                         return;
1820                 }
1821
1822                 do {
1823                         virtqueue_disable_cb(sq->vq);
1824                         free_old_xmit_skbs(sq, true);
1825                 } while (unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1826
1827                 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1828                         netif_tx_wake_queue(txq);
1829
1830                 __netif_tx_unlock(txq);
1831         }
1832 }
1833
1834 static int virtnet_poll(struct napi_struct *napi, int budget)
1835 {
1836         struct receive_queue *rq =
1837                 container_of(napi, struct receive_queue, napi);
1838         struct virtnet_info *vi = rq->vq->vdev->priv;
1839         struct send_queue *sq;
1840         unsigned int received;
1841         unsigned int xdp_xmit = 0;
1842
1843         virtnet_poll_cleantx(rq);
1844
1845         received = virtnet_receive(rq, budget, &xdp_xmit);
1846
1847         if (xdp_xmit & VIRTIO_XDP_REDIR)
1848                 xdp_do_flush();
1849
1850         /* Out of packets? */
1851         if (received < budget)
1852                 virtqueue_napi_complete(napi, rq->vq, received);
1853
1854         if (xdp_xmit & VIRTIO_XDP_TX) {
1855                 sq = virtnet_xdp_get_sq(vi);
1856                 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1857                         u64_stats_update_begin(&sq->stats.syncp);
1858                         sq->stats.kicks++;
1859                         u64_stats_update_end(&sq->stats.syncp);
1860                 }
1861                 virtnet_xdp_put_sq(vi, sq);
1862         }
1863
1864         return received;
1865 }
1866
1867 static int virtnet_open(struct net_device *dev)
1868 {
1869         struct virtnet_info *vi = netdev_priv(dev);
1870         int i, err;
1871
1872         enable_delayed_refill(vi);
1873
1874         for (i = 0; i < vi->max_queue_pairs; i++) {
1875                 if (i < vi->curr_queue_pairs)
1876                         /* Make sure we have some buffers: if oom use wq. */
1877                         if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1878                                 schedule_delayed_work(&vi->refill, 0);
1879
1880                 err = xdp_rxq_info_reg(&vi->rq[i].xdp_rxq, dev, i, vi->rq[i].napi.napi_id);
1881                 if (err < 0)
1882                         return err;
1883
1884                 err = xdp_rxq_info_reg_mem_model(&vi->rq[i].xdp_rxq,
1885                                                  MEM_TYPE_PAGE_SHARED, NULL);
1886                 if (err < 0) {
1887                         xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1888                         return err;
1889                 }
1890
1891                 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1892                 virtnet_napi_tx_enable(vi, vi->sq[i].vq, &vi->sq[i].napi);
1893         }
1894
1895         return 0;
1896 }
1897
1898 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1899 {
1900         struct send_queue *sq = container_of(napi, struct send_queue, napi);
1901         struct virtnet_info *vi = sq->vq->vdev->priv;
1902         unsigned int index = vq2txq(sq->vq);
1903         struct netdev_queue *txq;
1904         int opaque;
1905         bool done;
1906
1907         if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
1908                 /* We don't need to enable cb for XDP */
1909                 napi_complete_done(napi, 0);
1910                 return 0;
1911         }
1912
1913         txq = netdev_get_tx_queue(vi->dev, index);
1914         __netif_tx_lock(txq, raw_smp_processor_id());
1915         virtqueue_disable_cb(sq->vq);
1916         free_old_xmit_skbs(sq, true);
1917
1918         if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1919                 netif_tx_wake_queue(txq);
1920
1921         opaque = virtqueue_enable_cb_prepare(sq->vq);
1922
1923         done = napi_complete_done(napi, 0);
1924
1925         if (!done)
1926                 virtqueue_disable_cb(sq->vq);
1927
1928         __netif_tx_unlock(txq);
1929
1930         if (done) {
1931                 if (unlikely(virtqueue_poll(sq->vq, opaque))) {
1932                         if (napi_schedule_prep(napi)) {
1933                                 __netif_tx_lock(txq, raw_smp_processor_id());
1934                                 virtqueue_disable_cb(sq->vq);
1935                                 __netif_tx_unlock(txq);
1936                                 __napi_schedule(napi);
1937                         }
1938                 }
1939         }
1940
1941         return 0;
1942 }
1943
1944 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1945 {
1946         struct virtio_net_hdr_mrg_rxbuf *hdr;
1947         const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1948         struct virtnet_info *vi = sq->vq->vdev->priv;
1949         int num_sg;
1950         unsigned hdr_len = vi->hdr_len;
1951         bool can_push;
1952
1953         pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1954
1955         can_push = vi->any_header_sg &&
1956                 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1957                 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1958         /* Even if we can, don't push here yet as this would skew
1959          * csum_start offset below. */
1960         if (can_push)
1961                 hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1962         else
1963                 hdr = skb_vnet_hdr(skb);
1964
1965         if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1966                                     virtio_is_little_endian(vi->vdev), false,
1967                                     0))
1968                 return -EPROTO;
1969
1970         if (vi->mergeable_rx_bufs)
1971                 hdr->num_buffers = 0;
1972
1973         sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1974         if (can_push) {
1975                 __skb_push(skb, hdr_len);
1976                 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1977                 if (unlikely(num_sg < 0))
1978                         return num_sg;
1979                 /* Pull header back to avoid skew in tx bytes calculations. */
1980                 __skb_pull(skb, hdr_len);
1981         } else {
1982                 sg_set_buf(sq->sg, hdr, hdr_len);
1983                 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
1984                 if (unlikely(num_sg < 0))
1985                         return num_sg;
1986                 num_sg++;
1987         }
1988         return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1989 }
1990
1991 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1992 {
1993         struct virtnet_info *vi = netdev_priv(dev);
1994         int qnum = skb_get_queue_mapping(skb);
1995         struct send_queue *sq = &vi->sq[qnum];
1996         int err;
1997         struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1998         bool kick = !netdev_xmit_more();
1999         bool use_napi = sq->napi.weight;
2000
2001         /* Free up any pending old buffers before queueing new ones. */
2002         do {
2003                 if (use_napi)
2004                         virtqueue_disable_cb(sq->vq);
2005
2006                 free_old_xmit_skbs(sq, false);
2007
2008         } while (use_napi && kick &&
2009                unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
2010
2011         /* timestamp packet in software */
2012         skb_tx_timestamp(skb);
2013
2014         /* Try to transmit */
2015         err = xmit_skb(sq, skb);
2016
2017         /* This should not happen! */
2018         if (unlikely(err)) {
2019                 dev->stats.tx_fifo_errors++;
2020                 if (net_ratelimit())
2021                         dev_warn(&dev->dev,
2022                                  "Unexpected TXQ (%d) queue failure: %d\n",
2023                                  qnum, err);
2024                 dev->stats.tx_dropped++;
2025                 dev_kfree_skb_any(skb);
2026                 return NETDEV_TX_OK;
2027         }
2028
2029         /* Don't wait up for transmitted skbs to be freed. */
2030         if (!use_napi) {
2031                 skb_orphan(skb);
2032                 nf_reset_ct(skb);
2033         }
2034
2035         check_sq_full_and_disable(vi, dev, sq);
2036
2037         if (kick || netif_xmit_stopped(txq)) {
2038                 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
2039                         u64_stats_update_begin(&sq->stats.syncp);
2040                         sq->stats.kicks++;
2041                         u64_stats_update_end(&sq->stats.syncp);
2042                 }
2043         }
2044
2045         return NETDEV_TX_OK;
2046 }
2047
2048 static int virtnet_rx_resize(struct virtnet_info *vi,
2049                              struct receive_queue *rq, u32 ring_num)
2050 {
2051         bool running = netif_running(vi->dev);
2052         int err, qindex;
2053
2054         qindex = rq - vi->rq;
2055
2056         if (running)
2057                 napi_disable(&rq->napi);
2058
2059         err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_free_unused_buf);
2060         if (err)
2061                 netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
2062
2063         if (!try_fill_recv(vi, rq, GFP_KERNEL))
2064                 schedule_delayed_work(&vi->refill, 0);
2065
2066         if (running)
2067                 virtnet_napi_enable(rq->vq, &rq->napi);
2068         return err;
2069 }
2070
2071 static int virtnet_tx_resize(struct virtnet_info *vi,
2072                              struct send_queue *sq, u32 ring_num)
2073 {
2074         bool running = netif_running(vi->dev);
2075         struct netdev_queue *txq;
2076         int err, qindex;
2077
2078         qindex = sq - vi->sq;
2079
2080         if (running)
2081                 virtnet_napi_tx_disable(&sq->napi);
2082
2083         txq = netdev_get_tx_queue(vi->dev, qindex);
2084
2085         /* 1. wait all ximt complete
2086          * 2. fix the race of netif_stop_subqueue() vs netif_start_subqueue()
2087          */
2088         __netif_tx_lock_bh(txq);
2089
2090         /* Prevent rx poll from accessing sq. */
2091         sq->reset = true;
2092
2093         /* Prevent the upper layer from trying to send packets. */
2094         netif_stop_subqueue(vi->dev, qindex);
2095
2096         __netif_tx_unlock_bh(txq);
2097
2098         err = virtqueue_resize(sq->vq, ring_num, virtnet_sq_free_unused_buf);
2099         if (err)
2100                 netdev_err(vi->dev, "resize tx fail: tx queue index: %d err: %d\n", qindex, err);
2101
2102         __netif_tx_lock_bh(txq);
2103         sq->reset = false;
2104         netif_tx_wake_queue(txq);
2105         __netif_tx_unlock_bh(txq);
2106
2107         if (running)
2108                 virtnet_napi_tx_enable(vi, sq->vq, &sq->napi);
2109         return err;
2110 }
2111
2112 /*
2113  * Send command via the control virtqueue and check status.  Commands
2114  * supported by the hypervisor, as indicated by feature bits, should
2115  * never fail unless improperly formatted.
2116  */
2117 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
2118                                  struct scatterlist *out)
2119 {
2120         struct scatterlist *sgs[4], hdr, stat;
2121         unsigned out_num = 0, tmp;
2122         int ret;
2123
2124         /* Caller should know better */
2125         BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
2126
2127         vi->ctrl->status = ~0;
2128         vi->ctrl->hdr.class = class;
2129         vi->ctrl->hdr.cmd = cmd;
2130         /* Add header */
2131         sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
2132         sgs[out_num++] = &hdr;
2133
2134         if (out)
2135                 sgs[out_num++] = out;
2136
2137         /* Add return status. */
2138         sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
2139         sgs[out_num] = &stat;
2140
2141         BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
2142         ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
2143         if (ret < 0) {
2144                 dev_warn(&vi->vdev->dev,
2145                          "Failed to add sgs for command vq: %d\n.", ret);
2146                 return false;
2147         }
2148
2149         if (unlikely(!virtqueue_kick(vi->cvq)))
2150                 return vi->ctrl->status == VIRTIO_NET_OK;
2151
2152         /* Spin for a response, the kick causes an ioport write, trapping
2153          * into the hypervisor, so the request should be handled immediately.
2154          */
2155         while (!virtqueue_get_buf(vi->cvq, &tmp) &&
2156                !virtqueue_is_broken(vi->cvq))
2157                 cpu_relax();
2158
2159         return vi->ctrl->status == VIRTIO_NET_OK;
2160 }
2161
2162 static int virtnet_set_mac_address(struct net_device *dev, void *p)
2163 {
2164         struct virtnet_info *vi = netdev_priv(dev);
2165         struct virtio_device *vdev = vi->vdev;
2166         int ret;
2167         struct sockaddr *addr;
2168         struct scatterlist sg;
2169
2170         if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2171                 return -EOPNOTSUPP;
2172
2173         addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
2174         if (!addr)
2175                 return -ENOMEM;
2176
2177         ret = eth_prepare_mac_addr_change(dev, addr);
2178         if (ret)
2179                 goto out;
2180
2181         if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
2182                 sg_init_one(&sg, addr->sa_data, dev->addr_len);
2183                 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2184                                           VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
2185                         dev_warn(&vdev->dev,
2186                                  "Failed to set mac address by vq command.\n");
2187                         ret = -EINVAL;
2188                         goto out;
2189                 }
2190         } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
2191                    !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2192                 unsigned int i;
2193
2194                 /* Naturally, this has an atomicity problem. */
2195                 for (i = 0; i < dev->addr_len; i++)
2196                         virtio_cwrite8(vdev,
2197                                        offsetof(struct virtio_net_config, mac) +
2198                                        i, addr->sa_data[i]);
2199         }
2200
2201         eth_commit_mac_addr_change(dev, p);
2202         ret = 0;
2203
2204 out:
2205         kfree(addr);
2206         return ret;
2207 }
2208
2209 static void virtnet_stats(struct net_device *dev,
2210                           struct rtnl_link_stats64 *tot)
2211 {
2212         struct virtnet_info *vi = netdev_priv(dev);
2213         unsigned int start;
2214         int i;
2215
2216         for (i = 0; i < vi->max_queue_pairs; i++) {
2217                 u64 tpackets, tbytes, terrors, rpackets, rbytes, rdrops;
2218                 struct receive_queue *rq = &vi->rq[i];
2219                 struct send_queue *sq = &vi->sq[i];
2220
2221                 do {
2222                         start = u64_stats_fetch_begin(&sq->stats.syncp);
2223                         tpackets = sq->stats.packets;
2224                         tbytes   = sq->stats.bytes;
2225                         terrors  = sq->stats.tx_timeouts;
2226                 } while (u64_stats_fetch_retry(&sq->stats.syncp, start));
2227
2228                 do {
2229                         start = u64_stats_fetch_begin(&rq->stats.syncp);
2230                         rpackets = rq->stats.packets;
2231                         rbytes   = rq->stats.bytes;
2232                         rdrops   = rq->stats.drops;
2233                 } while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2234
2235                 tot->rx_packets += rpackets;
2236                 tot->tx_packets += tpackets;
2237                 tot->rx_bytes   += rbytes;
2238                 tot->tx_bytes   += tbytes;
2239                 tot->rx_dropped += rdrops;
2240                 tot->tx_errors  += terrors;
2241         }
2242
2243         tot->tx_dropped = dev->stats.tx_dropped;
2244         tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
2245         tot->rx_length_errors = dev->stats.rx_length_errors;
2246         tot->rx_frame_errors = dev->stats.rx_frame_errors;
2247 }
2248
2249 static void virtnet_ack_link_announce(struct virtnet_info *vi)
2250 {
2251         rtnl_lock();
2252         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
2253                                   VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
2254                 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
2255         rtnl_unlock();
2256 }
2257
2258 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2259 {
2260         struct scatterlist sg;
2261         struct net_device *dev = vi->dev;
2262
2263         if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
2264                 return 0;
2265
2266         vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
2267         sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
2268
2269         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2270                                   VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
2271                 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
2272                          queue_pairs);
2273                 return -EINVAL;
2274         } else {
2275                 vi->curr_queue_pairs = queue_pairs;
2276                 /* virtnet_open() will refill when device is going to up. */
2277                 if (dev->flags & IFF_UP)
2278                         schedule_delayed_work(&vi->refill, 0);
2279         }
2280
2281         return 0;
2282 }
2283
2284 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2285 {
2286         int err;
2287
2288         rtnl_lock();
2289         err = _virtnet_set_queues(vi, queue_pairs);
2290         rtnl_unlock();
2291         return err;
2292 }
2293
2294 static int virtnet_close(struct net_device *dev)
2295 {
2296         struct virtnet_info *vi = netdev_priv(dev);
2297         int i;
2298
2299         /* Make sure NAPI doesn't schedule refill work */
2300         disable_delayed_refill(vi);
2301         /* Make sure refill_work doesn't re-enable napi! */
2302         cancel_delayed_work_sync(&vi->refill);
2303
2304         for (i = 0; i < vi->max_queue_pairs; i++) {
2305                 virtnet_napi_tx_disable(&vi->sq[i].napi);
2306                 napi_disable(&vi->rq[i].napi);
2307                 xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
2308         }
2309
2310         return 0;
2311 }
2312
2313 static void virtnet_set_rx_mode(struct net_device *dev)
2314 {
2315         struct virtnet_info *vi = netdev_priv(dev);
2316         struct scatterlist sg[2];
2317         struct virtio_net_ctrl_mac *mac_data;
2318         struct netdev_hw_addr *ha;
2319         int uc_count;
2320         int mc_count;
2321         void *buf;
2322         int i;
2323
2324         /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
2325         if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
2326                 return;
2327
2328         vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
2329         vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
2330
2331         sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
2332
2333         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2334                                   VIRTIO_NET_CTRL_RX_PROMISC, sg))
2335                 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
2336                          vi->ctrl->promisc ? "en" : "dis");
2337
2338         sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
2339
2340         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2341                                   VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
2342                 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
2343                          vi->ctrl->allmulti ? "en" : "dis");
2344
2345         uc_count = netdev_uc_count(dev);
2346         mc_count = netdev_mc_count(dev);
2347         /* MAC filter - use one buffer for both lists */
2348         buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
2349                       (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
2350         mac_data = buf;
2351         if (!buf)
2352                 return;
2353
2354         sg_init_table(sg, 2);
2355
2356         /* Store the unicast list and count in the front of the buffer */
2357         mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2358         i = 0;
2359         netdev_for_each_uc_addr(ha, dev)
2360                 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2361
2362         sg_set_buf(&sg[0], mac_data,
2363                    sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2364
2365         /* multicast list and count fill the end */
2366         mac_data = (void *)&mac_data->macs[uc_count][0];
2367
2368         mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2369         i = 0;
2370         netdev_for_each_mc_addr(ha, dev)
2371                 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2372
2373         sg_set_buf(&sg[1], mac_data,
2374                    sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2375
2376         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2377                                   VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2378                 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2379
2380         kfree(buf);
2381 }
2382
2383 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
2384                                    __be16 proto, u16 vid)
2385 {
2386         struct virtnet_info *vi = netdev_priv(dev);
2387         struct scatterlist sg;
2388
2389         vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2390         sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2391
2392         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2393                                   VIRTIO_NET_CTRL_VLAN_ADD, &sg))
2394                 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
2395         return 0;
2396 }
2397
2398 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
2399                                     __be16 proto, u16 vid)
2400 {
2401         struct virtnet_info *vi = netdev_priv(dev);
2402         struct scatterlist sg;
2403
2404         vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2405         sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2406
2407         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2408                                   VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2409                 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2410         return 0;
2411 }
2412
2413 static void virtnet_clean_affinity(struct virtnet_info *vi)
2414 {
2415         int i;
2416
2417         if (vi->affinity_hint_set) {
2418                 for (i = 0; i < vi->max_queue_pairs; i++) {
2419                         virtqueue_set_affinity(vi->rq[i].vq, NULL);
2420                         virtqueue_set_affinity(vi->sq[i].vq, NULL);
2421                 }
2422
2423                 vi->affinity_hint_set = false;
2424         }
2425 }
2426
2427 static void virtnet_set_affinity(struct virtnet_info *vi)
2428 {
2429         cpumask_var_t mask;
2430         int stragglers;
2431         int group_size;
2432         int i, j, cpu;
2433         int num_cpu;
2434         int stride;
2435
2436         if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2437                 virtnet_clean_affinity(vi);
2438                 return;
2439         }
2440
2441         num_cpu = num_online_cpus();
2442         stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2443         stragglers = num_cpu >= vi->curr_queue_pairs ?
2444                         num_cpu % vi->curr_queue_pairs :
2445                         0;
2446         cpu = cpumask_first(cpu_online_mask);
2447
2448         for (i = 0; i < vi->curr_queue_pairs; i++) {
2449                 group_size = stride + (i < stragglers ? 1 : 0);
2450
2451                 for (j = 0; j < group_size; j++) {
2452                         cpumask_set_cpu(cpu, mask);
2453                         cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2454                                                 nr_cpu_ids, false);
2455                 }
2456                 virtqueue_set_affinity(vi->rq[i].vq, mask);
2457                 virtqueue_set_affinity(vi->sq[i].vq, mask);
2458                 __netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2459                 cpumask_clear(mask);
2460         }
2461
2462         vi->affinity_hint_set = true;
2463         free_cpumask_var(mask);
2464 }
2465
2466 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2467 {
2468         struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2469                                                    node);
2470         virtnet_set_affinity(vi);
2471         return 0;
2472 }
2473
2474 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2475 {
2476         struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2477                                                    node_dead);
2478         virtnet_set_affinity(vi);
2479         return 0;
2480 }
2481
2482 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2483 {
2484         struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2485                                                    node);
2486
2487         virtnet_clean_affinity(vi);
2488         return 0;
2489 }
2490
2491 static enum cpuhp_state virtionet_online;
2492
2493 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2494 {
2495         int ret;
2496
2497         ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2498         if (ret)
2499                 return ret;
2500         ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2501                                                &vi->node_dead);
2502         if (!ret)
2503                 return ret;
2504         cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2505         return ret;
2506 }
2507
2508 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2509 {
2510         cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2511         cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2512                                             &vi->node_dead);
2513 }
2514
2515 static void virtnet_get_ringparam(struct net_device *dev,
2516                                   struct ethtool_ringparam *ring,
2517                                   struct kernel_ethtool_ringparam *kernel_ring,
2518                                   struct netlink_ext_ack *extack)
2519 {
2520         struct virtnet_info *vi = netdev_priv(dev);
2521
2522         ring->rx_max_pending = vi->rq[0].vq->num_max;
2523         ring->tx_max_pending = vi->sq[0].vq->num_max;
2524         ring->rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2525         ring->tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2526 }
2527
2528 static int virtnet_set_ringparam(struct net_device *dev,
2529                                  struct ethtool_ringparam *ring,
2530                                  struct kernel_ethtool_ringparam *kernel_ring,
2531                                  struct netlink_ext_ack *extack)
2532 {
2533         struct virtnet_info *vi = netdev_priv(dev);
2534         u32 rx_pending, tx_pending;
2535         struct receive_queue *rq;
2536         struct send_queue *sq;
2537         int i, err;
2538
2539         if (ring->rx_mini_pending || ring->rx_jumbo_pending)
2540                 return -EINVAL;
2541
2542         rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2543         tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2544
2545         if (ring->rx_pending == rx_pending &&
2546             ring->tx_pending == tx_pending)
2547                 return 0;
2548
2549         if (ring->rx_pending > vi->rq[0].vq->num_max)
2550                 return -EINVAL;
2551
2552         if (ring->tx_pending > vi->sq[0].vq->num_max)
2553                 return -EINVAL;
2554
2555         for (i = 0; i < vi->max_queue_pairs; i++) {
2556                 rq = vi->rq + i;
2557                 sq = vi->sq + i;
2558
2559                 if (ring->tx_pending != tx_pending) {
2560                         err = virtnet_tx_resize(vi, sq, ring->tx_pending);
2561                         if (err)
2562                                 return err;
2563                 }
2564
2565                 if (ring->rx_pending != rx_pending) {
2566                         err = virtnet_rx_resize(vi, rq, ring->rx_pending);
2567                         if (err)
2568                                 return err;
2569                 }
2570         }
2571
2572         return 0;
2573 }
2574
2575 static bool virtnet_commit_rss_command(struct virtnet_info *vi)
2576 {
2577         struct net_device *dev = vi->dev;
2578         struct scatterlist sgs[4];
2579         unsigned int sg_buf_size;
2580
2581         /* prepare sgs */
2582         sg_init_table(sgs, 4);
2583
2584         sg_buf_size = offsetof(struct virtio_net_ctrl_rss, indirection_table);
2585         sg_set_buf(&sgs[0], &vi->ctrl->rss, sg_buf_size);
2586
2587         sg_buf_size = sizeof(uint16_t) * (vi->ctrl->rss.indirection_table_mask + 1);
2588         sg_set_buf(&sgs[1], vi->ctrl->rss.indirection_table, sg_buf_size);
2589
2590         sg_buf_size = offsetof(struct virtio_net_ctrl_rss, key)
2591                         - offsetof(struct virtio_net_ctrl_rss, max_tx_vq);
2592         sg_set_buf(&sgs[2], &vi->ctrl->rss.max_tx_vq, sg_buf_size);
2593
2594         sg_buf_size = vi->rss_key_size;
2595         sg_set_buf(&sgs[3], vi->ctrl->rss.key, sg_buf_size);
2596
2597         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2598                                   vi->has_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG
2599                                   : VIRTIO_NET_CTRL_MQ_HASH_CONFIG, sgs)) {
2600                 dev_warn(&dev->dev, "VIRTIONET issue with committing RSS sgs\n");
2601                 return false;
2602         }
2603         return true;
2604 }
2605
2606 static void virtnet_init_default_rss(struct virtnet_info *vi)
2607 {
2608         u32 indir_val = 0;
2609         int i = 0;
2610
2611         vi->ctrl->rss.hash_types = vi->rss_hash_types_supported;
2612         vi->rss_hash_types_saved = vi->rss_hash_types_supported;
2613         vi->ctrl->rss.indirection_table_mask = vi->rss_indir_table_size
2614                                                 ? vi->rss_indir_table_size - 1 : 0;
2615         vi->ctrl->rss.unclassified_queue = 0;
2616
2617         for (; i < vi->rss_indir_table_size; ++i) {
2618                 indir_val = ethtool_rxfh_indir_default(i, vi->curr_queue_pairs);
2619                 vi->ctrl->rss.indirection_table[i] = indir_val;
2620         }
2621
2622         vi->ctrl->rss.max_tx_vq = vi->curr_queue_pairs;
2623         vi->ctrl->rss.hash_key_length = vi->rss_key_size;
2624
2625         netdev_rss_key_fill(vi->ctrl->rss.key, vi->rss_key_size);
2626 }
2627
2628 static void virtnet_get_hashflow(const struct virtnet_info *vi, struct ethtool_rxnfc *info)
2629 {
2630         info->data = 0;
2631         switch (info->flow_type) {
2632         case TCP_V4_FLOW:
2633                 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
2634                         info->data = RXH_IP_SRC | RXH_IP_DST |
2635                                                  RXH_L4_B_0_1 | RXH_L4_B_2_3;
2636                 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2637                         info->data = RXH_IP_SRC | RXH_IP_DST;
2638                 }
2639                 break;
2640         case TCP_V6_FLOW:
2641                 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
2642                         info->data = RXH_IP_SRC | RXH_IP_DST |
2643                                                  RXH_L4_B_0_1 | RXH_L4_B_2_3;
2644                 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2645                         info->data = RXH_IP_SRC | RXH_IP_DST;
2646                 }
2647                 break;
2648         case UDP_V4_FLOW:
2649                 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
2650                         info->data = RXH_IP_SRC | RXH_IP_DST |
2651                                                  RXH_L4_B_0_1 | RXH_L4_B_2_3;
2652                 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2653                         info->data = RXH_IP_SRC | RXH_IP_DST;
2654                 }
2655                 break;
2656         case UDP_V6_FLOW:
2657                 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
2658                         info->data = RXH_IP_SRC | RXH_IP_DST |
2659                                                  RXH_L4_B_0_1 | RXH_L4_B_2_3;
2660                 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2661                         info->data = RXH_IP_SRC | RXH_IP_DST;
2662                 }
2663                 break;
2664         case IPV4_FLOW:
2665                 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4)
2666                         info->data = RXH_IP_SRC | RXH_IP_DST;
2667
2668                 break;
2669         case IPV6_FLOW:
2670                 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6)
2671                         info->data = RXH_IP_SRC | RXH_IP_DST;
2672
2673                 break;
2674         default:
2675                 info->data = 0;
2676                 break;
2677         }
2678 }
2679
2680 static bool virtnet_set_hashflow(struct virtnet_info *vi, struct ethtool_rxnfc *info)
2681 {
2682         u32 new_hashtypes = vi->rss_hash_types_saved;
2683         bool is_disable = info->data & RXH_DISCARD;
2684         bool is_l4 = info->data == (RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3);
2685
2686         /* supports only 'sd', 'sdfn' and 'r' */
2687         if (!((info->data == (RXH_IP_SRC | RXH_IP_DST)) | is_l4 | is_disable))
2688                 return false;
2689
2690         switch (info->flow_type) {
2691         case TCP_V4_FLOW:
2692                 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_TCPv4);
2693                 if (!is_disable)
2694                         new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2695                                 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0);
2696                 break;
2697         case UDP_V4_FLOW:
2698                 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_UDPv4);
2699                 if (!is_disable)
2700                         new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2701                                 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0);
2702                 break;
2703         case IPV4_FLOW:
2704                 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2705                 if (!is_disable)
2706                         new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2707                 break;
2708         case TCP_V6_FLOW:
2709                 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_TCPv6);
2710                 if (!is_disable)
2711                         new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2712                                 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0);
2713                 break;
2714         case UDP_V6_FLOW:
2715                 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_UDPv6);
2716                 if (!is_disable)
2717                         new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2718                                 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0);
2719                 break;
2720         case IPV6_FLOW:
2721                 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2722                 if (!is_disable)
2723                         new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2724                 break;
2725         default:
2726                 /* unsupported flow */
2727                 return false;
2728         }
2729
2730         /* if unsupported hashtype was set */
2731         if (new_hashtypes != (new_hashtypes & vi->rss_hash_types_supported))
2732                 return false;
2733
2734         if (new_hashtypes != vi->rss_hash_types_saved) {
2735                 vi->rss_hash_types_saved = new_hashtypes;
2736                 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
2737                 if (vi->dev->features & NETIF_F_RXHASH)
2738                         return virtnet_commit_rss_command(vi);
2739         }
2740
2741         return true;
2742 }
2743
2744 static void virtnet_get_drvinfo(struct net_device *dev,
2745                                 struct ethtool_drvinfo *info)
2746 {
2747         struct virtnet_info *vi = netdev_priv(dev);
2748         struct virtio_device *vdev = vi->vdev;
2749
2750         strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2751         strscpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2752         strscpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2753
2754 }
2755
2756 /* TODO: Eliminate OOO packets during switching */
2757 static int virtnet_set_channels(struct net_device *dev,
2758                                 struct ethtool_channels *channels)
2759 {
2760         struct virtnet_info *vi = netdev_priv(dev);
2761         u16 queue_pairs = channels->combined_count;
2762         int err;
2763
2764         /* We don't support separate rx/tx channels.
2765          * We don't allow setting 'other' channels.
2766          */
2767         if (channels->rx_count || channels->tx_count || channels->other_count)
2768                 return -EINVAL;
2769
2770         if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2771                 return -EINVAL;
2772
2773         /* For now we don't support modifying channels while XDP is loaded
2774          * also when XDP is loaded all RX queues have XDP programs so we only
2775          * need to check a single RX queue.
2776          */
2777         if (vi->rq[0].xdp_prog)
2778                 return -EINVAL;
2779
2780         cpus_read_lock();
2781         err = _virtnet_set_queues(vi, queue_pairs);
2782         if (err) {
2783                 cpus_read_unlock();
2784                 goto err;
2785         }
2786         virtnet_set_affinity(vi);
2787         cpus_read_unlock();
2788
2789         netif_set_real_num_tx_queues(dev, queue_pairs);
2790         netif_set_real_num_rx_queues(dev, queue_pairs);
2791  err:
2792         return err;
2793 }
2794
2795 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2796 {
2797         struct virtnet_info *vi = netdev_priv(dev);
2798         unsigned int i, j;
2799         u8 *p = data;
2800
2801         switch (stringset) {
2802         case ETH_SS_STATS:
2803                 for (i = 0; i < vi->curr_queue_pairs; i++) {
2804                         for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
2805                                 ethtool_sprintf(&p, "rx_queue_%u_%s", i,
2806                                                 virtnet_rq_stats_desc[j].desc);
2807                 }
2808
2809                 for (i = 0; i < vi->curr_queue_pairs; i++) {
2810                         for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
2811                                 ethtool_sprintf(&p, "tx_queue_%u_%s", i,
2812                                                 virtnet_sq_stats_desc[j].desc);
2813                 }
2814                 break;
2815         }
2816 }
2817
2818 static int virtnet_get_sset_count(struct net_device *dev, int sset)
2819 {
2820         struct virtnet_info *vi = netdev_priv(dev);
2821
2822         switch (sset) {
2823         case ETH_SS_STATS:
2824                 return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2825                                                VIRTNET_SQ_STATS_LEN);
2826         default:
2827                 return -EOPNOTSUPP;
2828         }
2829 }
2830
2831 static void virtnet_get_ethtool_stats(struct net_device *dev,
2832                                       struct ethtool_stats *stats, u64 *data)
2833 {
2834         struct virtnet_info *vi = netdev_priv(dev);
2835         unsigned int idx = 0, start, i, j;
2836         const u8 *stats_base;
2837         size_t offset;
2838
2839         for (i = 0; i < vi->curr_queue_pairs; i++) {
2840                 struct receive_queue *rq = &vi->rq[i];
2841
2842                 stats_base = (u8 *)&rq->stats;
2843                 do {
2844                         start = u64_stats_fetch_begin(&rq->stats.syncp);
2845                         for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2846                                 offset = virtnet_rq_stats_desc[j].offset;
2847                                 data[idx + j] = *(u64 *)(stats_base + offset);
2848                         }
2849                 } while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2850                 idx += VIRTNET_RQ_STATS_LEN;
2851         }
2852
2853         for (i = 0; i < vi->curr_queue_pairs; i++) {
2854                 struct send_queue *sq = &vi->sq[i];
2855
2856                 stats_base = (u8 *)&sq->stats;
2857                 do {
2858                         start = u64_stats_fetch_begin(&sq->stats.syncp);
2859                         for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2860                                 offset = virtnet_sq_stats_desc[j].offset;
2861                                 data[idx + j] = *(u64 *)(stats_base + offset);
2862                         }
2863                 } while (u64_stats_fetch_retry(&sq->stats.syncp, start));
2864                 idx += VIRTNET_SQ_STATS_LEN;
2865         }
2866 }
2867
2868 static void virtnet_get_channels(struct net_device *dev,
2869                                  struct ethtool_channels *channels)
2870 {
2871         struct virtnet_info *vi = netdev_priv(dev);
2872
2873         channels->combined_count = vi->curr_queue_pairs;
2874         channels->max_combined = vi->max_queue_pairs;
2875         channels->max_other = 0;
2876         channels->rx_count = 0;
2877         channels->tx_count = 0;
2878         channels->other_count = 0;
2879 }
2880
2881 static int virtnet_set_link_ksettings(struct net_device *dev,
2882                                       const struct ethtool_link_ksettings *cmd)
2883 {
2884         struct virtnet_info *vi = netdev_priv(dev);
2885
2886         return ethtool_virtdev_set_link_ksettings(dev, cmd,
2887                                                   &vi->speed, &vi->duplex);
2888 }
2889
2890 static int virtnet_get_link_ksettings(struct net_device *dev,
2891                                       struct ethtool_link_ksettings *cmd)
2892 {
2893         struct virtnet_info *vi = netdev_priv(dev);
2894
2895         cmd->base.speed = vi->speed;
2896         cmd->base.duplex = vi->duplex;
2897         cmd->base.port = PORT_OTHER;
2898
2899         return 0;
2900 }
2901
2902 static int virtnet_send_notf_coal_cmds(struct virtnet_info *vi,
2903                                        struct ethtool_coalesce *ec)
2904 {
2905         struct scatterlist sgs_tx, sgs_rx;
2906         struct virtio_net_ctrl_coal_tx coal_tx;
2907         struct virtio_net_ctrl_coal_rx coal_rx;
2908
2909         coal_tx.tx_usecs = cpu_to_le32(ec->tx_coalesce_usecs);
2910         coal_tx.tx_max_packets = cpu_to_le32(ec->tx_max_coalesced_frames);
2911         sg_init_one(&sgs_tx, &coal_tx, sizeof(coal_tx));
2912
2913         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2914                                   VIRTIO_NET_CTRL_NOTF_COAL_TX_SET,
2915                                   &sgs_tx))
2916                 return -EINVAL;
2917
2918         /* Save parameters */
2919         vi->tx_usecs = ec->tx_coalesce_usecs;
2920         vi->tx_max_packets = ec->tx_max_coalesced_frames;
2921
2922         coal_rx.rx_usecs = cpu_to_le32(ec->rx_coalesce_usecs);
2923         coal_rx.rx_max_packets = cpu_to_le32(ec->rx_max_coalesced_frames);
2924         sg_init_one(&sgs_rx, &coal_rx, sizeof(coal_rx));
2925
2926         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2927                                   VIRTIO_NET_CTRL_NOTF_COAL_RX_SET,
2928                                   &sgs_rx))
2929                 return -EINVAL;
2930
2931         /* Save parameters */
2932         vi->rx_usecs = ec->rx_coalesce_usecs;
2933         vi->rx_max_packets = ec->rx_max_coalesced_frames;
2934
2935         return 0;
2936 }
2937
2938 static int virtnet_coal_params_supported(struct ethtool_coalesce *ec)
2939 {
2940         /* usecs coalescing is supported only if VIRTIO_NET_F_NOTF_COAL
2941          * feature is negotiated.
2942          */
2943         if (ec->rx_coalesce_usecs || ec->tx_coalesce_usecs)
2944                 return -EOPNOTSUPP;
2945
2946         if (ec->tx_max_coalesced_frames > 1 ||
2947             ec->rx_max_coalesced_frames != 1)
2948                 return -EINVAL;
2949
2950         return 0;
2951 }
2952
2953 static int virtnet_set_coalesce(struct net_device *dev,
2954                                 struct ethtool_coalesce *ec,
2955                                 struct kernel_ethtool_coalesce *kernel_coal,
2956                                 struct netlink_ext_ack *extack)
2957 {
2958         struct virtnet_info *vi = netdev_priv(dev);
2959         int ret, i, napi_weight;
2960         bool update_napi = false;
2961
2962         /* Can't change NAPI weight if the link is up */
2963         napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
2964         if (napi_weight ^ vi->sq[0].napi.weight) {
2965                 if (dev->flags & IFF_UP)
2966                         return -EBUSY;
2967                 else
2968                         update_napi = true;
2969         }
2970
2971         if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL))
2972                 ret = virtnet_send_notf_coal_cmds(vi, ec);
2973         else
2974                 ret = virtnet_coal_params_supported(ec);
2975
2976         if (ret)
2977                 return ret;
2978
2979         if (update_napi) {
2980                 for (i = 0; i < vi->max_queue_pairs; i++)
2981                         vi->sq[i].napi.weight = napi_weight;
2982         }
2983
2984         return ret;
2985 }
2986
2987 static int virtnet_get_coalesce(struct net_device *dev,
2988                                 struct ethtool_coalesce *ec,
2989                                 struct kernel_ethtool_coalesce *kernel_coal,
2990                                 struct netlink_ext_ack *extack)
2991 {
2992         struct virtnet_info *vi = netdev_priv(dev);
2993
2994         if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
2995                 ec->rx_coalesce_usecs = vi->rx_usecs;
2996                 ec->tx_coalesce_usecs = vi->tx_usecs;
2997                 ec->tx_max_coalesced_frames = vi->tx_max_packets;
2998                 ec->rx_max_coalesced_frames = vi->rx_max_packets;
2999         } else {
3000                 ec->rx_max_coalesced_frames = 1;
3001
3002                 if (vi->sq[0].napi.weight)
3003                         ec->tx_max_coalesced_frames = 1;
3004         }
3005
3006         return 0;
3007 }
3008
3009 static void virtnet_init_settings(struct net_device *dev)
3010 {
3011         struct virtnet_info *vi = netdev_priv(dev);
3012
3013         vi->speed = SPEED_UNKNOWN;
3014         vi->duplex = DUPLEX_UNKNOWN;
3015 }
3016
3017 static void virtnet_update_settings(struct virtnet_info *vi)
3018 {
3019         u32 speed;
3020         u8 duplex;
3021
3022         if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
3023                 return;
3024
3025         virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
3026
3027         if (ethtool_validate_speed(speed))
3028                 vi->speed = speed;
3029
3030         virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
3031
3032         if (ethtool_validate_duplex(duplex))
3033                 vi->duplex = duplex;
3034 }
3035
3036 static u32 virtnet_get_rxfh_key_size(struct net_device *dev)
3037 {
3038         return ((struct virtnet_info *)netdev_priv(dev))->rss_key_size;
3039 }
3040
3041 static u32 virtnet_get_rxfh_indir_size(struct net_device *dev)
3042 {
3043         return ((struct virtnet_info *)netdev_priv(dev))->rss_indir_table_size;
3044 }
3045
3046 static int virtnet_get_rxfh(struct net_device *dev, u32 *indir, u8 *key, u8 *hfunc)
3047 {
3048         struct virtnet_info *vi = netdev_priv(dev);
3049         int i;
3050
3051         if (indir) {
3052                 for (i = 0; i < vi->rss_indir_table_size; ++i)
3053                         indir[i] = vi->ctrl->rss.indirection_table[i];
3054         }
3055
3056         if (key)
3057                 memcpy(key, vi->ctrl->rss.key, vi->rss_key_size);
3058
3059         if (hfunc)
3060                 *hfunc = ETH_RSS_HASH_TOP;
3061
3062         return 0;
3063 }
3064
3065 static int virtnet_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key, const u8 hfunc)
3066 {
3067         struct virtnet_info *vi = netdev_priv(dev);
3068         int i;
3069
3070         if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
3071                 return -EOPNOTSUPP;
3072
3073         if (indir) {
3074                 for (i = 0; i < vi->rss_indir_table_size; ++i)
3075                         vi->ctrl->rss.indirection_table[i] = indir[i];
3076         }
3077         if (key)
3078                 memcpy(vi->ctrl->rss.key, key, vi->rss_key_size);
3079
3080         virtnet_commit_rss_command(vi);
3081
3082         return 0;
3083 }
3084
3085 static int virtnet_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rule_locs)
3086 {
3087         struct virtnet_info *vi = netdev_priv(dev);
3088         int rc = 0;
3089
3090         switch (info->cmd) {
3091         case ETHTOOL_GRXRINGS:
3092                 info->data = vi->curr_queue_pairs;
3093                 break;
3094         case ETHTOOL_GRXFH:
3095                 virtnet_get_hashflow(vi, info);
3096                 break;
3097         default:
3098                 rc = -EOPNOTSUPP;
3099         }
3100
3101         return rc;
3102 }
3103
3104 static int virtnet_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info)
3105 {
3106         struct virtnet_info *vi = netdev_priv(dev);
3107         int rc = 0;
3108
3109         switch (info->cmd) {
3110         case ETHTOOL_SRXFH:
3111                 if (!virtnet_set_hashflow(vi, info))
3112                         rc = -EINVAL;
3113
3114                 break;
3115         default:
3116                 rc = -EOPNOTSUPP;
3117         }
3118
3119         return rc;
3120 }
3121
3122 static const struct ethtool_ops virtnet_ethtool_ops = {
3123         .supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES |
3124                 ETHTOOL_COALESCE_USECS,
3125         .get_drvinfo = virtnet_get_drvinfo,
3126         .get_link = ethtool_op_get_link,
3127         .get_ringparam = virtnet_get_ringparam,
3128         .set_ringparam = virtnet_set_ringparam,
3129         .get_strings = virtnet_get_strings,
3130         .get_sset_count = virtnet_get_sset_count,
3131         .get_ethtool_stats = virtnet_get_ethtool_stats,
3132         .set_channels = virtnet_set_channels,
3133         .get_channels = virtnet_get_channels,
3134         .get_ts_info = ethtool_op_get_ts_info,
3135         .get_link_ksettings = virtnet_get_link_ksettings,
3136         .set_link_ksettings = virtnet_set_link_ksettings,
3137         .set_coalesce = virtnet_set_coalesce,
3138         .get_coalesce = virtnet_get_coalesce,
3139         .get_rxfh_key_size = virtnet_get_rxfh_key_size,
3140         .get_rxfh_indir_size = virtnet_get_rxfh_indir_size,
3141         .get_rxfh = virtnet_get_rxfh,
3142         .set_rxfh = virtnet_set_rxfh,
3143         .get_rxnfc = virtnet_get_rxnfc,
3144         .set_rxnfc = virtnet_set_rxnfc,
3145 };
3146
3147 static void virtnet_freeze_down(struct virtio_device *vdev)
3148 {
3149         struct virtnet_info *vi = vdev->priv;
3150
3151         /* Make sure no work handler is accessing the device */
3152         flush_work(&vi->config_work);
3153
3154         netif_tx_lock_bh(vi->dev);
3155         netif_device_detach(vi->dev);
3156         netif_tx_unlock_bh(vi->dev);
3157         if (netif_running(vi->dev))
3158                 virtnet_close(vi->dev);
3159 }
3160
3161 static int init_vqs(struct virtnet_info *vi);
3162
3163 static int virtnet_restore_up(struct virtio_device *vdev)
3164 {
3165         struct virtnet_info *vi = vdev->priv;
3166         int err;
3167
3168         err = init_vqs(vi);
3169         if (err)
3170                 return err;
3171
3172         virtio_device_ready(vdev);
3173
3174         enable_delayed_refill(vi);
3175
3176         if (netif_running(vi->dev)) {
3177                 err = virtnet_open(vi->dev);
3178                 if (err)
3179                         return err;
3180         }
3181
3182         netif_tx_lock_bh(vi->dev);
3183         netif_device_attach(vi->dev);
3184         netif_tx_unlock_bh(vi->dev);
3185         return err;
3186 }
3187
3188 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
3189 {
3190         struct scatterlist sg;
3191         vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
3192
3193         sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
3194
3195         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
3196                                   VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
3197                 dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
3198                 return -EINVAL;
3199         }
3200
3201         return 0;
3202 }
3203
3204 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
3205 {
3206         u64 offloads = 0;
3207
3208         if (!vi->guest_offloads)
3209                 return 0;
3210
3211         return virtnet_set_guest_offloads(vi, offloads);
3212 }
3213
3214 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
3215 {
3216         u64 offloads = vi->guest_offloads;
3217
3218         if (!vi->guest_offloads)
3219                 return 0;
3220
3221         return virtnet_set_guest_offloads(vi, offloads);
3222 }
3223
3224 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
3225                            struct netlink_ext_ack *extack)
3226 {
3227         unsigned int room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
3228                                            sizeof(struct skb_shared_info));
3229         unsigned int max_sz = PAGE_SIZE - room - ETH_HLEN;
3230         struct virtnet_info *vi = netdev_priv(dev);
3231         struct bpf_prog *old_prog;
3232         u16 xdp_qp = 0, curr_qp;
3233         int i, err;
3234
3235         if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
3236             && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3237                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3238                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3239                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3240                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM) ||
3241                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) ||
3242                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6))) {
3243                 NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
3244                 return -EOPNOTSUPP;
3245         }
3246
3247         if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
3248                 NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
3249                 return -EINVAL;
3250         }
3251
3252         if (prog && !prog->aux->xdp_has_frags && dev->mtu > max_sz) {
3253                 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP without frags");
3254                 netdev_warn(dev, "single-buffer XDP requires MTU less than %u\n", max_sz);
3255                 return -EINVAL;
3256         }
3257
3258         curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
3259         if (prog)
3260                 xdp_qp = nr_cpu_ids;
3261
3262         /* XDP requires extra queues for XDP_TX */
3263         if (curr_qp + xdp_qp > vi->max_queue_pairs) {
3264                 netdev_warn_once(dev, "XDP request %i queues but max is %i. XDP_TX and XDP_REDIRECT will operate in a slower locked tx mode.\n",
3265                                  curr_qp + xdp_qp, vi->max_queue_pairs);
3266                 xdp_qp = 0;
3267         }
3268
3269         old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
3270         if (!prog && !old_prog)
3271                 return 0;
3272
3273         if (prog)
3274                 bpf_prog_add(prog, vi->max_queue_pairs - 1);
3275
3276         /* Make sure NAPI is not using any XDP TX queues for RX. */
3277         if (netif_running(dev)) {
3278                 for (i = 0; i < vi->max_queue_pairs; i++) {
3279                         napi_disable(&vi->rq[i].napi);
3280                         virtnet_napi_tx_disable(&vi->sq[i].napi);
3281                 }
3282         }
3283
3284         if (!prog) {
3285                 for (i = 0; i < vi->max_queue_pairs; i++) {
3286                         rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3287                         if (i == 0)
3288                                 virtnet_restore_guest_offloads(vi);
3289                 }
3290                 synchronize_net();
3291         }
3292
3293         err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
3294         if (err)
3295                 goto err;
3296         netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
3297         vi->xdp_queue_pairs = xdp_qp;
3298
3299         if (prog) {
3300                 vi->xdp_enabled = true;
3301                 for (i = 0; i < vi->max_queue_pairs; i++) {
3302                         rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3303                         if (i == 0 && !old_prog)
3304                                 virtnet_clear_guest_offloads(vi);
3305                 }
3306                 if (!old_prog)
3307                         xdp_features_set_redirect_target(dev, true);
3308         } else {
3309                 xdp_features_clear_redirect_target(dev);
3310                 vi->xdp_enabled = false;
3311         }
3312
3313         for (i = 0; i < vi->max_queue_pairs; i++) {
3314                 if (old_prog)
3315                         bpf_prog_put(old_prog);
3316                 if (netif_running(dev)) {
3317                         virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3318                         virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3319                                                &vi->sq[i].napi);
3320                 }
3321         }
3322
3323         return 0;
3324
3325 err:
3326         if (!prog) {
3327                 virtnet_clear_guest_offloads(vi);
3328                 for (i = 0; i < vi->max_queue_pairs; i++)
3329                         rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
3330         }
3331
3332         if (netif_running(dev)) {
3333                 for (i = 0; i < vi->max_queue_pairs; i++) {
3334                         virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3335                         virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3336                                                &vi->sq[i].napi);
3337                 }
3338         }
3339         if (prog)
3340                 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
3341         return err;
3342 }
3343
3344 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
3345 {
3346         switch (xdp->command) {
3347         case XDP_SETUP_PROG:
3348                 return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
3349         default:
3350                 return -EINVAL;
3351         }
3352 }
3353
3354 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
3355                                       size_t len)
3356 {
3357         struct virtnet_info *vi = netdev_priv(dev);
3358         int ret;
3359
3360         if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
3361                 return -EOPNOTSUPP;
3362
3363         ret = snprintf(buf, len, "sby");
3364         if (ret >= len)
3365                 return -EOPNOTSUPP;
3366
3367         return 0;
3368 }
3369
3370 static int virtnet_set_features(struct net_device *dev,
3371                                 netdev_features_t features)
3372 {
3373         struct virtnet_info *vi = netdev_priv(dev);
3374         u64 offloads;
3375         int err;
3376
3377         if ((dev->features ^ features) & NETIF_F_GRO_HW) {
3378                 if (vi->xdp_enabled)
3379                         return -EBUSY;
3380
3381                 if (features & NETIF_F_GRO_HW)
3382                         offloads = vi->guest_offloads_capable;
3383                 else
3384                         offloads = vi->guest_offloads_capable &
3385                                    ~GUEST_OFFLOAD_GRO_HW_MASK;
3386
3387                 err = virtnet_set_guest_offloads(vi, offloads);
3388                 if (err)
3389                         return err;
3390                 vi->guest_offloads = offloads;
3391         }
3392
3393         if ((dev->features ^ features) & NETIF_F_RXHASH) {
3394                 if (features & NETIF_F_RXHASH)
3395                         vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
3396                 else
3397                         vi->ctrl->rss.hash_types = VIRTIO_NET_HASH_REPORT_NONE;
3398
3399                 if (!virtnet_commit_rss_command(vi))
3400                         return -EINVAL;
3401         }
3402
3403         return 0;
3404 }
3405
3406 static void virtnet_tx_timeout(struct net_device *dev, unsigned int txqueue)
3407 {
3408         struct virtnet_info *priv = netdev_priv(dev);
3409         struct send_queue *sq = &priv->sq[txqueue];
3410         struct netdev_queue *txq = netdev_get_tx_queue(dev, txqueue);
3411
3412         u64_stats_update_begin(&sq->stats.syncp);
3413         sq->stats.tx_timeouts++;
3414         u64_stats_update_end(&sq->stats.syncp);
3415
3416         netdev_err(dev, "TX timeout on queue: %u, sq: %s, vq: 0x%x, name: %s, %u usecs ago\n",
3417                    txqueue, sq->name, sq->vq->index, sq->vq->name,
3418                    jiffies_to_usecs(jiffies - READ_ONCE(txq->trans_start)));
3419 }
3420
3421 static const struct net_device_ops virtnet_netdev = {
3422         .ndo_open            = virtnet_open,
3423         .ndo_stop            = virtnet_close,
3424         .ndo_start_xmit      = start_xmit,
3425         .ndo_validate_addr   = eth_validate_addr,
3426         .ndo_set_mac_address = virtnet_set_mac_address,
3427         .ndo_set_rx_mode     = virtnet_set_rx_mode,
3428         .ndo_get_stats64     = virtnet_stats,
3429         .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
3430         .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
3431         .ndo_bpf                = virtnet_xdp,
3432         .ndo_xdp_xmit           = virtnet_xdp_xmit,
3433         .ndo_features_check     = passthru_features_check,
3434         .ndo_get_phys_port_name = virtnet_get_phys_port_name,
3435         .ndo_set_features       = virtnet_set_features,
3436         .ndo_tx_timeout         = virtnet_tx_timeout,
3437 };
3438
3439 static void virtnet_config_changed_work(struct work_struct *work)
3440 {
3441         struct virtnet_info *vi =
3442                 container_of(work, struct virtnet_info, config_work);
3443         u16 v;
3444
3445         if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
3446                                  struct virtio_net_config, status, &v) < 0)
3447                 return;
3448
3449         if (v & VIRTIO_NET_S_ANNOUNCE) {
3450                 netdev_notify_peers(vi->dev);
3451                 virtnet_ack_link_announce(vi);
3452         }
3453
3454         /* Ignore unknown (future) status bits */
3455         v &= VIRTIO_NET_S_LINK_UP;
3456
3457         if (vi->status == v)
3458                 return;
3459
3460         vi->status = v;
3461
3462         if (vi->status & VIRTIO_NET_S_LINK_UP) {
3463                 virtnet_update_settings(vi);
3464                 netif_carrier_on(vi->dev);
3465                 netif_tx_wake_all_queues(vi->dev);
3466         } else {
3467                 netif_carrier_off(vi->dev);
3468                 netif_tx_stop_all_queues(vi->dev);
3469         }
3470 }
3471
3472 static void virtnet_config_changed(struct virtio_device *vdev)
3473 {
3474         struct virtnet_info *vi = vdev->priv;
3475
3476         schedule_work(&vi->config_work);
3477 }
3478
3479 static void virtnet_free_queues(struct virtnet_info *vi)
3480 {
3481         int i;
3482
3483         for (i = 0; i < vi->max_queue_pairs; i++) {
3484                 __netif_napi_del(&vi->rq[i].napi);
3485                 __netif_napi_del(&vi->sq[i].napi);
3486         }
3487
3488         /* We called __netif_napi_del(),
3489          * we need to respect an RCU grace period before freeing vi->rq
3490          */
3491         synchronize_net();
3492
3493         kfree(vi->rq);
3494         kfree(vi->sq);
3495         kfree(vi->ctrl);
3496 }
3497
3498 static void _free_receive_bufs(struct virtnet_info *vi)
3499 {
3500         struct bpf_prog *old_prog;
3501         int i;
3502
3503         for (i = 0; i < vi->max_queue_pairs; i++) {
3504                 while (vi->rq[i].pages)
3505                         __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
3506
3507                 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
3508                 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
3509                 if (old_prog)
3510                         bpf_prog_put(old_prog);
3511         }
3512 }
3513
3514 static void free_receive_bufs(struct virtnet_info *vi)
3515 {
3516         rtnl_lock();
3517         _free_receive_bufs(vi);
3518         rtnl_unlock();
3519 }
3520
3521 static void free_receive_page_frags(struct virtnet_info *vi)
3522 {
3523         int i;
3524         for (i = 0; i < vi->max_queue_pairs; i++)
3525                 if (vi->rq[i].alloc_frag.page)
3526                         put_page(vi->rq[i].alloc_frag.page);
3527 }
3528
3529 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf)
3530 {
3531         if (!is_xdp_frame(buf))
3532                 dev_kfree_skb(buf);
3533         else
3534                 xdp_return_frame(ptr_to_xdp(buf));
3535 }
3536
3537 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf)
3538 {
3539         struct virtnet_info *vi = vq->vdev->priv;
3540         int i = vq2rxq(vq);
3541
3542         if (vi->mergeable_rx_bufs)
3543                 put_page(virt_to_head_page(buf));
3544         else if (vi->big_packets)
3545                 give_pages(&vi->rq[i], buf);
3546         else
3547                 put_page(virt_to_head_page(buf));
3548 }
3549
3550 static void free_unused_bufs(struct virtnet_info *vi)
3551 {
3552         void *buf;
3553         int i;
3554
3555         for (i = 0; i < vi->max_queue_pairs; i++) {
3556                 struct virtqueue *vq = vi->sq[i].vq;
3557                 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3558                         virtnet_sq_free_unused_buf(vq, buf);
3559         }
3560
3561         for (i = 0; i < vi->max_queue_pairs; i++) {
3562                 struct virtqueue *vq = vi->rq[i].vq;
3563                 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3564                         virtnet_rq_free_unused_buf(vq, buf);
3565         }
3566 }
3567
3568 static void virtnet_del_vqs(struct virtnet_info *vi)
3569 {
3570         struct virtio_device *vdev = vi->vdev;
3571
3572         virtnet_clean_affinity(vi);
3573
3574         vdev->config->del_vqs(vdev);
3575
3576         virtnet_free_queues(vi);
3577 }
3578
3579 /* How large should a single buffer be so a queue full of these can fit at
3580  * least one full packet?
3581  * Logic below assumes the mergeable buffer header is used.
3582  */
3583 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
3584 {
3585         const unsigned int hdr_len = vi->hdr_len;
3586         unsigned int rq_size = virtqueue_get_vring_size(vq);
3587         unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
3588         unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
3589         unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
3590
3591         return max(max(min_buf_len, hdr_len) - hdr_len,
3592                    (unsigned int)GOOD_PACKET_LEN);
3593 }
3594
3595 static int virtnet_find_vqs(struct virtnet_info *vi)
3596 {
3597         vq_callback_t **callbacks;
3598         struct virtqueue **vqs;
3599         int ret = -ENOMEM;
3600         int i, total_vqs;
3601         const char **names;
3602         bool *ctx;
3603
3604         /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
3605          * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
3606          * possible control vq.
3607          */
3608         total_vqs = vi->max_queue_pairs * 2 +
3609                     virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
3610
3611         /* Allocate space for find_vqs parameters */
3612         vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
3613         if (!vqs)
3614                 goto err_vq;
3615         callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
3616         if (!callbacks)
3617                 goto err_callback;
3618         names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
3619         if (!names)
3620                 goto err_names;
3621         if (!vi->big_packets || vi->mergeable_rx_bufs) {
3622                 ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
3623                 if (!ctx)
3624                         goto err_ctx;
3625         } else {
3626                 ctx = NULL;
3627         }
3628
3629         /* Parameters for control virtqueue, if any */
3630         if (vi->has_cvq) {
3631                 callbacks[total_vqs - 1] = NULL;
3632                 names[total_vqs - 1] = "control";
3633         }
3634
3635         /* Allocate/initialize parameters for send/receive virtqueues */
3636         for (i = 0; i < vi->max_queue_pairs; i++) {
3637                 callbacks[rxq2vq(i)] = skb_recv_done;
3638                 callbacks[txq2vq(i)] = skb_xmit_done;
3639                 sprintf(vi->rq[i].name, "input.%d", i);
3640                 sprintf(vi->sq[i].name, "output.%d", i);
3641                 names[rxq2vq(i)] = vi->rq[i].name;
3642                 names[txq2vq(i)] = vi->sq[i].name;
3643                 if (ctx)
3644                         ctx[rxq2vq(i)] = true;
3645         }
3646
3647         ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
3648                                   names, ctx, NULL);
3649         if (ret)
3650                 goto err_find;
3651
3652         if (vi->has_cvq) {
3653                 vi->cvq = vqs[total_vqs - 1];
3654                 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
3655                         vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
3656         }
3657
3658         for (i = 0; i < vi->max_queue_pairs; i++) {
3659                 vi->rq[i].vq = vqs[rxq2vq(i)];
3660                 vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
3661                 vi->sq[i].vq = vqs[txq2vq(i)];
3662         }
3663
3664         /* run here: ret == 0. */
3665
3666
3667 err_find:
3668         kfree(ctx);
3669 err_ctx:
3670         kfree(names);
3671 err_names:
3672         kfree(callbacks);
3673 err_callback:
3674         kfree(vqs);
3675 err_vq:
3676         return ret;
3677 }
3678
3679 static int virtnet_alloc_queues(struct virtnet_info *vi)
3680 {
3681         int i;
3682
3683         if (vi->has_cvq) {
3684                 vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
3685                 if (!vi->ctrl)
3686                         goto err_ctrl;
3687         } else {
3688                 vi->ctrl = NULL;
3689         }
3690         vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
3691         if (!vi->sq)
3692                 goto err_sq;
3693         vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
3694         if (!vi->rq)
3695                 goto err_rq;
3696
3697         INIT_DELAYED_WORK(&vi->refill, refill_work);
3698         for (i = 0; i < vi->max_queue_pairs; i++) {
3699                 vi->rq[i].pages = NULL;
3700                 netif_napi_add_weight(vi->dev, &vi->rq[i].napi, virtnet_poll,
3701                                       napi_weight);
3702                 netif_napi_add_tx_weight(vi->dev, &vi->sq[i].napi,
3703                                          virtnet_poll_tx,
3704                                          napi_tx ? napi_weight : 0);
3705
3706                 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
3707                 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
3708                 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
3709
3710                 u64_stats_init(&vi->rq[i].stats.syncp);
3711                 u64_stats_init(&vi->sq[i].stats.syncp);
3712         }
3713
3714         return 0;
3715
3716 err_rq:
3717         kfree(vi->sq);
3718 err_sq:
3719         kfree(vi->ctrl);
3720 err_ctrl:
3721         return -ENOMEM;
3722 }
3723
3724 static int init_vqs(struct virtnet_info *vi)
3725 {
3726         int ret;
3727
3728         /* Allocate send & receive queues */
3729         ret = virtnet_alloc_queues(vi);
3730         if (ret)
3731                 goto err;
3732
3733         ret = virtnet_find_vqs(vi);
3734         if (ret)
3735                 goto err_free;
3736
3737         cpus_read_lock();
3738         virtnet_set_affinity(vi);
3739         cpus_read_unlock();
3740
3741         return 0;
3742
3743 err_free:
3744         virtnet_free_queues(vi);
3745 err:
3746         return ret;
3747 }
3748
3749 #ifdef CONFIG_SYSFS
3750 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
3751                 char *buf)
3752 {
3753         struct virtnet_info *vi = netdev_priv(queue->dev);
3754         unsigned int queue_index = get_netdev_rx_queue_index(queue);
3755         unsigned int headroom = virtnet_get_headroom(vi);
3756         unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
3757         struct ewma_pkt_len *avg;
3758
3759         BUG_ON(queue_index >= vi->max_queue_pairs);
3760         avg = &vi->rq[queue_index].mrg_avg_pkt_len;
3761         return sprintf(buf, "%u\n",
3762                        get_mergeable_buf_len(&vi->rq[queue_index], avg,
3763                                        SKB_DATA_ALIGN(headroom + tailroom)));
3764 }
3765
3766 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
3767         __ATTR_RO(mergeable_rx_buffer_size);
3768
3769 static struct attribute *virtio_net_mrg_rx_attrs[] = {
3770         &mergeable_rx_buffer_size_attribute.attr,
3771         NULL
3772 };
3773
3774 static const struct attribute_group virtio_net_mrg_rx_group = {
3775         .name = "virtio_net",
3776         .attrs = virtio_net_mrg_rx_attrs
3777 };
3778 #endif
3779
3780 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
3781                                     unsigned int fbit,
3782                                     const char *fname, const char *dname)
3783 {
3784         if (!virtio_has_feature(vdev, fbit))
3785                 return false;
3786
3787         dev_err(&vdev->dev, "device advertises feature %s but not %s",
3788                 fname, dname);
3789
3790         return true;
3791 }
3792
3793 #define VIRTNET_FAIL_ON(vdev, fbit, dbit)                       \
3794         virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
3795
3796 static bool virtnet_validate_features(struct virtio_device *vdev)
3797 {
3798         if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
3799             (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
3800                              "VIRTIO_NET_F_CTRL_VQ") ||
3801              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
3802                              "VIRTIO_NET_F_CTRL_VQ") ||
3803              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
3804                              "VIRTIO_NET_F_CTRL_VQ") ||
3805              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
3806              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
3807                              "VIRTIO_NET_F_CTRL_VQ") ||
3808              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_RSS,
3809                              "VIRTIO_NET_F_CTRL_VQ") ||
3810              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_HASH_REPORT,
3811                              "VIRTIO_NET_F_CTRL_VQ") ||
3812              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_NOTF_COAL,
3813                              "VIRTIO_NET_F_CTRL_VQ"))) {
3814                 return false;
3815         }
3816
3817         return true;
3818 }
3819
3820 #define MIN_MTU ETH_MIN_MTU
3821 #define MAX_MTU ETH_MAX_MTU
3822
3823 static int virtnet_validate(struct virtio_device *vdev)
3824 {
3825         if (!vdev->config->get) {
3826                 dev_err(&vdev->dev, "%s failure: config access disabled\n",
3827                         __func__);
3828                 return -EINVAL;
3829         }
3830
3831         if (!virtnet_validate_features(vdev))
3832                 return -EINVAL;
3833
3834         if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3835                 int mtu = virtio_cread16(vdev,
3836                                          offsetof(struct virtio_net_config,
3837                                                   mtu));
3838                 if (mtu < MIN_MTU)
3839                         __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3840         }
3841
3842         if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY) &&
3843             !virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3844                 dev_warn(&vdev->dev, "device advertises feature VIRTIO_NET_F_STANDBY but not VIRTIO_NET_F_MAC, disabling standby");
3845                 __virtio_clear_bit(vdev, VIRTIO_NET_F_STANDBY);
3846         }
3847
3848         return 0;
3849 }
3850
3851 static bool virtnet_check_guest_gso(const struct virtnet_info *vi)
3852 {
3853         return virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3854                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3855                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3856                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3857                 (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) &&
3858                 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6));
3859 }
3860
3861 static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu)
3862 {
3863         bool guest_gso = virtnet_check_guest_gso(vi);
3864
3865         /* If device can receive ANY guest GSO packets, regardless of mtu,
3866          * allocate packets of maximum size, otherwise limit it to only
3867          * mtu size worth only.
3868          */
3869         if (mtu > ETH_DATA_LEN || guest_gso) {
3870                 vi->big_packets = true;
3871                 vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE);
3872         }
3873 }
3874
3875 static int virtnet_probe(struct virtio_device *vdev)
3876 {
3877         int i, err = -ENOMEM;
3878         struct net_device *dev;
3879         struct virtnet_info *vi;
3880         u16 max_queue_pairs;
3881         int mtu = 0;
3882
3883         /* Find if host supports multiqueue/rss virtio_net device */
3884         max_queue_pairs = 1;
3885         if (virtio_has_feature(vdev, VIRTIO_NET_F_MQ) || virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3886                 max_queue_pairs =
3887                      virtio_cread16(vdev, offsetof(struct virtio_net_config, max_virtqueue_pairs));
3888
3889         /* We need at least 2 queue's */
3890         if (max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
3891             max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
3892             !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3893                 max_queue_pairs = 1;
3894
3895         /* Allocate ourselves a network device with room for our info */
3896         dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
3897         if (!dev)
3898                 return -ENOMEM;
3899
3900         /* Set up network device as normal. */
3901         dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
3902                            IFF_TX_SKB_NO_LINEAR;
3903         dev->netdev_ops = &virtnet_netdev;
3904         dev->features = NETIF_F_HIGHDMA;
3905
3906         dev->ethtool_ops = &virtnet_ethtool_ops;
3907         SET_NETDEV_DEV(dev, &vdev->dev);
3908
3909         /* Do we support "hardware" checksums? */
3910         if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
3911                 /* This opens up the world of extra features. */
3912                 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3913                 if (csum)
3914                         dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3915
3916                 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
3917                         dev->hw_features |= NETIF_F_TSO
3918                                 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
3919                 }
3920                 /* Individual feature bits: what can host handle? */
3921                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
3922                         dev->hw_features |= NETIF_F_TSO;
3923                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
3924                         dev->hw_features |= NETIF_F_TSO6;
3925                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
3926                         dev->hw_features |= NETIF_F_TSO_ECN;
3927                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_USO))
3928                         dev->hw_features |= NETIF_F_GSO_UDP_L4;
3929
3930                 dev->features |= NETIF_F_GSO_ROBUST;
3931
3932                 if (gso)
3933                         dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
3934                 /* (!csum && gso) case will be fixed by register_netdev() */
3935         }
3936         if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
3937                 dev->features |= NETIF_F_RXCSUM;
3938         if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3939             virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3940                 dev->features |= NETIF_F_GRO_HW;
3941         if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3942                 dev->hw_features |= NETIF_F_GRO_HW;
3943
3944         dev->vlan_features = dev->features;
3945         dev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT;
3946
3947         /* MTU range: 68 - 65535 */
3948         dev->min_mtu = MIN_MTU;
3949         dev->max_mtu = MAX_MTU;
3950
3951         /* Configuration may specify what MAC to use.  Otherwise random. */
3952         if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3953                 u8 addr[ETH_ALEN];
3954
3955                 virtio_cread_bytes(vdev,
3956                                    offsetof(struct virtio_net_config, mac),
3957                                    addr, ETH_ALEN);
3958                 eth_hw_addr_set(dev, addr);
3959         } else {
3960                 eth_hw_addr_random(dev);
3961                 dev_info(&vdev->dev, "Assigned random MAC address %pM\n",
3962                          dev->dev_addr);
3963         }
3964
3965         /* Set up our device-specific information */
3966         vi = netdev_priv(dev);
3967         vi->dev = dev;
3968         vi->vdev = vdev;
3969         vdev->priv = vi;
3970
3971         INIT_WORK(&vi->config_work, virtnet_config_changed_work);
3972         spin_lock_init(&vi->refill_lock);
3973
3974         if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) {
3975                 vi->mergeable_rx_bufs = true;
3976                 dev->xdp_features |= NETDEV_XDP_ACT_RX_SG;
3977         }
3978
3979         if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
3980                 vi->rx_usecs = 0;
3981                 vi->tx_usecs = 0;
3982                 vi->tx_max_packets = 0;
3983                 vi->rx_max_packets = 0;
3984         }
3985
3986         if (virtio_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT))
3987                 vi->has_rss_hash_report = true;
3988
3989         if (virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3990                 vi->has_rss = true;
3991
3992         if (vi->has_rss || vi->has_rss_hash_report) {
3993                 vi->rss_indir_table_size =
3994                         virtio_cread16(vdev, offsetof(struct virtio_net_config,
3995                                 rss_max_indirection_table_length));
3996                 vi->rss_key_size =
3997                         virtio_cread8(vdev, offsetof(struct virtio_net_config, rss_max_key_size));
3998
3999                 vi->rss_hash_types_supported =
4000                     virtio_cread32(vdev, offsetof(struct virtio_net_config, supported_hash_types));
4001                 vi->rss_hash_types_supported &=
4002                                 ~(VIRTIO_NET_RSS_HASH_TYPE_IP_EX |
4003                                   VIRTIO_NET_RSS_HASH_TYPE_TCP_EX |
4004                                   VIRTIO_NET_RSS_HASH_TYPE_UDP_EX);
4005
4006                 dev->hw_features |= NETIF_F_RXHASH;
4007         }
4008
4009         if (vi->has_rss_hash_report)
4010                 vi->hdr_len = sizeof(struct virtio_net_hdr_v1_hash);
4011         else if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
4012                  virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4013                 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
4014         else
4015                 vi->hdr_len = sizeof(struct virtio_net_hdr);
4016
4017         if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
4018             virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4019                 vi->any_header_sg = true;
4020
4021         if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
4022                 vi->has_cvq = true;
4023
4024         if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
4025                 mtu = virtio_cread16(vdev,
4026                                      offsetof(struct virtio_net_config,
4027                                               mtu));
4028                 if (mtu < dev->min_mtu) {
4029                         /* Should never trigger: MTU was previously validated
4030                          * in virtnet_validate.
4031                          */
4032                         dev_err(&vdev->dev,
4033                                 "device MTU appears to have changed it is now %d < %d",
4034                                 mtu, dev->min_mtu);
4035                         err = -EINVAL;
4036                         goto free;
4037                 }
4038
4039                 dev->mtu = mtu;
4040                 dev->max_mtu = mtu;
4041         }
4042
4043         virtnet_set_big_packets(vi, mtu);
4044
4045         if (vi->any_header_sg)
4046                 dev->needed_headroom = vi->hdr_len;
4047
4048         /* Enable multiqueue by default */
4049         if (num_online_cpus() >= max_queue_pairs)
4050                 vi->curr_queue_pairs = max_queue_pairs;
4051         else
4052                 vi->curr_queue_pairs = num_online_cpus();
4053         vi->max_queue_pairs = max_queue_pairs;
4054
4055         /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
4056         err = init_vqs(vi);
4057         if (err)
4058                 goto free;
4059
4060 #ifdef CONFIG_SYSFS
4061         if (vi->mergeable_rx_bufs)
4062                 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
4063 #endif
4064         netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
4065         netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
4066
4067         virtnet_init_settings(dev);
4068
4069         if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
4070                 vi->failover = net_failover_create(vi->dev);
4071                 if (IS_ERR(vi->failover)) {
4072                         err = PTR_ERR(vi->failover);
4073                         goto free_vqs;
4074                 }
4075         }
4076
4077         if (vi->has_rss || vi->has_rss_hash_report)
4078                 virtnet_init_default_rss(vi);
4079
4080         /* serialize netdev register + virtio_device_ready() with ndo_open() */
4081         rtnl_lock();
4082
4083         err = register_netdevice(dev);
4084         if (err) {
4085                 pr_debug("virtio_net: registering device failed\n");
4086                 rtnl_unlock();
4087                 goto free_failover;
4088         }
4089
4090         virtio_device_ready(vdev);
4091
4092         /* a random MAC address has been assigned, notify the device.
4093          * We don't fail probe if VIRTIO_NET_F_CTRL_MAC_ADDR is not there
4094          * because many devices work fine without getting MAC explicitly
4095          */
4096         if (!virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
4097             virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
4098                 struct scatterlist sg;
4099
4100                 sg_init_one(&sg, dev->dev_addr, dev->addr_len);
4101                 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
4102                                           VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
4103                         pr_debug("virtio_net: setting MAC address failed\n");
4104                         rtnl_unlock();
4105                         err = -EINVAL;
4106                         goto free_unregister_netdev;
4107                 }
4108         }
4109
4110         rtnl_unlock();
4111
4112         err = virtnet_cpu_notif_add(vi);
4113         if (err) {
4114                 pr_debug("virtio_net: registering cpu notifier failed\n");
4115                 goto free_unregister_netdev;
4116         }
4117
4118         virtnet_set_queues(vi, vi->curr_queue_pairs);
4119
4120         /* Assume link up if device can't report link status,
4121            otherwise get link status from config. */
4122         netif_carrier_off(dev);
4123         if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
4124                 schedule_work(&vi->config_work);
4125         } else {
4126                 vi->status = VIRTIO_NET_S_LINK_UP;
4127                 virtnet_update_settings(vi);
4128                 netif_carrier_on(dev);
4129         }
4130
4131         for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
4132                 if (virtio_has_feature(vi->vdev, guest_offloads[i]))
4133                         set_bit(guest_offloads[i], &vi->guest_offloads);
4134         vi->guest_offloads_capable = vi->guest_offloads;
4135
4136         pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
4137                  dev->name, max_queue_pairs);
4138
4139         return 0;
4140
4141 free_unregister_netdev:
4142         unregister_netdev(dev);
4143 free_failover:
4144         net_failover_destroy(vi->failover);
4145 free_vqs:
4146         virtio_reset_device(vdev);
4147         cancel_delayed_work_sync(&vi->refill);
4148         free_receive_page_frags(vi);
4149         virtnet_del_vqs(vi);
4150 free:
4151         free_netdev(dev);
4152         return err;
4153 }
4154
4155 static void remove_vq_common(struct virtnet_info *vi)
4156 {
4157         virtio_reset_device(vi->vdev);
4158
4159         /* Free unused buffers in both send and recv, if any. */
4160         free_unused_bufs(vi);
4161
4162         free_receive_bufs(vi);
4163
4164         free_receive_page_frags(vi);
4165
4166         virtnet_del_vqs(vi);
4167 }
4168
4169 static void virtnet_remove(struct virtio_device *vdev)
4170 {
4171         struct virtnet_info *vi = vdev->priv;
4172
4173         virtnet_cpu_notif_remove(vi);
4174
4175         /* Make sure no work handler is accessing the device. */
4176         flush_work(&vi->config_work);
4177
4178         unregister_netdev(vi->dev);
4179
4180         net_failover_destroy(vi->failover);
4181
4182         remove_vq_common(vi);
4183
4184         free_netdev(vi->dev);
4185 }
4186
4187 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
4188 {
4189         struct virtnet_info *vi = vdev->priv;
4190
4191         virtnet_cpu_notif_remove(vi);
4192         virtnet_freeze_down(vdev);
4193         remove_vq_common(vi);
4194
4195         return 0;
4196 }
4197
4198 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
4199 {
4200         struct virtnet_info *vi = vdev->priv;
4201         int err;
4202
4203         err = virtnet_restore_up(vdev);
4204         if (err)
4205                 return err;
4206         virtnet_set_queues(vi, vi->curr_queue_pairs);
4207
4208         err = virtnet_cpu_notif_add(vi);
4209         if (err) {
4210                 virtnet_freeze_down(vdev);
4211                 remove_vq_common(vi);
4212                 return err;
4213         }
4214
4215         return 0;
4216 }
4217
4218 static struct virtio_device_id id_table[] = {
4219         { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
4220         { 0 },
4221 };
4222
4223 #define VIRTNET_FEATURES \
4224         VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
4225         VIRTIO_NET_F_MAC, \
4226         VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
4227         VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
4228         VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
4229         VIRTIO_NET_F_HOST_USO, VIRTIO_NET_F_GUEST_USO4, VIRTIO_NET_F_GUEST_USO6, \
4230         VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
4231         VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
4232         VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
4233         VIRTIO_NET_F_CTRL_MAC_ADDR, \
4234         VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
4235         VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY, \
4236         VIRTIO_NET_F_RSS, VIRTIO_NET_F_HASH_REPORT, VIRTIO_NET_F_NOTF_COAL, \
4237         VIRTIO_NET_F_GUEST_HDRLEN
4238
4239 static unsigned int features[] = {
4240         VIRTNET_FEATURES,
4241 };
4242
4243 static unsigned int features_legacy[] = {
4244         VIRTNET_FEATURES,
4245         VIRTIO_NET_F_GSO,
4246         VIRTIO_F_ANY_LAYOUT,
4247 };
4248
4249 static struct virtio_driver virtio_net_driver = {
4250         .feature_table = features,
4251         .feature_table_size = ARRAY_SIZE(features),
4252         .feature_table_legacy = features_legacy,
4253         .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
4254         .driver.name =  KBUILD_MODNAME,
4255         .driver.owner = THIS_MODULE,
4256         .id_table =     id_table,
4257         .validate =     virtnet_validate,
4258         .probe =        virtnet_probe,
4259         .remove =       virtnet_remove,
4260         .config_changed = virtnet_config_changed,
4261 #ifdef CONFIG_PM_SLEEP
4262         .freeze =       virtnet_freeze,
4263         .restore =      virtnet_restore,
4264 #endif
4265 };
4266
4267 static __init int virtio_net_driver_init(void)
4268 {
4269         int ret;
4270
4271         ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
4272                                       virtnet_cpu_online,
4273                                       virtnet_cpu_down_prep);
4274         if (ret < 0)
4275                 goto out;
4276         virtionet_online = ret;
4277         ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
4278                                       NULL, virtnet_cpu_dead);
4279         if (ret)
4280                 goto err_dead;
4281         ret = register_virtio_driver(&virtio_net_driver);
4282         if (ret)
4283                 goto err_virtio;
4284         return 0;
4285 err_virtio:
4286         cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4287 err_dead:
4288         cpuhp_remove_multi_state(virtionet_online);
4289 out:
4290         return ret;
4291 }
4292 module_init(virtio_net_driver_init);
4293
4294 static __exit void virtio_net_driver_exit(void)
4295 {
4296         unregister_virtio_driver(&virtio_net_driver);
4297         cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4298         cpuhp_remove_multi_state(virtionet_online);
4299 }
4300 module_exit(virtio_net_driver_exit);
4301
4302 MODULE_DEVICE_TABLE(virtio, id_table);
4303 MODULE_DESCRIPTION("Virtio network driver");
4304 MODULE_LICENSE("GPL");