Merge tag 'for-f2fs-4.11' of git://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk...
[sfrench/cifs-2.6.git] / drivers / net / virtio_net.c
1 /* A network driver using virtio.
2  *
3  * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, see <http://www.gnu.org/licenses/>.
17  */
18 //#define DEBUG
19 #include <linux/netdevice.h>
20 #include <linux/etherdevice.h>
21 #include <linux/ethtool.h>
22 #include <linux/module.h>
23 #include <linux/virtio.h>
24 #include <linux/virtio_net.h>
25 #include <linux/bpf.h>
26 #include <linux/bpf_trace.h>
27 #include <linux/scatterlist.h>
28 #include <linux/if_vlan.h>
29 #include <linux/slab.h>
30 #include <linux/cpu.h>
31 #include <linux/average.h>
32
33 static int napi_weight = NAPI_POLL_WEIGHT;
34 module_param(napi_weight, int, 0444);
35
36 static bool csum = true, gso = true;
37 module_param(csum, bool, 0444);
38 module_param(gso, bool, 0444);
39
40 /* FIXME: MTU in config. */
41 #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
42 #define GOOD_COPY_LEN   128
43
44 #define VIRTNET_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
45
46 /* Amount of XDP headroom to prepend to packets for use by xdp_adjust_head */
47 #define VIRTIO_XDP_HEADROOM 256
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, 1, 64)
55
56 /* With mergeable buffers we align buffer address and use the low bits to
57  * encode its true size. Buffer size is up to 1 page so we need to align to
58  * square root of page size to ensure we reserve enough bits to encode the true
59  * size.
60  */
61 #define MERGEABLE_BUFFER_MIN_ALIGN_SHIFT ((PAGE_SHIFT + 1) / 2)
62
63 /* Minimum alignment for mergeable packet buffers. */
64 #define MERGEABLE_BUFFER_ALIGN max(L1_CACHE_BYTES, \
65                                    1 << MERGEABLE_BUFFER_MIN_ALIGN_SHIFT)
66
67 #define VIRTNET_DRIVER_VERSION "1.0.0"
68
69 struct virtnet_stats {
70         struct u64_stats_sync tx_syncp;
71         struct u64_stats_sync rx_syncp;
72         u64 tx_bytes;
73         u64 tx_packets;
74
75         u64 rx_bytes;
76         u64 rx_packets;
77 };
78
79 /* Internal representation of a send virtqueue */
80 struct send_queue {
81         /* Virtqueue associated with this send _queue */
82         struct virtqueue *vq;
83
84         /* TX: fragments + linear part + virtio header */
85         struct scatterlist sg[MAX_SKB_FRAGS + 2];
86
87         /* Name of the send queue: output.$index */
88         char name[40];
89 };
90
91 /* Internal representation of a receive virtqueue */
92 struct receive_queue {
93         /* Virtqueue associated with this receive_queue */
94         struct virtqueue *vq;
95
96         struct napi_struct napi;
97
98         struct bpf_prog __rcu *xdp_prog;
99
100         /* Chain pages by the private ptr. */
101         struct page *pages;
102
103         /* Average packet length for mergeable receive buffers. */
104         struct ewma_pkt_len mrg_avg_pkt_len;
105
106         /* Page frag for packet buffer allocation. */
107         struct page_frag alloc_frag;
108
109         /* RX: fragments + linear part + virtio header */
110         struct scatterlist sg[MAX_SKB_FRAGS + 2];
111
112         /* Name of this receive queue: input.$index */
113         char name[40];
114 };
115
116 struct virtnet_info {
117         struct virtio_device *vdev;
118         struct virtqueue *cvq;
119         struct net_device *dev;
120         struct send_queue *sq;
121         struct receive_queue *rq;
122         unsigned int status;
123
124         /* Max # of queue pairs supported by the device */
125         u16 max_queue_pairs;
126
127         /* # of queue pairs currently used by the driver */
128         u16 curr_queue_pairs;
129
130         /* # of XDP queue pairs currently used by the driver */
131         u16 xdp_queue_pairs;
132
133         /* I like... big packets and I cannot lie! */
134         bool big_packets;
135
136         /* Host will merge rx buffers for big packets (shake it! shake it!) */
137         bool mergeable_rx_bufs;
138
139         /* Has control virtqueue */
140         bool has_cvq;
141
142         /* Host can handle any s/g split between our header and packet data */
143         bool any_header_sg;
144
145         /* Packet virtio header size */
146         u8 hdr_len;
147
148         /* Active statistics */
149         struct virtnet_stats __percpu *stats;
150
151         /* Work struct for refilling if we run low on memory. */
152         struct delayed_work refill;
153
154         /* Work struct for config space updates */
155         struct work_struct config_work;
156
157         /* Does the affinity hint is set for virtqueues? */
158         bool affinity_hint_set;
159
160         /* CPU hotplug instances for online & dead */
161         struct hlist_node node;
162         struct hlist_node node_dead;
163
164         /* Control VQ buffers: protected by the rtnl lock */
165         struct virtio_net_ctrl_hdr ctrl_hdr;
166         virtio_net_ctrl_ack ctrl_status;
167         struct virtio_net_ctrl_mq ctrl_mq;
168         u8 ctrl_promisc;
169         u8 ctrl_allmulti;
170         u16 ctrl_vid;
171
172         /* Ethtool settings */
173         u8 duplex;
174         u32 speed;
175 };
176
177 struct padded_vnet_hdr {
178         struct virtio_net_hdr_mrg_rxbuf hdr;
179         /*
180          * hdr is in a separate sg buffer, and data sg buffer shares same page
181          * with this header sg. This padding makes next sg 16 byte aligned
182          * after the header.
183          */
184         char padding[4];
185 };
186
187 /* Converting between virtqueue no. and kernel tx/rx queue no.
188  * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
189  */
190 static int vq2txq(struct virtqueue *vq)
191 {
192         return (vq->index - 1) / 2;
193 }
194
195 static int txq2vq(int txq)
196 {
197         return txq * 2 + 1;
198 }
199
200 static int vq2rxq(struct virtqueue *vq)
201 {
202         return vq->index / 2;
203 }
204
205 static int rxq2vq(int rxq)
206 {
207         return rxq * 2;
208 }
209
210 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
211 {
212         return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
213 }
214
215 /*
216  * private is used to chain pages for big packets, put the whole
217  * most recent used list in the beginning for reuse
218  */
219 static void give_pages(struct receive_queue *rq, struct page *page)
220 {
221         struct page *end;
222
223         /* Find end of list, sew whole thing into vi->rq.pages. */
224         for (end = page; end->private; end = (struct page *)end->private);
225         end->private = (unsigned long)rq->pages;
226         rq->pages = page;
227 }
228
229 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
230 {
231         struct page *p = rq->pages;
232
233         if (p) {
234                 rq->pages = (struct page *)p->private;
235                 /* clear private here, it is used to chain pages */
236                 p->private = 0;
237         } else
238                 p = alloc_page(gfp_mask);
239         return p;
240 }
241
242 static void skb_xmit_done(struct virtqueue *vq)
243 {
244         struct virtnet_info *vi = vq->vdev->priv;
245
246         /* Suppress further interrupts. */
247         virtqueue_disable_cb(vq);
248
249         /* We were probably waiting for more output buffers. */
250         netif_wake_subqueue(vi->dev, vq2txq(vq));
251 }
252
253 static unsigned int mergeable_ctx_to_buf_truesize(unsigned long mrg_ctx)
254 {
255         unsigned int truesize = mrg_ctx & (MERGEABLE_BUFFER_ALIGN - 1);
256         return (truesize + 1) * MERGEABLE_BUFFER_ALIGN;
257 }
258
259 static void *mergeable_ctx_to_buf_address(unsigned long mrg_ctx)
260 {
261         return (void *)(mrg_ctx & -MERGEABLE_BUFFER_ALIGN);
262
263 }
264
265 static unsigned long mergeable_buf_to_ctx(void *buf, unsigned int truesize)
266 {
267         unsigned int size = truesize / MERGEABLE_BUFFER_ALIGN;
268         return (unsigned long)buf | (size - 1);
269 }
270
271 /* Called from bottom half context */
272 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
273                                    struct receive_queue *rq,
274                                    struct page *page, unsigned int offset,
275                                    unsigned int len, unsigned int truesize)
276 {
277         struct sk_buff *skb;
278         struct virtio_net_hdr_mrg_rxbuf *hdr;
279         unsigned int copy, hdr_len, hdr_padded_len;
280         char *p;
281
282         p = page_address(page) + offset;
283
284         /* copy small packet so we can reuse these pages for small data */
285         skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
286         if (unlikely(!skb))
287                 return NULL;
288
289         hdr = skb_vnet_hdr(skb);
290
291         hdr_len = vi->hdr_len;
292         if (vi->mergeable_rx_bufs)
293                 hdr_padded_len = sizeof *hdr;
294         else
295                 hdr_padded_len = sizeof(struct padded_vnet_hdr);
296
297         memcpy(hdr, p, hdr_len);
298
299         len -= hdr_len;
300         offset += hdr_padded_len;
301         p += hdr_padded_len;
302
303         copy = len;
304         if (copy > skb_tailroom(skb))
305                 copy = skb_tailroom(skb);
306         memcpy(skb_put(skb, copy), p, copy);
307
308         len -= copy;
309         offset += copy;
310
311         if (vi->mergeable_rx_bufs) {
312                 if (len)
313                         skb_add_rx_frag(skb, 0, page, offset, len, truesize);
314                 else
315                         put_page(page);
316                 return skb;
317         }
318
319         /*
320          * Verify that we can indeed put this data into a skb.
321          * This is here to handle cases when the device erroneously
322          * tries to receive more than is possible. This is usually
323          * the case of a broken device.
324          */
325         if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
326                 net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
327                 dev_kfree_skb(skb);
328                 return NULL;
329         }
330         BUG_ON(offset >= PAGE_SIZE);
331         while (len) {
332                 unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
333                 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
334                                 frag_size, truesize);
335                 len -= frag_size;
336                 page = (struct page *)page->private;
337                 offset = 0;
338         }
339
340         if (page)
341                 give_pages(rq, page);
342
343         return skb;
344 }
345
346 static bool virtnet_xdp_xmit(struct virtnet_info *vi,
347                              struct receive_queue *rq,
348                              struct xdp_buff *xdp)
349 {
350         struct virtio_net_hdr_mrg_rxbuf *hdr;
351         unsigned int len;
352         struct send_queue *sq;
353         unsigned int qp;
354         void *xdp_sent;
355         int err;
356
357         qp = vi->curr_queue_pairs - vi->xdp_queue_pairs + smp_processor_id();
358         sq = &vi->sq[qp];
359
360         /* Free up any pending old buffers before queueing new ones. */
361         while ((xdp_sent = virtqueue_get_buf(sq->vq, &len)) != NULL) {
362                 struct page *sent_page = virt_to_head_page(xdp_sent);
363
364                 put_page(sent_page);
365         }
366
367         xdp->data -= vi->hdr_len;
368         /* Zero header and leave csum up to XDP layers */
369         hdr = xdp->data;
370         memset(hdr, 0, vi->hdr_len);
371
372         sg_init_one(sq->sg, xdp->data, xdp->data_end - xdp->data);
373
374         err = virtqueue_add_outbuf(sq->vq, sq->sg, 1, xdp->data, GFP_ATOMIC);
375         if (unlikely(err)) {
376                 struct page *page = virt_to_head_page(xdp->data);
377
378                 put_page(page);
379                 return false;
380         }
381
382         virtqueue_kick(sq->vq);
383         return true;
384 }
385
386 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
387 {
388         return vi->xdp_queue_pairs ? VIRTIO_XDP_HEADROOM : 0;
389 }
390
391 static struct sk_buff *receive_small(struct net_device *dev,
392                                      struct virtnet_info *vi,
393                                      struct receive_queue *rq,
394                                      void *buf, unsigned int len)
395 {
396         struct sk_buff *skb;
397         struct bpf_prog *xdp_prog;
398         unsigned int xdp_headroom = virtnet_get_headroom(vi);
399         unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
400         unsigned int headroom = vi->hdr_len + header_offset;
401         unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
402                               SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
403         unsigned int delta = 0;
404         len -= vi->hdr_len;
405
406         rcu_read_lock();
407         xdp_prog = rcu_dereference(rq->xdp_prog);
408         if (xdp_prog) {
409                 struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
410                 struct xdp_buff xdp;
411                 void *orig_data;
412                 u32 act;
413
414                 if (unlikely(hdr->hdr.gso_type || hdr->hdr.flags))
415                         goto err_xdp;
416
417                 xdp.data_hard_start = buf + VIRTNET_RX_PAD + vi->hdr_len;
418                 xdp.data = xdp.data_hard_start + xdp_headroom;
419                 xdp.data_end = xdp.data + len;
420                 orig_data = xdp.data;
421                 act = bpf_prog_run_xdp(xdp_prog, &xdp);
422
423                 switch (act) {
424                 case XDP_PASS:
425                         /* Recalculate length in case bpf program changed it */
426                         delta = orig_data - xdp.data;
427                         break;
428                 case XDP_TX:
429                         if (unlikely(!virtnet_xdp_xmit(vi, rq, &xdp)))
430                                 trace_xdp_exception(vi->dev, xdp_prog, act);
431                         rcu_read_unlock();
432                         goto xdp_xmit;
433                 default:
434                         bpf_warn_invalid_xdp_action(act);
435                 case XDP_ABORTED:
436                         trace_xdp_exception(vi->dev, xdp_prog, act);
437                 case XDP_DROP:
438                         goto err_xdp;
439                 }
440         }
441         rcu_read_unlock();
442
443         skb = build_skb(buf, buflen);
444         if (!skb) {
445                 put_page(virt_to_head_page(buf));
446                 goto err;
447         }
448         skb_reserve(skb, headroom - delta);
449         skb_put(skb, len + delta);
450         if (!delta) {
451                 buf += header_offset;
452                 memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
453         } /* keep zeroed vnet hdr since packet was changed by bpf */
454
455 err:
456         return skb;
457
458 err_xdp:
459         rcu_read_unlock();
460         dev->stats.rx_dropped++;
461         put_page(virt_to_head_page(buf));
462 xdp_xmit:
463         return NULL;
464 }
465
466 static struct sk_buff *receive_big(struct net_device *dev,
467                                    struct virtnet_info *vi,
468                                    struct receive_queue *rq,
469                                    void *buf,
470                                    unsigned int len)
471 {
472         struct page *page = buf;
473         struct sk_buff *skb = page_to_skb(vi, rq, page, 0, len, PAGE_SIZE);
474
475         if (unlikely(!skb))
476                 goto err;
477
478         return skb;
479
480 err:
481         dev->stats.rx_dropped++;
482         give_pages(rq, page);
483         return NULL;
484 }
485
486 /* The conditions to enable XDP should preclude the underlying device from
487  * sending packets across multiple buffers (num_buf > 1). However per spec
488  * it does not appear to be illegal to do so but rather just against convention.
489  * So in order to avoid making a system unresponsive the packets are pushed
490  * into a page and the XDP program is run. This will be extremely slow and we
491  * push a warning to the user to fix this as soon as possible. Fixing this may
492  * require resolving the underlying hardware to determine why multiple buffers
493  * are being received or simply loading the XDP program in the ingress stack
494  * after the skb is built because there is no advantage to running it here
495  * anymore.
496  */
497 static struct page *xdp_linearize_page(struct receive_queue *rq,
498                                        u16 *num_buf,
499                                        struct page *p,
500                                        int offset,
501                                        unsigned int *len)
502 {
503         struct page *page = alloc_page(GFP_ATOMIC);
504         unsigned int page_off = VIRTIO_XDP_HEADROOM;
505
506         if (!page)
507                 return NULL;
508
509         memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
510         page_off += *len;
511
512         while (--*num_buf) {
513                 unsigned int buflen;
514                 unsigned long ctx;
515                 void *buf;
516                 int off;
517
518                 ctx = (unsigned long)virtqueue_get_buf(rq->vq, &buflen);
519                 if (unlikely(!ctx))
520                         goto err_buf;
521
522                 buf = mergeable_ctx_to_buf_address(ctx);
523                 p = virt_to_head_page(buf);
524                 off = buf - page_address(p);
525
526                 /* guard against a misconfigured or uncooperative backend that
527                  * is sending packet larger than the MTU.
528                  */
529                 if ((page_off + buflen) > PAGE_SIZE) {
530                         put_page(p);
531                         goto err_buf;
532                 }
533
534                 memcpy(page_address(page) + page_off,
535                        page_address(p) + off, buflen);
536                 page_off += buflen;
537                 put_page(p);
538         }
539
540         /* Headroom does not contribute to packet length */
541         *len = page_off - VIRTIO_XDP_HEADROOM;
542         return page;
543 err_buf:
544         __free_pages(page, 0);
545         return NULL;
546 }
547
548 static struct sk_buff *receive_mergeable(struct net_device *dev,
549                                          struct virtnet_info *vi,
550                                          struct receive_queue *rq,
551                                          unsigned long ctx,
552                                          unsigned int len)
553 {
554         void *buf = mergeable_ctx_to_buf_address(ctx);
555         struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
556         u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
557         struct page *page = virt_to_head_page(buf);
558         int offset = buf - page_address(page);
559         struct sk_buff *head_skb, *curr_skb;
560         struct bpf_prog *xdp_prog;
561         unsigned int truesize;
562
563         head_skb = NULL;
564
565         rcu_read_lock();
566         xdp_prog = rcu_dereference(rq->xdp_prog);
567         if (xdp_prog) {
568                 struct page *xdp_page;
569                 struct xdp_buff xdp;
570                 void *data;
571                 u32 act;
572
573                 /* This happens when rx buffer size is underestimated */
574                 if (unlikely(num_buf > 1)) {
575                         /* linearize data for XDP */
576                         xdp_page = xdp_linearize_page(rq, &num_buf,
577                                                       page, offset, &len);
578                         if (!xdp_page)
579                                 goto err_xdp;
580                         offset = VIRTIO_XDP_HEADROOM;
581                 } else {
582                         xdp_page = page;
583                 }
584
585                 /* Transient failure which in theory could occur if
586                  * in-flight packets from before XDP was enabled reach
587                  * the receive path after XDP is loaded. In practice I
588                  * was not able to create this condition.
589                  */
590                 if (unlikely(hdr->hdr.gso_type))
591                         goto err_xdp;
592
593                 /* Allow consuming headroom but reserve enough space to push
594                  * the descriptor on if we get an XDP_TX return code.
595                  */
596                 data = page_address(xdp_page) + offset;
597                 xdp.data_hard_start = data - VIRTIO_XDP_HEADROOM + vi->hdr_len;
598                 xdp.data = data + vi->hdr_len;
599                 xdp.data_end = xdp.data + (len - vi->hdr_len);
600                 act = bpf_prog_run_xdp(xdp_prog, &xdp);
601
602                 switch (act) {
603                 case XDP_PASS:
604                         /* recalculate offset to account for any header
605                          * adjustments. Note other cases do not build an
606                          * skb and avoid using offset
607                          */
608                         offset = xdp.data -
609                                         page_address(xdp_page) - vi->hdr_len;
610
611                         /* We can only create skb based on xdp_page. */
612                         if (unlikely(xdp_page != page)) {
613                                 rcu_read_unlock();
614                                 put_page(page);
615                                 head_skb = page_to_skb(vi, rq, xdp_page,
616                                                        offset, len, PAGE_SIZE);
617                                 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, len);
618                                 return head_skb;
619                         }
620                         break;
621                 case XDP_TX:
622                         if (unlikely(!virtnet_xdp_xmit(vi, rq, &xdp)))
623                                 trace_xdp_exception(vi->dev, xdp_prog, act);
624                         ewma_pkt_len_add(&rq->mrg_avg_pkt_len, len);
625                         if (unlikely(xdp_page != page))
626                                 goto err_xdp;
627                         rcu_read_unlock();
628                         goto xdp_xmit;
629                 default:
630                         bpf_warn_invalid_xdp_action(act);
631                 case XDP_ABORTED:
632                         trace_xdp_exception(vi->dev, xdp_prog, act);
633                 case XDP_DROP:
634                         if (unlikely(xdp_page != page))
635                                 __free_pages(xdp_page, 0);
636                         ewma_pkt_len_add(&rq->mrg_avg_pkt_len, len);
637                         goto err_xdp;
638                 }
639         }
640         rcu_read_unlock();
641
642         truesize = max(len, mergeable_ctx_to_buf_truesize(ctx));
643         head_skb = page_to_skb(vi, rq, page, offset, len, truesize);
644         curr_skb = head_skb;
645
646         if (unlikely(!curr_skb))
647                 goto err_skb;
648         while (--num_buf) {
649                 int num_skb_frags;
650
651                 ctx = (unsigned long)virtqueue_get_buf(rq->vq, &len);
652                 if (unlikely(!ctx)) {
653                         pr_debug("%s: rx error: %d buffers out of %d missing\n",
654                                  dev->name, num_buf,
655                                  virtio16_to_cpu(vi->vdev,
656                                                  hdr->num_buffers));
657                         dev->stats.rx_length_errors++;
658                         goto err_buf;
659                 }
660
661                 buf = mergeable_ctx_to_buf_address(ctx);
662                 page = virt_to_head_page(buf);
663
664                 num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
665                 if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
666                         struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
667
668                         if (unlikely(!nskb))
669                                 goto err_skb;
670                         if (curr_skb == head_skb)
671                                 skb_shinfo(curr_skb)->frag_list = nskb;
672                         else
673                                 curr_skb->next = nskb;
674                         curr_skb = nskb;
675                         head_skb->truesize += nskb->truesize;
676                         num_skb_frags = 0;
677                 }
678                 truesize = max(len, mergeable_ctx_to_buf_truesize(ctx));
679                 if (curr_skb != head_skb) {
680                         head_skb->data_len += len;
681                         head_skb->len += len;
682                         head_skb->truesize += truesize;
683                 }
684                 offset = buf - page_address(page);
685                 if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
686                         put_page(page);
687                         skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
688                                              len, truesize);
689                 } else {
690                         skb_add_rx_frag(curr_skb, num_skb_frags, page,
691                                         offset, len, truesize);
692                 }
693         }
694
695         ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
696         return head_skb;
697
698 err_xdp:
699         rcu_read_unlock();
700 err_skb:
701         put_page(page);
702         while (--num_buf) {
703                 ctx = (unsigned long)virtqueue_get_buf(rq->vq, &len);
704                 if (unlikely(!ctx)) {
705                         pr_debug("%s: rx error: %d buffers missing\n",
706                                  dev->name, num_buf);
707                         dev->stats.rx_length_errors++;
708                         break;
709                 }
710                 page = virt_to_head_page(mergeable_ctx_to_buf_address(ctx));
711                 put_page(page);
712         }
713 err_buf:
714         dev->stats.rx_dropped++;
715         dev_kfree_skb(head_skb);
716 xdp_xmit:
717         return NULL;
718 }
719
720 static int receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
721                        void *buf, unsigned int len)
722 {
723         struct net_device *dev = vi->dev;
724         struct sk_buff *skb;
725         struct virtio_net_hdr_mrg_rxbuf *hdr;
726         int ret;
727
728         if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
729                 pr_debug("%s: short packet %i\n", dev->name, len);
730                 dev->stats.rx_length_errors++;
731                 if (vi->mergeable_rx_bufs) {
732                         unsigned long ctx = (unsigned long)buf;
733                         void *base = mergeable_ctx_to_buf_address(ctx);
734                         put_page(virt_to_head_page(base));
735                 } else if (vi->big_packets) {
736                         give_pages(rq, buf);
737                 } else {
738                         put_page(virt_to_head_page(buf));
739                 }
740                 return 0;
741         }
742
743         if (vi->mergeable_rx_bufs)
744                 skb = receive_mergeable(dev, vi, rq, (unsigned long)buf, len);
745         else if (vi->big_packets)
746                 skb = receive_big(dev, vi, rq, buf, len);
747         else
748                 skb = receive_small(dev, vi, rq, buf, len);
749
750         if (unlikely(!skb))
751                 return 0;
752
753         hdr = skb_vnet_hdr(skb);
754
755         ret = skb->len;
756
757         if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
758                 skb->ip_summed = CHECKSUM_UNNECESSARY;
759
760         if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
761                                   virtio_is_little_endian(vi->vdev))) {
762                 net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
763                                      dev->name, hdr->hdr.gso_type,
764                                      hdr->hdr.gso_size);
765                 goto frame_err;
766         }
767
768         skb->protocol = eth_type_trans(skb, dev);
769         pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
770                  ntohs(skb->protocol), skb->len, skb->pkt_type);
771
772         napi_gro_receive(&rq->napi, skb);
773         return ret;
774
775 frame_err:
776         dev->stats.rx_frame_errors++;
777         dev_kfree_skb(skb);
778         return 0;
779 }
780
781 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
782                              gfp_t gfp)
783 {
784         struct page_frag *alloc_frag = &rq->alloc_frag;
785         char *buf;
786         unsigned int xdp_headroom = virtnet_get_headroom(vi);
787         int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
788         int err;
789
790         len = SKB_DATA_ALIGN(len) +
791               SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
792         if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
793                 return -ENOMEM;
794
795         buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
796         get_page(alloc_frag->page);
797         alloc_frag->offset += len;
798         sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
799                     vi->hdr_len + GOOD_PACKET_LEN);
800         err = virtqueue_add_inbuf(rq->vq, rq->sg, 1, buf, gfp);
801         if (err < 0)
802                 put_page(virt_to_head_page(buf));
803
804         return err;
805 }
806
807 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
808                            gfp_t gfp)
809 {
810         struct page *first, *list = NULL;
811         char *p;
812         int i, err, offset;
813
814         sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
815
816         /* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
817         for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
818                 first = get_a_page(rq, gfp);
819                 if (!first) {
820                         if (list)
821                                 give_pages(rq, list);
822                         return -ENOMEM;
823                 }
824                 sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
825
826                 /* chain new page in list head to match sg */
827                 first->private = (unsigned long)list;
828                 list = first;
829         }
830
831         first = get_a_page(rq, gfp);
832         if (!first) {
833                 give_pages(rq, list);
834                 return -ENOMEM;
835         }
836         p = page_address(first);
837
838         /* rq->sg[0], rq->sg[1] share the same page */
839         /* a separated rq->sg[0] for header - required in case !any_header_sg */
840         sg_set_buf(&rq->sg[0], p, vi->hdr_len);
841
842         /* rq->sg[1] for data packet, from offset */
843         offset = sizeof(struct padded_vnet_hdr);
844         sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
845
846         /* chain first in list head */
847         first->private = (unsigned long)list;
848         err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
849                                   first, gfp);
850         if (err < 0)
851                 give_pages(rq, first);
852
853         return err;
854 }
855
856 static unsigned int get_mergeable_buf_len(struct ewma_pkt_len *avg_pkt_len)
857 {
858         const size_t hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
859         unsigned int len;
860
861         len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
862                         GOOD_PACKET_LEN, PAGE_SIZE - hdr_len);
863         return ALIGN(len, MERGEABLE_BUFFER_ALIGN);
864 }
865
866 static int add_recvbuf_mergeable(struct virtnet_info *vi,
867                                  struct receive_queue *rq, gfp_t gfp)
868 {
869         struct page_frag *alloc_frag = &rq->alloc_frag;
870         unsigned int headroom = virtnet_get_headroom(vi);
871         char *buf;
872         unsigned long ctx;
873         int err;
874         unsigned int len, hole;
875
876         len = get_mergeable_buf_len(&rq->mrg_avg_pkt_len);
877         if (unlikely(!skb_page_frag_refill(len + headroom, alloc_frag, gfp)))
878                 return -ENOMEM;
879
880         buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
881         buf += headroom; /* advance address leaving hole at front of pkt */
882         ctx = mergeable_buf_to_ctx(buf, len);
883         get_page(alloc_frag->page);
884         alloc_frag->offset += len + headroom;
885         hole = alloc_frag->size - alloc_frag->offset;
886         if (hole < len + headroom) {
887                 /* To avoid internal fragmentation, if there is very likely not
888                  * enough space for another buffer, add the remaining space to
889                  * the current buffer. This extra space is not included in
890                  * the truesize stored in ctx.
891                  */
892                 len += hole;
893                 alloc_frag->offset += hole;
894         }
895
896         sg_init_one(rq->sg, buf, len);
897         err = virtqueue_add_inbuf(rq->vq, rq->sg, 1, (void *)ctx, gfp);
898         if (err < 0)
899                 put_page(virt_to_head_page(buf));
900
901         return err;
902 }
903
904 /*
905  * Returns false if we couldn't fill entirely (OOM).
906  *
907  * Normally run in the receive path, but can also be run from ndo_open
908  * before we're receiving packets, or from refill_work which is
909  * careful to disable receiving (using napi_disable).
910  */
911 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
912                           gfp_t gfp)
913 {
914         int err;
915         bool oom;
916
917         gfp |= __GFP_COLD;
918         do {
919                 if (vi->mergeable_rx_bufs)
920                         err = add_recvbuf_mergeable(vi, rq, gfp);
921                 else if (vi->big_packets)
922                         err = add_recvbuf_big(vi, rq, gfp);
923                 else
924                         err = add_recvbuf_small(vi, rq, gfp);
925
926                 oom = err == -ENOMEM;
927                 if (err)
928                         break;
929         } while (rq->vq->num_free);
930         virtqueue_kick(rq->vq);
931         return !oom;
932 }
933
934 static void skb_recv_done(struct virtqueue *rvq)
935 {
936         struct virtnet_info *vi = rvq->vdev->priv;
937         struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
938
939         /* Schedule NAPI, Suppress further interrupts if successful. */
940         if (napi_schedule_prep(&rq->napi)) {
941                 virtqueue_disable_cb(rvq);
942                 __napi_schedule(&rq->napi);
943         }
944 }
945
946 static void virtnet_napi_enable(struct receive_queue *rq)
947 {
948         napi_enable(&rq->napi);
949
950         /* If all buffers were filled by other side before we napi_enabled, we
951          * won't get another interrupt, so process any outstanding packets
952          * now.  virtnet_poll wants re-enable the queue, so we disable here.
953          * We synchronize against interrupts via NAPI_STATE_SCHED */
954         if (napi_schedule_prep(&rq->napi)) {
955                 virtqueue_disable_cb(rq->vq);
956                 local_bh_disable();
957                 __napi_schedule(&rq->napi);
958                 local_bh_enable();
959         }
960 }
961
962 static void refill_work(struct work_struct *work)
963 {
964         struct virtnet_info *vi =
965                 container_of(work, struct virtnet_info, refill.work);
966         bool still_empty;
967         int i;
968
969         for (i = 0; i < vi->curr_queue_pairs; i++) {
970                 struct receive_queue *rq = &vi->rq[i];
971
972                 napi_disable(&rq->napi);
973                 still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
974                 virtnet_napi_enable(rq);
975
976                 /* In theory, this can happen: if we don't get any buffers in
977                  * we will *never* try to fill again.
978                  */
979                 if (still_empty)
980                         schedule_delayed_work(&vi->refill, HZ/2);
981         }
982 }
983
984 static int virtnet_receive(struct receive_queue *rq, int budget)
985 {
986         struct virtnet_info *vi = rq->vq->vdev->priv;
987         unsigned int len, received = 0, bytes = 0;
988         void *buf;
989         struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
990
991         while (received < budget &&
992                (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
993                 bytes += receive_buf(vi, rq, buf, len);
994                 received++;
995         }
996
997         if (rq->vq->num_free > virtqueue_get_vring_size(rq->vq) / 2) {
998                 if (!try_fill_recv(vi, rq, GFP_ATOMIC))
999                         schedule_delayed_work(&vi->refill, 0);
1000         }
1001
1002         u64_stats_update_begin(&stats->rx_syncp);
1003         stats->rx_bytes += bytes;
1004         stats->rx_packets += received;
1005         u64_stats_update_end(&stats->rx_syncp);
1006
1007         return received;
1008 }
1009
1010 static int virtnet_poll(struct napi_struct *napi, int budget)
1011 {
1012         struct receive_queue *rq =
1013                 container_of(napi, struct receive_queue, napi);
1014         unsigned int r, received;
1015
1016         received = virtnet_receive(rq, budget);
1017
1018         /* Out of packets? */
1019         if (received < budget) {
1020                 r = virtqueue_enable_cb_prepare(rq->vq);
1021                 if (napi_complete_done(napi, received)) {
1022                         if (unlikely(virtqueue_poll(rq->vq, r)) &&
1023                             napi_schedule_prep(napi)) {
1024                                 virtqueue_disable_cb(rq->vq);
1025                                 __napi_schedule(napi);
1026                         }
1027                 }
1028         }
1029
1030         return received;
1031 }
1032
1033 static int virtnet_open(struct net_device *dev)
1034 {
1035         struct virtnet_info *vi = netdev_priv(dev);
1036         int i;
1037
1038         for (i = 0; i < vi->max_queue_pairs; i++) {
1039                 if (i < vi->curr_queue_pairs)
1040                         /* Make sure we have some buffers: if oom use wq. */
1041                         if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1042                                 schedule_delayed_work(&vi->refill, 0);
1043                 virtnet_napi_enable(&vi->rq[i]);
1044         }
1045
1046         return 0;
1047 }
1048
1049 static void free_old_xmit_skbs(struct send_queue *sq)
1050 {
1051         struct sk_buff *skb;
1052         unsigned int len;
1053         struct virtnet_info *vi = sq->vq->vdev->priv;
1054         struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
1055         unsigned int packets = 0;
1056         unsigned int bytes = 0;
1057
1058         while ((skb = virtqueue_get_buf(sq->vq, &len)) != NULL) {
1059                 pr_debug("Sent skb %p\n", skb);
1060
1061                 bytes += skb->len;
1062                 packets++;
1063
1064                 dev_kfree_skb_any(skb);
1065         }
1066
1067         /* Avoid overhead when no packets have been processed
1068          * happens when called speculatively from start_xmit.
1069          */
1070         if (!packets)
1071                 return;
1072
1073         u64_stats_update_begin(&stats->tx_syncp);
1074         stats->tx_bytes += bytes;
1075         stats->tx_packets += packets;
1076         u64_stats_update_end(&stats->tx_syncp);
1077 }
1078
1079 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1080 {
1081         struct virtio_net_hdr_mrg_rxbuf *hdr;
1082         const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1083         struct virtnet_info *vi = sq->vq->vdev->priv;
1084         unsigned num_sg;
1085         unsigned hdr_len = vi->hdr_len;
1086         bool can_push;
1087
1088         pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1089
1090         can_push = vi->any_header_sg &&
1091                 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1092                 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1093         /* Even if we can, don't push here yet as this would skew
1094          * csum_start offset below. */
1095         if (can_push)
1096                 hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1097         else
1098                 hdr = skb_vnet_hdr(skb);
1099
1100         if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1101                                     virtio_is_little_endian(vi->vdev), false))
1102                 BUG();
1103
1104         if (vi->mergeable_rx_bufs)
1105                 hdr->num_buffers = 0;
1106
1107         sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1108         if (can_push) {
1109                 __skb_push(skb, hdr_len);
1110                 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1111                 /* Pull header back to avoid skew in tx bytes calculations. */
1112                 __skb_pull(skb, hdr_len);
1113         } else {
1114                 sg_set_buf(sq->sg, hdr, hdr_len);
1115                 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len) + 1;
1116         }
1117         return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1118 }
1119
1120 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1121 {
1122         struct virtnet_info *vi = netdev_priv(dev);
1123         int qnum = skb_get_queue_mapping(skb);
1124         struct send_queue *sq = &vi->sq[qnum];
1125         int err;
1126         struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1127         bool kick = !skb->xmit_more;
1128
1129         /* Free up any pending old buffers before queueing new ones. */
1130         free_old_xmit_skbs(sq);
1131
1132         /* timestamp packet in software */
1133         skb_tx_timestamp(skb);
1134
1135         /* Try to transmit */
1136         err = xmit_skb(sq, skb);
1137
1138         /* This should not happen! */
1139         if (unlikely(err)) {
1140                 dev->stats.tx_fifo_errors++;
1141                 if (net_ratelimit())
1142                         dev_warn(&dev->dev,
1143                                  "Unexpected TXQ (%d) queue failure: %d\n", qnum, err);
1144                 dev->stats.tx_dropped++;
1145                 dev_kfree_skb_any(skb);
1146                 return NETDEV_TX_OK;
1147         }
1148
1149         /* Don't wait up for transmitted skbs to be freed. */
1150         skb_orphan(skb);
1151         nf_reset(skb);
1152
1153         /* If running out of space, stop queue to avoid getting packets that we
1154          * are then unable to transmit.
1155          * An alternative would be to force queuing layer to requeue the skb by
1156          * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
1157          * returned in a normal path of operation: it means that driver is not
1158          * maintaining the TX queue stop/start state properly, and causes
1159          * the stack to do a non-trivial amount of useless work.
1160          * Since most packets only take 1 or 2 ring slots, stopping the queue
1161          * early means 16 slots are typically wasted.
1162          */
1163         if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1164                 netif_stop_subqueue(dev, qnum);
1165                 if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1166                         /* More just got used, free them then recheck. */
1167                         free_old_xmit_skbs(sq);
1168                         if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1169                                 netif_start_subqueue(dev, qnum);
1170                                 virtqueue_disable_cb(sq->vq);
1171                         }
1172                 }
1173         }
1174
1175         if (kick || netif_xmit_stopped(txq))
1176                 virtqueue_kick(sq->vq);
1177
1178         return NETDEV_TX_OK;
1179 }
1180
1181 /*
1182  * Send command via the control virtqueue and check status.  Commands
1183  * supported by the hypervisor, as indicated by feature bits, should
1184  * never fail unless improperly formatted.
1185  */
1186 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1187                                  struct scatterlist *out)
1188 {
1189         struct scatterlist *sgs[4], hdr, stat;
1190         unsigned out_num = 0, tmp;
1191
1192         /* Caller should know better */
1193         BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1194
1195         vi->ctrl_status = ~0;
1196         vi->ctrl_hdr.class = class;
1197         vi->ctrl_hdr.cmd = cmd;
1198         /* Add header */
1199         sg_init_one(&hdr, &vi->ctrl_hdr, sizeof(vi->ctrl_hdr));
1200         sgs[out_num++] = &hdr;
1201
1202         if (out)
1203                 sgs[out_num++] = out;
1204
1205         /* Add return status. */
1206         sg_init_one(&stat, &vi->ctrl_status, sizeof(vi->ctrl_status));
1207         sgs[out_num] = &stat;
1208
1209         BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1210         virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1211
1212         if (unlikely(!virtqueue_kick(vi->cvq)))
1213                 return vi->ctrl_status == VIRTIO_NET_OK;
1214
1215         /* Spin for a response, the kick causes an ioport write, trapping
1216          * into the hypervisor, so the request should be handled immediately.
1217          */
1218         while (!virtqueue_get_buf(vi->cvq, &tmp) &&
1219                !virtqueue_is_broken(vi->cvq))
1220                 cpu_relax();
1221
1222         return vi->ctrl_status == VIRTIO_NET_OK;
1223 }
1224
1225 static int virtnet_set_mac_address(struct net_device *dev, void *p)
1226 {
1227         struct virtnet_info *vi = netdev_priv(dev);
1228         struct virtio_device *vdev = vi->vdev;
1229         int ret;
1230         struct sockaddr *addr;
1231         struct scatterlist sg;
1232
1233         addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
1234         if (!addr)
1235                 return -ENOMEM;
1236
1237         ret = eth_prepare_mac_addr_change(dev, addr);
1238         if (ret)
1239                 goto out;
1240
1241         if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1242                 sg_init_one(&sg, addr->sa_data, dev->addr_len);
1243                 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1244                                           VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
1245                         dev_warn(&vdev->dev,
1246                                  "Failed to set mac address by vq command.\n");
1247                         ret = -EINVAL;
1248                         goto out;
1249                 }
1250         } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
1251                    !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1252                 unsigned int i;
1253
1254                 /* Naturally, this has an atomicity problem. */
1255                 for (i = 0; i < dev->addr_len; i++)
1256                         virtio_cwrite8(vdev,
1257                                        offsetof(struct virtio_net_config, mac) +
1258                                        i, addr->sa_data[i]);
1259         }
1260
1261         eth_commit_mac_addr_change(dev, p);
1262         ret = 0;
1263
1264 out:
1265         kfree(addr);
1266         return ret;
1267 }
1268
1269 static void virtnet_stats(struct net_device *dev,
1270                           struct rtnl_link_stats64 *tot)
1271 {
1272         struct virtnet_info *vi = netdev_priv(dev);
1273         int cpu;
1274         unsigned int start;
1275
1276         for_each_possible_cpu(cpu) {
1277                 struct virtnet_stats *stats = per_cpu_ptr(vi->stats, cpu);
1278                 u64 tpackets, tbytes, rpackets, rbytes;
1279
1280                 do {
1281                         start = u64_stats_fetch_begin_irq(&stats->tx_syncp);
1282                         tpackets = stats->tx_packets;
1283                         tbytes   = stats->tx_bytes;
1284                 } while (u64_stats_fetch_retry_irq(&stats->tx_syncp, start));
1285
1286                 do {
1287                         start = u64_stats_fetch_begin_irq(&stats->rx_syncp);
1288                         rpackets = stats->rx_packets;
1289                         rbytes   = stats->rx_bytes;
1290                 } while (u64_stats_fetch_retry_irq(&stats->rx_syncp, start));
1291
1292                 tot->rx_packets += rpackets;
1293                 tot->tx_packets += tpackets;
1294                 tot->rx_bytes   += rbytes;
1295                 tot->tx_bytes   += tbytes;
1296         }
1297
1298         tot->tx_dropped = dev->stats.tx_dropped;
1299         tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
1300         tot->rx_dropped = dev->stats.rx_dropped;
1301         tot->rx_length_errors = dev->stats.rx_length_errors;
1302         tot->rx_frame_errors = dev->stats.rx_frame_errors;
1303 }
1304
1305 #ifdef CONFIG_NET_POLL_CONTROLLER
1306 static void virtnet_netpoll(struct net_device *dev)
1307 {
1308         struct virtnet_info *vi = netdev_priv(dev);
1309         int i;
1310
1311         for (i = 0; i < vi->curr_queue_pairs; i++)
1312                 napi_schedule(&vi->rq[i].napi);
1313 }
1314 #endif
1315
1316 static void virtnet_ack_link_announce(struct virtnet_info *vi)
1317 {
1318         rtnl_lock();
1319         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
1320                                   VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
1321                 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
1322         rtnl_unlock();
1323 }
1324
1325 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1326 {
1327         struct scatterlist sg;
1328         struct net_device *dev = vi->dev;
1329
1330         if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
1331                 return 0;
1332
1333         vi->ctrl_mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
1334         sg_init_one(&sg, &vi->ctrl_mq, sizeof(vi->ctrl_mq));
1335
1336         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
1337                                   VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
1338                 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
1339                          queue_pairs);
1340                 return -EINVAL;
1341         } else {
1342                 vi->curr_queue_pairs = queue_pairs;
1343                 /* virtnet_open() will refill when device is going to up. */
1344                 if (dev->flags & IFF_UP)
1345                         schedule_delayed_work(&vi->refill, 0);
1346         }
1347
1348         return 0;
1349 }
1350
1351 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1352 {
1353         int err;
1354
1355         rtnl_lock();
1356         err = _virtnet_set_queues(vi, queue_pairs);
1357         rtnl_unlock();
1358         return err;
1359 }
1360
1361 static int virtnet_close(struct net_device *dev)
1362 {
1363         struct virtnet_info *vi = netdev_priv(dev);
1364         int i;
1365
1366         /* Make sure refill_work doesn't re-enable napi! */
1367         cancel_delayed_work_sync(&vi->refill);
1368
1369         for (i = 0; i < vi->max_queue_pairs; i++)
1370                 napi_disable(&vi->rq[i].napi);
1371
1372         return 0;
1373 }
1374
1375 static void virtnet_set_rx_mode(struct net_device *dev)
1376 {
1377         struct virtnet_info *vi = netdev_priv(dev);
1378         struct scatterlist sg[2];
1379         struct virtio_net_ctrl_mac *mac_data;
1380         struct netdev_hw_addr *ha;
1381         int uc_count;
1382         int mc_count;
1383         void *buf;
1384         int i;
1385
1386         /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
1387         if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
1388                 return;
1389
1390         vi->ctrl_promisc = ((dev->flags & IFF_PROMISC) != 0);
1391         vi->ctrl_allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
1392
1393         sg_init_one(sg, &vi->ctrl_promisc, sizeof(vi->ctrl_promisc));
1394
1395         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1396                                   VIRTIO_NET_CTRL_RX_PROMISC, sg))
1397                 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
1398                          vi->ctrl_promisc ? "en" : "dis");
1399
1400         sg_init_one(sg, &vi->ctrl_allmulti, sizeof(vi->ctrl_allmulti));
1401
1402         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1403                                   VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
1404                 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
1405                          vi->ctrl_allmulti ? "en" : "dis");
1406
1407         uc_count = netdev_uc_count(dev);
1408         mc_count = netdev_mc_count(dev);
1409         /* MAC filter - use one buffer for both lists */
1410         buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
1411                       (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
1412         mac_data = buf;
1413         if (!buf)
1414                 return;
1415
1416         sg_init_table(sg, 2);
1417
1418         /* Store the unicast list and count in the front of the buffer */
1419         mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
1420         i = 0;
1421         netdev_for_each_uc_addr(ha, dev)
1422                 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1423
1424         sg_set_buf(&sg[0], mac_data,
1425                    sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
1426
1427         /* multicast list and count fill the end */
1428         mac_data = (void *)&mac_data->macs[uc_count][0];
1429
1430         mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
1431         i = 0;
1432         netdev_for_each_mc_addr(ha, dev)
1433                 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1434
1435         sg_set_buf(&sg[1], mac_data,
1436                    sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
1437
1438         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1439                                   VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
1440                 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
1441
1442         kfree(buf);
1443 }
1444
1445 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
1446                                    __be16 proto, u16 vid)
1447 {
1448         struct virtnet_info *vi = netdev_priv(dev);
1449         struct scatterlist sg;
1450
1451         vi->ctrl_vid = vid;
1452         sg_init_one(&sg, &vi->ctrl_vid, sizeof(vi->ctrl_vid));
1453
1454         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1455                                   VIRTIO_NET_CTRL_VLAN_ADD, &sg))
1456                 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
1457         return 0;
1458 }
1459
1460 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
1461                                     __be16 proto, u16 vid)
1462 {
1463         struct virtnet_info *vi = netdev_priv(dev);
1464         struct scatterlist sg;
1465
1466         vi->ctrl_vid = vid;
1467         sg_init_one(&sg, &vi->ctrl_vid, sizeof(vi->ctrl_vid));
1468
1469         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1470                                   VIRTIO_NET_CTRL_VLAN_DEL, &sg))
1471                 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
1472         return 0;
1473 }
1474
1475 static void virtnet_clean_affinity(struct virtnet_info *vi, long hcpu)
1476 {
1477         int i;
1478
1479         if (vi->affinity_hint_set) {
1480                 for (i = 0; i < vi->max_queue_pairs; i++) {
1481                         virtqueue_set_affinity(vi->rq[i].vq, -1);
1482                         virtqueue_set_affinity(vi->sq[i].vq, -1);
1483                 }
1484
1485                 vi->affinity_hint_set = false;
1486         }
1487 }
1488
1489 static void virtnet_set_affinity(struct virtnet_info *vi)
1490 {
1491         int i;
1492         int cpu;
1493
1494         /* In multiqueue mode, when the number of cpu is equal to the number of
1495          * queue pairs, we let the queue pairs to be private to one cpu by
1496          * setting the affinity hint to eliminate the contention.
1497          */
1498         if (vi->curr_queue_pairs == 1 ||
1499             vi->max_queue_pairs != num_online_cpus()) {
1500                 virtnet_clean_affinity(vi, -1);
1501                 return;
1502         }
1503
1504         i = 0;
1505         for_each_online_cpu(cpu) {
1506                 virtqueue_set_affinity(vi->rq[i].vq, cpu);
1507                 virtqueue_set_affinity(vi->sq[i].vq, cpu);
1508                 netif_set_xps_queue(vi->dev, cpumask_of(cpu), i);
1509                 i++;
1510         }
1511
1512         vi->affinity_hint_set = true;
1513 }
1514
1515 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
1516 {
1517         struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1518                                                    node);
1519         virtnet_set_affinity(vi);
1520         return 0;
1521 }
1522
1523 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
1524 {
1525         struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1526                                                    node_dead);
1527         virtnet_set_affinity(vi);
1528         return 0;
1529 }
1530
1531 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
1532 {
1533         struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1534                                                    node);
1535
1536         virtnet_clean_affinity(vi, cpu);
1537         return 0;
1538 }
1539
1540 static enum cpuhp_state virtionet_online;
1541
1542 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
1543 {
1544         int ret;
1545
1546         ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
1547         if (ret)
1548                 return ret;
1549         ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
1550                                                &vi->node_dead);
1551         if (!ret)
1552                 return ret;
1553         cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
1554         return ret;
1555 }
1556
1557 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
1558 {
1559         cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
1560         cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
1561                                             &vi->node_dead);
1562 }
1563
1564 static void virtnet_get_ringparam(struct net_device *dev,
1565                                 struct ethtool_ringparam *ring)
1566 {
1567         struct virtnet_info *vi = netdev_priv(dev);
1568
1569         ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
1570         ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
1571         ring->rx_pending = ring->rx_max_pending;
1572         ring->tx_pending = ring->tx_max_pending;
1573 }
1574
1575
1576 static void virtnet_get_drvinfo(struct net_device *dev,
1577                                 struct ethtool_drvinfo *info)
1578 {
1579         struct virtnet_info *vi = netdev_priv(dev);
1580         struct virtio_device *vdev = vi->vdev;
1581
1582         strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
1583         strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
1584         strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
1585
1586 }
1587
1588 /* TODO: Eliminate OOO packets during switching */
1589 static int virtnet_set_channels(struct net_device *dev,
1590                                 struct ethtool_channels *channels)
1591 {
1592         struct virtnet_info *vi = netdev_priv(dev);
1593         u16 queue_pairs = channels->combined_count;
1594         int err;
1595
1596         /* We don't support separate rx/tx channels.
1597          * We don't allow setting 'other' channels.
1598          */
1599         if (channels->rx_count || channels->tx_count || channels->other_count)
1600                 return -EINVAL;
1601
1602         if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
1603                 return -EINVAL;
1604
1605         /* For now we don't support modifying channels while XDP is loaded
1606          * also when XDP is loaded all RX queues have XDP programs so we only
1607          * need to check a single RX queue.
1608          */
1609         if (vi->rq[0].xdp_prog)
1610                 return -EINVAL;
1611
1612         get_online_cpus();
1613         err = _virtnet_set_queues(vi, queue_pairs);
1614         if (!err) {
1615                 netif_set_real_num_tx_queues(dev, queue_pairs);
1616                 netif_set_real_num_rx_queues(dev, queue_pairs);
1617
1618                 virtnet_set_affinity(vi);
1619         }
1620         put_online_cpus();
1621
1622         return err;
1623 }
1624
1625 static void virtnet_get_channels(struct net_device *dev,
1626                                  struct ethtool_channels *channels)
1627 {
1628         struct virtnet_info *vi = netdev_priv(dev);
1629
1630         channels->combined_count = vi->curr_queue_pairs;
1631         channels->max_combined = vi->max_queue_pairs;
1632         channels->max_other = 0;
1633         channels->rx_count = 0;
1634         channels->tx_count = 0;
1635         channels->other_count = 0;
1636 }
1637
1638 /* Check if the user is trying to change anything besides speed/duplex */
1639 static bool virtnet_validate_ethtool_cmd(const struct ethtool_cmd *cmd)
1640 {
1641         struct ethtool_cmd diff1 = *cmd;
1642         struct ethtool_cmd diff2 = {};
1643
1644         /* cmd is always set so we need to clear it, validate the port type
1645          * and also without autonegotiation we can ignore advertising
1646          */
1647         ethtool_cmd_speed_set(&diff1, 0);
1648         diff2.port = PORT_OTHER;
1649         diff1.advertising = 0;
1650         diff1.duplex = 0;
1651         diff1.cmd = 0;
1652
1653         return !memcmp(&diff1, &diff2, sizeof(diff1));
1654 }
1655
1656 static int virtnet_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1657 {
1658         struct virtnet_info *vi = netdev_priv(dev);
1659         u32 speed;
1660
1661         speed = ethtool_cmd_speed(cmd);
1662         /* don't allow custom speed and duplex */
1663         if (!ethtool_validate_speed(speed) ||
1664             !ethtool_validate_duplex(cmd->duplex) ||
1665             !virtnet_validate_ethtool_cmd(cmd))
1666                 return -EINVAL;
1667         vi->speed = speed;
1668         vi->duplex = cmd->duplex;
1669
1670         return 0;
1671 }
1672
1673 static int virtnet_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1674 {
1675         struct virtnet_info *vi = netdev_priv(dev);
1676
1677         ethtool_cmd_speed_set(cmd, vi->speed);
1678         cmd->duplex = vi->duplex;
1679         cmd->port = PORT_OTHER;
1680
1681         return 0;
1682 }
1683
1684 static void virtnet_init_settings(struct net_device *dev)
1685 {
1686         struct virtnet_info *vi = netdev_priv(dev);
1687
1688         vi->speed = SPEED_UNKNOWN;
1689         vi->duplex = DUPLEX_UNKNOWN;
1690 }
1691
1692 static const struct ethtool_ops virtnet_ethtool_ops = {
1693         .get_drvinfo = virtnet_get_drvinfo,
1694         .get_link = ethtool_op_get_link,
1695         .get_ringparam = virtnet_get_ringparam,
1696         .set_channels = virtnet_set_channels,
1697         .get_channels = virtnet_get_channels,
1698         .get_ts_info = ethtool_op_get_ts_info,
1699         .get_settings = virtnet_get_settings,
1700         .set_settings = virtnet_set_settings,
1701 };
1702
1703 static void virtnet_freeze_down(struct virtio_device *vdev)
1704 {
1705         struct virtnet_info *vi = vdev->priv;
1706         int i;
1707
1708         /* Make sure no work handler is accessing the device */
1709         flush_work(&vi->config_work);
1710
1711         netif_device_detach(vi->dev);
1712         cancel_delayed_work_sync(&vi->refill);
1713
1714         if (netif_running(vi->dev)) {
1715                 for (i = 0; i < vi->max_queue_pairs; i++)
1716                         napi_disable(&vi->rq[i].napi);
1717         }
1718 }
1719
1720 static int init_vqs(struct virtnet_info *vi);
1721 static void _remove_vq_common(struct virtnet_info *vi);
1722
1723 static int virtnet_restore_up(struct virtio_device *vdev)
1724 {
1725         struct virtnet_info *vi = vdev->priv;
1726         int err, i;
1727
1728         err = init_vqs(vi);
1729         if (err)
1730                 return err;
1731
1732         virtio_device_ready(vdev);
1733
1734         if (netif_running(vi->dev)) {
1735                 for (i = 0; i < vi->curr_queue_pairs; i++)
1736                         if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1737                                 schedule_delayed_work(&vi->refill, 0);
1738
1739                 for (i = 0; i < vi->max_queue_pairs; i++)
1740                         virtnet_napi_enable(&vi->rq[i]);
1741         }
1742
1743         netif_device_attach(vi->dev);
1744         return err;
1745 }
1746
1747 static int virtnet_reset(struct virtnet_info *vi, int curr_qp, int xdp_qp)
1748 {
1749         struct virtio_device *dev = vi->vdev;
1750         int ret;
1751
1752         virtio_config_disable(dev);
1753         dev->failed = dev->config->get_status(dev) & VIRTIO_CONFIG_S_FAILED;
1754         virtnet_freeze_down(dev);
1755         _remove_vq_common(vi);
1756
1757         dev->config->reset(dev);
1758         virtio_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE);
1759         virtio_add_status(dev, VIRTIO_CONFIG_S_DRIVER);
1760
1761         ret = virtio_finalize_features(dev);
1762         if (ret)
1763                 goto err;
1764
1765         vi->xdp_queue_pairs = xdp_qp;
1766         ret = virtnet_restore_up(dev);
1767         if (ret)
1768                 goto err;
1769         ret = _virtnet_set_queues(vi, curr_qp);
1770         if (ret)
1771                 goto err;
1772
1773         virtio_add_status(dev, VIRTIO_CONFIG_S_DRIVER_OK);
1774         virtio_config_enable(dev);
1775         return 0;
1776 err:
1777         virtio_add_status(dev, VIRTIO_CONFIG_S_FAILED);
1778         return ret;
1779 }
1780
1781 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog)
1782 {
1783         unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
1784         struct virtnet_info *vi = netdev_priv(dev);
1785         struct bpf_prog *old_prog;
1786         u16 xdp_qp = 0, curr_qp;
1787         int i, err;
1788
1789         if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
1790             virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
1791             virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
1792             virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO)) {
1793                 netdev_warn(dev, "can't set XDP while host is implementing LRO, disable LRO first\n");
1794                 return -EOPNOTSUPP;
1795         }
1796
1797         if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
1798                 netdev_warn(dev, "XDP expects header/data in single page, any_header_sg required\n");
1799                 return -EINVAL;
1800         }
1801
1802         if (dev->mtu > max_sz) {
1803                 netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
1804                 return -EINVAL;
1805         }
1806
1807         curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
1808         if (prog)
1809                 xdp_qp = nr_cpu_ids;
1810
1811         /* XDP requires extra queues for XDP_TX */
1812         if (curr_qp + xdp_qp > vi->max_queue_pairs) {
1813                 netdev_warn(dev, "request %i queues but max is %i\n",
1814                             curr_qp + xdp_qp, vi->max_queue_pairs);
1815                 return -ENOMEM;
1816         }
1817
1818         if (prog) {
1819                 prog = bpf_prog_add(prog, vi->max_queue_pairs - 1);
1820                 if (IS_ERR(prog))
1821                         return PTR_ERR(prog);
1822         }
1823
1824         /* Changing the headroom in buffers is a disruptive operation because
1825          * existing buffers must be flushed and reallocated. This will happen
1826          * when a xdp program is initially added or xdp is disabled by removing
1827          * the xdp program resulting in number of XDP queues changing.
1828          */
1829         if (vi->xdp_queue_pairs != xdp_qp) {
1830                 err = virtnet_reset(vi, curr_qp + xdp_qp, xdp_qp);
1831                 if (err) {
1832                         dev_warn(&dev->dev, "XDP reset failure.\n");
1833                         goto virtio_reset_err;
1834                 }
1835         }
1836
1837         netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
1838
1839         for (i = 0; i < vi->max_queue_pairs; i++) {
1840                 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
1841                 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
1842                 if (old_prog)
1843                         bpf_prog_put(old_prog);
1844         }
1845
1846         return 0;
1847
1848 virtio_reset_err:
1849         /* On reset error do our best to unwind XDP changes inflight and return
1850          * error up to user space for resolution. The underlying reset hung on
1851          * us so not much we can do here.
1852          */
1853         if (prog)
1854                 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
1855         return err;
1856 }
1857
1858 static bool virtnet_xdp_query(struct net_device *dev)
1859 {
1860         struct virtnet_info *vi = netdev_priv(dev);
1861         int i;
1862
1863         for (i = 0; i < vi->max_queue_pairs; i++) {
1864                 if (vi->rq[i].xdp_prog)
1865                         return true;
1866         }
1867         return false;
1868 }
1869
1870 static int virtnet_xdp(struct net_device *dev, struct netdev_xdp *xdp)
1871 {
1872         switch (xdp->command) {
1873         case XDP_SETUP_PROG:
1874                 return virtnet_xdp_set(dev, xdp->prog);
1875         case XDP_QUERY_PROG:
1876                 xdp->prog_attached = virtnet_xdp_query(dev);
1877                 return 0;
1878         default:
1879                 return -EINVAL;
1880         }
1881 }
1882
1883 static const struct net_device_ops virtnet_netdev = {
1884         .ndo_open            = virtnet_open,
1885         .ndo_stop            = virtnet_close,
1886         .ndo_start_xmit      = start_xmit,
1887         .ndo_validate_addr   = eth_validate_addr,
1888         .ndo_set_mac_address = virtnet_set_mac_address,
1889         .ndo_set_rx_mode     = virtnet_set_rx_mode,
1890         .ndo_get_stats64     = virtnet_stats,
1891         .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
1892         .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
1893 #ifdef CONFIG_NET_POLL_CONTROLLER
1894         .ndo_poll_controller = virtnet_netpoll,
1895 #endif
1896         .ndo_xdp                = virtnet_xdp,
1897 };
1898
1899 static void virtnet_config_changed_work(struct work_struct *work)
1900 {
1901         struct virtnet_info *vi =
1902                 container_of(work, struct virtnet_info, config_work);
1903         u16 v;
1904
1905         if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
1906                                  struct virtio_net_config, status, &v) < 0)
1907                 return;
1908
1909         if (v & VIRTIO_NET_S_ANNOUNCE) {
1910                 netdev_notify_peers(vi->dev);
1911                 virtnet_ack_link_announce(vi);
1912         }
1913
1914         /* Ignore unknown (future) status bits */
1915         v &= VIRTIO_NET_S_LINK_UP;
1916
1917         if (vi->status == v)
1918                 return;
1919
1920         vi->status = v;
1921
1922         if (vi->status & VIRTIO_NET_S_LINK_UP) {
1923                 netif_carrier_on(vi->dev);
1924                 netif_tx_wake_all_queues(vi->dev);
1925         } else {
1926                 netif_carrier_off(vi->dev);
1927                 netif_tx_stop_all_queues(vi->dev);
1928         }
1929 }
1930
1931 static void virtnet_config_changed(struct virtio_device *vdev)
1932 {
1933         struct virtnet_info *vi = vdev->priv;
1934
1935         schedule_work(&vi->config_work);
1936 }
1937
1938 static void virtnet_free_queues(struct virtnet_info *vi)
1939 {
1940         int i;
1941
1942         for (i = 0; i < vi->max_queue_pairs; i++) {
1943                 napi_hash_del(&vi->rq[i].napi);
1944                 netif_napi_del(&vi->rq[i].napi);
1945         }
1946
1947         /* We called napi_hash_del() before netif_napi_del(),
1948          * we need to respect an RCU grace period before freeing vi->rq
1949          */
1950         synchronize_net();
1951
1952         kfree(vi->rq);
1953         kfree(vi->sq);
1954 }
1955
1956 static void _free_receive_bufs(struct virtnet_info *vi)
1957 {
1958         struct bpf_prog *old_prog;
1959         int i;
1960
1961         for (i = 0; i < vi->max_queue_pairs; i++) {
1962                 while (vi->rq[i].pages)
1963                         __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
1964
1965                 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
1966                 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
1967                 if (old_prog)
1968                         bpf_prog_put(old_prog);
1969         }
1970 }
1971
1972 static void free_receive_bufs(struct virtnet_info *vi)
1973 {
1974         rtnl_lock();
1975         _free_receive_bufs(vi);
1976         rtnl_unlock();
1977 }
1978
1979 static void free_receive_page_frags(struct virtnet_info *vi)
1980 {
1981         int i;
1982         for (i = 0; i < vi->max_queue_pairs; i++)
1983                 if (vi->rq[i].alloc_frag.page)
1984                         put_page(vi->rq[i].alloc_frag.page);
1985 }
1986
1987 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
1988 {
1989         if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
1990                 return false;
1991         else if (q < vi->curr_queue_pairs)
1992                 return true;
1993         else
1994                 return false;
1995 }
1996
1997 static void free_unused_bufs(struct virtnet_info *vi)
1998 {
1999         void *buf;
2000         int i;
2001
2002         for (i = 0; i < vi->max_queue_pairs; i++) {
2003                 struct virtqueue *vq = vi->sq[i].vq;
2004                 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2005                         if (!is_xdp_raw_buffer_queue(vi, i))
2006                                 dev_kfree_skb(buf);
2007                         else
2008                                 put_page(virt_to_head_page(buf));
2009                 }
2010         }
2011
2012         for (i = 0; i < vi->max_queue_pairs; i++) {
2013                 struct virtqueue *vq = vi->rq[i].vq;
2014
2015                 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2016                         if (vi->mergeable_rx_bufs) {
2017                                 unsigned long ctx = (unsigned long)buf;
2018                                 void *base = mergeable_ctx_to_buf_address(ctx);
2019                                 put_page(virt_to_head_page(base));
2020                         } else if (vi->big_packets) {
2021                                 give_pages(&vi->rq[i], buf);
2022                         } else {
2023                                 put_page(virt_to_head_page(buf));
2024                         }
2025                 }
2026         }
2027 }
2028
2029 static void virtnet_del_vqs(struct virtnet_info *vi)
2030 {
2031         struct virtio_device *vdev = vi->vdev;
2032
2033         virtnet_clean_affinity(vi, -1);
2034
2035         vdev->config->del_vqs(vdev);
2036
2037         virtnet_free_queues(vi);
2038 }
2039
2040 static int virtnet_find_vqs(struct virtnet_info *vi)
2041 {
2042         vq_callback_t **callbacks;
2043         struct virtqueue **vqs;
2044         int ret = -ENOMEM;
2045         int i, total_vqs;
2046         const char **names;
2047
2048         /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
2049          * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
2050          * possible control vq.
2051          */
2052         total_vqs = vi->max_queue_pairs * 2 +
2053                     virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
2054
2055         /* Allocate space for find_vqs parameters */
2056         vqs = kzalloc(total_vqs * sizeof(*vqs), GFP_KERNEL);
2057         if (!vqs)
2058                 goto err_vq;
2059         callbacks = kmalloc(total_vqs * sizeof(*callbacks), GFP_KERNEL);
2060         if (!callbacks)
2061                 goto err_callback;
2062         names = kmalloc(total_vqs * sizeof(*names), GFP_KERNEL);
2063         if (!names)
2064                 goto err_names;
2065
2066         /* Parameters for control virtqueue, if any */
2067         if (vi->has_cvq) {
2068                 callbacks[total_vqs - 1] = NULL;
2069                 names[total_vqs - 1] = "control";
2070         }
2071
2072         /* Allocate/initialize parameters for send/receive virtqueues */
2073         for (i = 0; i < vi->max_queue_pairs; i++) {
2074                 callbacks[rxq2vq(i)] = skb_recv_done;
2075                 callbacks[txq2vq(i)] = skb_xmit_done;
2076                 sprintf(vi->rq[i].name, "input.%d", i);
2077                 sprintf(vi->sq[i].name, "output.%d", i);
2078                 names[rxq2vq(i)] = vi->rq[i].name;
2079                 names[txq2vq(i)] = vi->sq[i].name;
2080         }
2081
2082         ret = vi->vdev->config->find_vqs(vi->vdev, total_vqs, vqs, callbacks,
2083                                          names);
2084         if (ret)
2085                 goto err_find;
2086
2087         if (vi->has_cvq) {
2088                 vi->cvq = vqs[total_vqs - 1];
2089                 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
2090                         vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
2091         }
2092
2093         for (i = 0; i < vi->max_queue_pairs; i++) {
2094                 vi->rq[i].vq = vqs[rxq2vq(i)];
2095                 vi->sq[i].vq = vqs[txq2vq(i)];
2096         }
2097
2098         kfree(names);
2099         kfree(callbacks);
2100         kfree(vqs);
2101
2102         return 0;
2103
2104 err_find:
2105         kfree(names);
2106 err_names:
2107         kfree(callbacks);
2108 err_callback:
2109         kfree(vqs);
2110 err_vq:
2111         return ret;
2112 }
2113
2114 static int virtnet_alloc_queues(struct virtnet_info *vi)
2115 {
2116         int i;
2117
2118         vi->sq = kzalloc(sizeof(*vi->sq) * vi->max_queue_pairs, GFP_KERNEL);
2119         if (!vi->sq)
2120                 goto err_sq;
2121         vi->rq = kzalloc(sizeof(*vi->rq) * vi->max_queue_pairs, GFP_KERNEL);
2122         if (!vi->rq)
2123                 goto err_rq;
2124
2125         INIT_DELAYED_WORK(&vi->refill, refill_work);
2126         for (i = 0; i < vi->max_queue_pairs; i++) {
2127                 vi->rq[i].pages = NULL;
2128                 netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
2129                                napi_weight);
2130
2131                 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
2132                 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
2133                 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
2134         }
2135
2136         return 0;
2137
2138 err_rq:
2139         kfree(vi->sq);
2140 err_sq:
2141         return -ENOMEM;
2142 }
2143
2144 static int init_vqs(struct virtnet_info *vi)
2145 {
2146         int ret;
2147
2148         /* Allocate send & receive queues */
2149         ret = virtnet_alloc_queues(vi);
2150         if (ret)
2151                 goto err;
2152
2153         ret = virtnet_find_vqs(vi);
2154         if (ret)
2155                 goto err_free;
2156
2157         get_online_cpus();
2158         virtnet_set_affinity(vi);
2159         put_online_cpus();
2160
2161         return 0;
2162
2163 err_free:
2164         virtnet_free_queues(vi);
2165 err:
2166         return ret;
2167 }
2168
2169 #ifdef CONFIG_SYSFS
2170 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
2171                 struct rx_queue_attribute *attribute, char *buf)
2172 {
2173         struct virtnet_info *vi = netdev_priv(queue->dev);
2174         unsigned int queue_index = get_netdev_rx_queue_index(queue);
2175         struct ewma_pkt_len *avg;
2176
2177         BUG_ON(queue_index >= vi->max_queue_pairs);
2178         avg = &vi->rq[queue_index].mrg_avg_pkt_len;
2179         return sprintf(buf, "%u\n", get_mergeable_buf_len(avg));
2180 }
2181
2182 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
2183         __ATTR_RO(mergeable_rx_buffer_size);
2184
2185 static struct attribute *virtio_net_mrg_rx_attrs[] = {
2186         &mergeable_rx_buffer_size_attribute.attr,
2187         NULL
2188 };
2189
2190 static const struct attribute_group virtio_net_mrg_rx_group = {
2191         .name = "virtio_net",
2192         .attrs = virtio_net_mrg_rx_attrs
2193 };
2194 #endif
2195
2196 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
2197                                     unsigned int fbit,
2198                                     const char *fname, const char *dname)
2199 {
2200         if (!virtio_has_feature(vdev, fbit))
2201                 return false;
2202
2203         dev_err(&vdev->dev, "device advertises feature %s but not %s",
2204                 fname, dname);
2205
2206         return true;
2207 }
2208
2209 #define VIRTNET_FAIL_ON(vdev, fbit, dbit)                       \
2210         virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
2211
2212 static bool virtnet_validate_features(struct virtio_device *vdev)
2213 {
2214         if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
2215             (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
2216                              "VIRTIO_NET_F_CTRL_VQ") ||
2217              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
2218                              "VIRTIO_NET_F_CTRL_VQ") ||
2219              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
2220                              "VIRTIO_NET_F_CTRL_VQ") ||
2221              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
2222              VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
2223                              "VIRTIO_NET_F_CTRL_VQ"))) {
2224                 return false;
2225         }
2226
2227         return true;
2228 }
2229
2230 #define MIN_MTU ETH_MIN_MTU
2231 #define MAX_MTU ETH_MAX_MTU
2232
2233 static int virtnet_probe(struct virtio_device *vdev)
2234 {
2235         int i, err;
2236         struct net_device *dev;
2237         struct virtnet_info *vi;
2238         u16 max_queue_pairs;
2239         int mtu;
2240
2241         if (!vdev->config->get) {
2242                 dev_err(&vdev->dev, "%s failure: config access disabled\n",
2243                         __func__);
2244                 return -EINVAL;
2245         }
2246
2247         if (!virtnet_validate_features(vdev))
2248                 return -EINVAL;
2249
2250         /* Find if host supports multiqueue virtio_net device */
2251         err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
2252                                    struct virtio_net_config,
2253                                    max_virtqueue_pairs, &max_queue_pairs);
2254
2255         /* We need at least 2 queue's */
2256         if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
2257             max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
2258             !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
2259                 max_queue_pairs = 1;
2260
2261         /* Allocate ourselves a network device with room for our info */
2262         dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
2263         if (!dev)
2264                 return -ENOMEM;
2265
2266         /* Set up network device as normal. */
2267         dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
2268         dev->netdev_ops = &virtnet_netdev;
2269         dev->features = NETIF_F_HIGHDMA;
2270
2271         dev->ethtool_ops = &virtnet_ethtool_ops;
2272         SET_NETDEV_DEV(dev, &vdev->dev);
2273
2274         /* Do we support "hardware" checksums? */
2275         if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
2276                 /* This opens up the world of extra features. */
2277                 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
2278                 if (csum)
2279                         dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
2280
2281                 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
2282                         dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
2283                                 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
2284                 }
2285                 /* Individual feature bits: what can host handle? */
2286                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
2287                         dev->hw_features |= NETIF_F_TSO;
2288                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
2289                         dev->hw_features |= NETIF_F_TSO6;
2290                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
2291                         dev->hw_features |= NETIF_F_TSO_ECN;
2292                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
2293                         dev->hw_features |= NETIF_F_UFO;
2294
2295                 dev->features |= NETIF_F_GSO_ROBUST;
2296
2297                 if (gso)
2298                         dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
2299                 /* (!csum && gso) case will be fixed by register_netdev() */
2300         }
2301         if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
2302                 dev->features |= NETIF_F_RXCSUM;
2303
2304         dev->vlan_features = dev->features;
2305
2306         /* MTU range: 68 - 65535 */
2307         dev->min_mtu = MIN_MTU;
2308         dev->max_mtu = MAX_MTU;
2309
2310         /* Configuration may specify what MAC to use.  Otherwise random. */
2311         if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
2312                 virtio_cread_bytes(vdev,
2313                                    offsetof(struct virtio_net_config, mac),
2314                                    dev->dev_addr, dev->addr_len);
2315         else
2316                 eth_hw_addr_random(dev);
2317
2318         /* Set up our device-specific information */
2319         vi = netdev_priv(dev);
2320         vi->dev = dev;
2321         vi->vdev = vdev;
2322         vdev->priv = vi;
2323         vi->stats = alloc_percpu(struct virtnet_stats);
2324         err = -ENOMEM;
2325         if (vi->stats == NULL)
2326                 goto free;
2327
2328         for_each_possible_cpu(i) {
2329                 struct virtnet_stats *virtnet_stats;
2330                 virtnet_stats = per_cpu_ptr(vi->stats, i);
2331                 u64_stats_init(&virtnet_stats->tx_syncp);
2332                 u64_stats_init(&virtnet_stats->rx_syncp);
2333         }
2334
2335         INIT_WORK(&vi->config_work, virtnet_config_changed_work);
2336
2337         /* If we can receive ANY GSO packets, we must allocate large ones. */
2338         if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
2339             virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
2340             virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
2341             virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
2342                 vi->big_packets = true;
2343
2344         if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
2345                 vi->mergeable_rx_bufs = true;
2346
2347         if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
2348             virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
2349                 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2350         else
2351                 vi->hdr_len = sizeof(struct virtio_net_hdr);
2352
2353         if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
2354             virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
2355                 vi->any_header_sg = true;
2356
2357         if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
2358                 vi->has_cvq = true;
2359
2360         if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
2361                 mtu = virtio_cread16(vdev,
2362                                      offsetof(struct virtio_net_config,
2363                                               mtu));
2364                 if (mtu < dev->min_mtu) {
2365                         __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
2366                 } else {
2367                         dev->mtu = mtu;
2368                         dev->max_mtu = mtu;
2369                 }
2370         }
2371
2372         if (vi->any_header_sg)
2373                 dev->needed_headroom = vi->hdr_len;
2374
2375         /* Enable multiqueue by default */
2376         if (num_online_cpus() >= max_queue_pairs)
2377                 vi->curr_queue_pairs = max_queue_pairs;
2378         else
2379                 vi->curr_queue_pairs = num_online_cpus();
2380         vi->max_queue_pairs = max_queue_pairs;
2381
2382         /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
2383         err = init_vqs(vi);
2384         if (err)
2385                 goto free_stats;
2386
2387 #ifdef CONFIG_SYSFS
2388         if (vi->mergeable_rx_bufs)
2389                 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
2390 #endif
2391         netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
2392         netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
2393
2394         virtnet_init_settings(dev);
2395
2396         err = register_netdev(dev);
2397         if (err) {
2398                 pr_debug("virtio_net: registering device failed\n");
2399                 goto free_vqs;
2400         }
2401
2402         virtio_device_ready(vdev);
2403
2404         err = virtnet_cpu_notif_add(vi);
2405         if (err) {
2406                 pr_debug("virtio_net: registering cpu notifier failed\n");
2407                 goto free_unregister_netdev;
2408         }
2409
2410         virtnet_set_queues(vi, vi->curr_queue_pairs);
2411
2412         /* Assume link up if device can't report link status,
2413            otherwise get link status from config. */
2414         if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
2415                 netif_carrier_off(dev);
2416                 schedule_work(&vi->config_work);
2417         } else {
2418                 vi->status = VIRTIO_NET_S_LINK_UP;
2419                 netif_carrier_on(dev);
2420         }
2421
2422         pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
2423                  dev->name, max_queue_pairs);
2424
2425         return 0;
2426
2427 free_unregister_netdev:
2428         vi->vdev->config->reset(vdev);
2429
2430         unregister_netdev(dev);
2431 free_vqs:
2432         cancel_delayed_work_sync(&vi->refill);
2433         free_receive_page_frags(vi);
2434         virtnet_del_vqs(vi);
2435 free_stats:
2436         free_percpu(vi->stats);
2437 free:
2438         free_netdev(dev);
2439         return err;
2440 }
2441
2442 static void _remove_vq_common(struct virtnet_info *vi)
2443 {
2444         vi->vdev->config->reset(vi->vdev);
2445         free_unused_bufs(vi);
2446         _free_receive_bufs(vi);
2447         free_receive_page_frags(vi);
2448         virtnet_del_vqs(vi);
2449 }
2450
2451 static void remove_vq_common(struct virtnet_info *vi)
2452 {
2453         vi->vdev->config->reset(vi->vdev);
2454
2455         /* Free unused buffers in both send and recv, if any. */
2456         free_unused_bufs(vi);
2457
2458         free_receive_bufs(vi);
2459
2460         free_receive_page_frags(vi);
2461
2462         virtnet_del_vqs(vi);
2463 }
2464
2465 static void virtnet_remove(struct virtio_device *vdev)
2466 {
2467         struct virtnet_info *vi = vdev->priv;
2468
2469         virtnet_cpu_notif_remove(vi);
2470
2471         /* Make sure no work handler is accessing the device. */
2472         flush_work(&vi->config_work);
2473
2474         unregister_netdev(vi->dev);
2475
2476         remove_vq_common(vi);
2477
2478         free_percpu(vi->stats);
2479         free_netdev(vi->dev);
2480 }
2481
2482 #ifdef CONFIG_PM_SLEEP
2483 static int virtnet_freeze(struct virtio_device *vdev)
2484 {
2485         struct virtnet_info *vi = vdev->priv;
2486
2487         virtnet_cpu_notif_remove(vi);
2488         virtnet_freeze_down(vdev);
2489         remove_vq_common(vi);
2490
2491         return 0;
2492 }
2493
2494 static int virtnet_restore(struct virtio_device *vdev)
2495 {
2496         struct virtnet_info *vi = vdev->priv;
2497         int err;
2498
2499         err = virtnet_restore_up(vdev);
2500         if (err)
2501                 return err;
2502         virtnet_set_queues(vi, vi->curr_queue_pairs);
2503
2504         err = virtnet_cpu_notif_add(vi);
2505         if (err)
2506                 return err;
2507
2508         return 0;
2509 }
2510 #endif
2511
2512 static struct virtio_device_id id_table[] = {
2513         { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
2514         { 0 },
2515 };
2516
2517 #define VIRTNET_FEATURES \
2518         VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
2519         VIRTIO_NET_F_MAC, \
2520         VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
2521         VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
2522         VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
2523         VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
2524         VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
2525         VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
2526         VIRTIO_NET_F_CTRL_MAC_ADDR, \
2527         VIRTIO_NET_F_MTU
2528
2529 static unsigned int features[] = {
2530         VIRTNET_FEATURES,
2531 };
2532
2533 static unsigned int features_legacy[] = {
2534         VIRTNET_FEATURES,
2535         VIRTIO_NET_F_GSO,
2536         VIRTIO_F_ANY_LAYOUT,
2537 };
2538
2539 static struct virtio_driver virtio_net_driver = {
2540         .feature_table = features,
2541         .feature_table_size = ARRAY_SIZE(features),
2542         .feature_table_legacy = features_legacy,
2543         .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
2544         .driver.name =  KBUILD_MODNAME,
2545         .driver.owner = THIS_MODULE,
2546         .id_table =     id_table,
2547         .probe =        virtnet_probe,
2548         .remove =       virtnet_remove,
2549         .config_changed = virtnet_config_changed,
2550 #ifdef CONFIG_PM_SLEEP
2551         .freeze =       virtnet_freeze,
2552         .restore =      virtnet_restore,
2553 #endif
2554 };
2555
2556 static __init int virtio_net_driver_init(void)
2557 {
2558         int ret;
2559
2560         ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
2561                                       virtnet_cpu_online,
2562                                       virtnet_cpu_down_prep);
2563         if (ret < 0)
2564                 goto out;
2565         virtionet_online = ret;
2566         ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
2567                                       NULL, virtnet_cpu_dead);
2568         if (ret)
2569                 goto err_dead;
2570
2571         ret = register_virtio_driver(&virtio_net_driver);
2572         if (ret)
2573                 goto err_virtio;
2574         return 0;
2575 err_virtio:
2576         cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
2577 err_dead:
2578         cpuhp_remove_multi_state(virtionet_online);
2579 out:
2580         return ret;
2581 }
2582 module_init(virtio_net_driver_init);
2583
2584 static __exit void virtio_net_driver_exit(void)
2585 {
2586         cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
2587         cpuhp_remove_multi_state(virtionet_online);
2588         unregister_virtio_driver(&virtio_net_driver);
2589 }
2590 module_exit(virtio_net_driver_exit);
2591
2592 MODULE_DEVICE_TABLE(virtio, id_table);
2593 MODULE_DESCRIPTION("Virtio network driver");
2594 MODULE_LICENSE("GPL");