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