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