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