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