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