]> Pileus Git - ~andy/linux/blob - drivers/net/virtio_net.c
net_sched: fix error return code in fw_change_attrs()
[~andy/linux] / 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/scatterlist.h>
26 #include <linux/if_vlan.h>
27 #include <linux/slab.h>
28 #include <linux/cpu.h>
29
30 static int napi_weight = NAPI_POLL_WEIGHT;
31 module_param(napi_weight, int, 0444);
32
33 static bool csum = true, gso = true;
34 module_param(csum, bool, 0444);
35 module_param(gso, bool, 0444);
36
37 /* FIXME: MTU in config. */
38 #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
39 #define MERGE_BUFFER_LEN (ALIGN(GOOD_PACKET_LEN + \
40                                 sizeof(struct virtio_net_hdr_mrg_rxbuf), \
41                                 L1_CACHE_BYTES))
42 #define GOOD_COPY_LEN   128
43
44 #define VIRTNET_DRIVER_VERSION "1.0.0"
45
46 struct virtnet_stats {
47         struct u64_stats_sync tx_syncp;
48         struct u64_stats_sync rx_syncp;
49         u64 tx_bytes;
50         u64 tx_packets;
51
52         u64 rx_bytes;
53         u64 rx_packets;
54 };
55
56 /* Internal representation of a send virtqueue */
57 struct send_queue {
58         /* Virtqueue associated with this send _queue */
59         struct virtqueue *vq;
60
61         /* TX: fragments + linear part + virtio header */
62         struct scatterlist sg[MAX_SKB_FRAGS + 2];
63
64         /* Name of the send queue: output.$index */
65         char name[40];
66 };
67
68 /* Internal representation of a receive virtqueue */
69 struct receive_queue {
70         /* Virtqueue associated with this receive_queue */
71         struct virtqueue *vq;
72
73         struct napi_struct napi;
74
75         /* Chain pages by the private ptr. */
76         struct page *pages;
77
78         /* RX: fragments + linear part + virtio header */
79         struct scatterlist sg[MAX_SKB_FRAGS + 2];
80
81         /* Name of this receive queue: input.$index */
82         char name[40];
83 };
84
85 struct virtnet_info {
86         struct virtio_device *vdev;
87         struct virtqueue *cvq;
88         struct net_device *dev;
89         struct send_queue *sq;
90         struct receive_queue *rq;
91         unsigned int status;
92
93         /* Max # of queue pairs supported by the device */
94         u16 max_queue_pairs;
95
96         /* # of queue pairs currently used by the driver */
97         u16 curr_queue_pairs;
98
99         /* I like... big packets and I cannot lie! */
100         bool big_packets;
101
102         /* Host will merge rx buffers for big packets (shake it! shake it!) */
103         bool mergeable_rx_bufs;
104
105         /* Has control virtqueue */
106         bool has_cvq;
107
108         /* Host can handle any s/g split between our header and packet data */
109         bool any_header_sg;
110
111         /* enable config space updates */
112         bool config_enable;
113
114         /* Active statistics */
115         struct virtnet_stats __percpu *stats;
116
117         /* Work struct for refilling if we run low on memory. */
118         struct delayed_work refill;
119
120         /* Work struct for config space updates */
121         struct work_struct config_work;
122
123         /* Lock for config space updates */
124         struct mutex config_lock;
125
126         /* Page_frag for GFP_KERNEL packet buffer allocation when we run
127          * low on memory.
128          */
129         struct page_frag alloc_frag;
130
131         /* Does the affinity hint is set for virtqueues? */
132         bool affinity_hint_set;
133
134         /* CPU hot plug notifier */
135         struct notifier_block nb;
136 };
137
138 struct skb_vnet_hdr {
139         union {
140                 struct virtio_net_hdr hdr;
141                 struct virtio_net_hdr_mrg_rxbuf mhdr;
142         };
143 };
144
145 struct padded_vnet_hdr {
146         struct virtio_net_hdr hdr;
147         /*
148          * virtio_net_hdr should be in a separated sg buffer because of a
149          * QEMU bug, and data sg buffer shares same page with this header sg.
150          * This padding makes next sg 16 byte aligned after virtio_net_hdr.
151          */
152         char padding[6];
153 };
154
155 /* Converting between virtqueue no. and kernel tx/rx queue no.
156  * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
157  */
158 static int vq2txq(struct virtqueue *vq)
159 {
160         return (vq->index - 1) / 2;
161 }
162
163 static int txq2vq(int txq)
164 {
165         return txq * 2 + 1;
166 }
167
168 static int vq2rxq(struct virtqueue *vq)
169 {
170         return vq->index / 2;
171 }
172
173 static int rxq2vq(int rxq)
174 {
175         return rxq * 2;
176 }
177
178 static inline struct skb_vnet_hdr *skb_vnet_hdr(struct sk_buff *skb)
179 {
180         return (struct skb_vnet_hdr *)skb->cb;
181 }
182
183 /*
184  * private is used to chain pages for big packets, put the whole
185  * most recent used list in the beginning for reuse
186  */
187 static void give_pages(struct receive_queue *rq, struct page *page)
188 {
189         struct page *end;
190
191         /* Find end of list, sew whole thing into vi->rq.pages. */
192         for (end = page; end->private; end = (struct page *)end->private);
193         end->private = (unsigned long)rq->pages;
194         rq->pages = page;
195 }
196
197 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
198 {
199         struct page *p = rq->pages;
200
201         if (p) {
202                 rq->pages = (struct page *)p->private;
203                 /* clear private here, it is used to chain pages */
204                 p->private = 0;
205         } else
206                 p = alloc_page(gfp_mask);
207         return p;
208 }
209
210 static void skb_xmit_done(struct virtqueue *vq)
211 {
212         struct virtnet_info *vi = vq->vdev->priv;
213
214         /* Suppress further interrupts. */
215         virtqueue_disable_cb(vq);
216
217         /* We were probably waiting for more output buffers. */
218         netif_wake_subqueue(vi->dev, vq2txq(vq));
219 }
220
221 /* Called from bottom half context */
222 static struct sk_buff *page_to_skb(struct receive_queue *rq,
223                                    struct page *page, unsigned int offset,
224                                    unsigned int len, unsigned int truesize)
225 {
226         struct virtnet_info *vi = rq->vq->vdev->priv;
227         struct sk_buff *skb;
228         struct skb_vnet_hdr *hdr;
229         unsigned int copy, hdr_len, hdr_padded_len;
230         char *p;
231
232         p = page_address(page) + offset;
233
234         /* copy small packet so we can reuse these pages for small data */
235         skb = netdev_alloc_skb_ip_align(vi->dev, GOOD_COPY_LEN);
236         if (unlikely(!skb))
237                 return NULL;
238
239         hdr = skb_vnet_hdr(skb);
240
241         if (vi->mergeable_rx_bufs) {
242                 hdr_len = sizeof hdr->mhdr;
243                 hdr_padded_len = sizeof hdr->mhdr;
244         } else {
245                 hdr_len = sizeof hdr->hdr;
246                 hdr_padded_len = sizeof(struct padded_vnet_hdr);
247         }
248
249         memcpy(hdr, p, hdr_len);
250
251         len -= hdr_len;
252         offset += hdr_padded_len;
253         p += hdr_padded_len;
254
255         copy = len;
256         if (copy > skb_tailroom(skb))
257                 copy = skb_tailroom(skb);
258         memcpy(skb_put(skb, copy), p, copy);
259
260         len -= copy;
261         offset += copy;
262
263         if (vi->mergeable_rx_bufs) {
264                 if (len)
265                         skb_add_rx_frag(skb, 0, page, offset, len, truesize);
266                 else
267                         put_page(page);
268                 return skb;
269         }
270
271         /*
272          * Verify that we can indeed put this data into a skb.
273          * This is here to handle cases when the device erroneously
274          * tries to receive more than is possible. This is usually
275          * the case of a broken device.
276          */
277         if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
278                 net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
279                 dev_kfree_skb(skb);
280                 return NULL;
281         }
282         BUG_ON(offset >= PAGE_SIZE);
283         while (len) {
284                 unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
285                 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
286                                 frag_size, truesize);
287                 len -= frag_size;
288                 page = (struct page *)page->private;
289                 offset = 0;
290         }
291
292         if (page)
293                 give_pages(rq, page);
294
295         return skb;
296 }
297
298 static struct sk_buff *receive_small(void *buf, unsigned int len)
299 {
300         struct sk_buff * skb = buf;
301
302         len -= sizeof(struct virtio_net_hdr);
303         skb_trim(skb, len);
304
305         return skb;
306 }
307
308 static struct sk_buff *receive_big(struct net_device *dev,
309                                    struct receive_queue *rq,
310                                    void *buf,
311                                    unsigned int len)
312 {
313         struct page *page = buf;
314         struct sk_buff *skb = page_to_skb(rq, page, 0, len, PAGE_SIZE);
315
316         if (unlikely(!skb))
317                 goto err;
318
319         return skb;
320
321 err:
322         dev->stats.rx_dropped++;
323         give_pages(rq, page);
324         return NULL;
325 }
326
327 static struct sk_buff *receive_mergeable(struct net_device *dev,
328                                          struct receive_queue *rq,
329                                          void *buf,
330                                          unsigned int len)
331 {
332         struct skb_vnet_hdr *hdr = buf;
333         int num_buf = hdr->mhdr.num_buffers;
334         struct page *page = virt_to_head_page(buf);
335         int offset = buf - page_address(page);
336         struct sk_buff *head_skb = page_to_skb(rq, page, offset, len,
337                                                MERGE_BUFFER_LEN);
338         struct sk_buff *curr_skb = head_skb;
339
340         if (unlikely(!curr_skb))
341                 goto err_skb;
342
343         while (--num_buf) {
344                 int num_skb_frags;
345
346                 buf = virtqueue_get_buf(rq->vq, &len);
347                 if (unlikely(!buf)) {
348                         pr_debug("%s: rx error: %d buffers out of %d missing\n",
349                                  dev->name, num_buf, hdr->mhdr.num_buffers);
350                         dev->stats.rx_length_errors++;
351                         goto err_buf;
352                 }
353                 if (unlikely(len > MERGE_BUFFER_LEN)) {
354                         pr_debug("%s: rx error: merge buffer too long\n",
355                                  dev->name);
356                         len = MERGE_BUFFER_LEN;
357                 }
358
359                 page = virt_to_head_page(buf);
360
361                 num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
362                 if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
363                         struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
364
365                         if (unlikely(!nskb))
366                                 goto err_skb;
367                         if (curr_skb == head_skb)
368                                 skb_shinfo(curr_skb)->frag_list = nskb;
369                         else
370                                 curr_skb->next = nskb;
371                         curr_skb = nskb;
372                         head_skb->truesize += nskb->truesize;
373                         num_skb_frags = 0;
374                 }
375                 if (curr_skb != head_skb) {
376                         head_skb->data_len += len;
377                         head_skb->len += len;
378                         head_skb->truesize += MERGE_BUFFER_LEN;
379                 }
380                 offset = buf - page_address(page);
381                 if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
382                         put_page(page);
383                         skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
384                                              len, MERGE_BUFFER_LEN);
385                 } else {
386                         skb_add_rx_frag(curr_skb, num_skb_frags, page,
387                                         offset, len, MERGE_BUFFER_LEN);
388                 }
389         }
390
391         return head_skb;
392
393 err_skb:
394         put_page(page);
395         while (--num_buf) {
396                 buf = virtqueue_get_buf(rq->vq, &len);
397                 if (unlikely(!buf)) {
398                         pr_debug("%s: rx error: %d buffers missing\n",
399                                  dev->name, num_buf);
400                         dev->stats.rx_length_errors++;
401                         break;
402                 }
403                 page = virt_to_head_page(buf);
404                 put_page(page);
405         }
406 err_buf:
407         dev->stats.rx_dropped++;
408         dev_kfree_skb(head_skb);
409         return NULL;
410 }
411
412 static void receive_buf(struct receive_queue *rq, void *buf, unsigned int len)
413 {
414         struct virtnet_info *vi = rq->vq->vdev->priv;
415         struct net_device *dev = vi->dev;
416         struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
417         struct sk_buff *skb;
418         struct skb_vnet_hdr *hdr;
419
420         if (unlikely(len < sizeof(struct virtio_net_hdr) + ETH_HLEN)) {
421                 pr_debug("%s: short packet %i\n", dev->name, len);
422                 dev->stats.rx_length_errors++;
423                 if (vi->mergeable_rx_bufs)
424                         put_page(virt_to_head_page(buf));
425                 else if (vi->big_packets)
426                         give_pages(rq, buf);
427                 else
428                         dev_kfree_skb(buf);
429                 return;
430         }
431
432         if (vi->mergeable_rx_bufs)
433                 skb = receive_mergeable(dev, rq, buf, len);
434         else if (vi->big_packets)
435                 skb = receive_big(dev, rq, buf, len);
436         else
437                 skb = receive_small(buf, len);
438
439         if (unlikely(!skb))
440                 return;
441
442         hdr = skb_vnet_hdr(skb);
443
444         u64_stats_update_begin(&stats->rx_syncp);
445         stats->rx_bytes += skb->len;
446         stats->rx_packets++;
447         u64_stats_update_end(&stats->rx_syncp);
448
449         if (hdr->hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
450                 pr_debug("Needs csum!\n");
451                 if (!skb_partial_csum_set(skb,
452                                           hdr->hdr.csum_start,
453                                           hdr->hdr.csum_offset))
454                         goto frame_err;
455         } else if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID) {
456                 skb->ip_summed = CHECKSUM_UNNECESSARY;
457         }
458
459         skb->protocol = eth_type_trans(skb, dev);
460         pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
461                  ntohs(skb->protocol), skb->len, skb->pkt_type);
462
463         if (hdr->hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
464                 pr_debug("GSO!\n");
465                 switch (hdr->hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
466                 case VIRTIO_NET_HDR_GSO_TCPV4:
467                         skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
468                         break;
469                 case VIRTIO_NET_HDR_GSO_UDP:
470                         skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
471                         break;
472                 case VIRTIO_NET_HDR_GSO_TCPV6:
473                         skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
474                         break;
475                 default:
476                         net_warn_ratelimited("%s: bad gso type %u.\n",
477                                              dev->name, hdr->hdr.gso_type);
478                         goto frame_err;
479                 }
480
481                 if (hdr->hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
482                         skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
483
484                 skb_shinfo(skb)->gso_size = hdr->hdr.gso_size;
485                 if (skb_shinfo(skb)->gso_size == 0) {
486                         net_warn_ratelimited("%s: zero gso size.\n", dev->name);
487                         goto frame_err;
488                 }
489
490                 /* Header must be checked, and gso_segs computed. */
491                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
492                 skb_shinfo(skb)->gso_segs = 0;
493         }
494
495         netif_receive_skb(skb);
496         return;
497
498 frame_err:
499         dev->stats.rx_frame_errors++;
500         dev_kfree_skb(skb);
501 }
502
503 static int add_recvbuf_small(struct receive_queue *rq, gfp_t gfp)
504 {
505         struct virtnet_info *vi = rq->vq->vdev->priv;
506         struct sk_buff *skb;
507         struct skb_vnet_hdr *hdr;
508         int err;
509
510         skb = __netdev_alloc_skb_ip_align(vi->dev, GOOD_PACKET_LEN, gfp);
511         if (unlikely(!skb))
512                 return -ENOMEM;
513
514         skb_put(skb, GOOD_PACKET_LEN);
515
516         hdr = skb_vnet_hdr(skb);
517         sg_set_buf(rq->sg, &hdr->hdr, sizeof hdr->hdr);
518
519         skb_to_sgvec(skb, rq->sg + 1, 0, skb->len);
520
521         err = virtqueue_add_inbuf(rq->vq, rq->sg, 2, skb, gfp);
522         if (err < 0)
523                 dev_kfree_skb(skb);
524
525         return err;
526 }
527
528 static int add_recvbuf_big(struct receive_queue *rq, gfp_t gfp)
529 {
530         struct page *first, *list = NULL;
531         char *p;
532         int i, err, offset;
533
534         /* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
535         for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
536                 first = get_a_page(rq, gfp);
537                 if (!first) {
538                         if (list)
539                                 give_pages(rq, list);
540                         return -ENOMEM;
541                 }
542                 sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
543
544                 /* chain new page in list head to match sg */
545                 first->private = (unsigned long)list;
546                 list = first;
547         }
548
549         first = get_a_page(rq, gfp);
550         if (!first) {
551                 give_pages(rq, list);
552                 return -ENOMEM;
553         }
554         p = page_address(first);
555
556         /* rq->sg[0], rq->sg[1] share the same page */
557         /* a separated rq->sg[0] for virtio_net_hdr only due to QEMU bug */
558         sg_set_buf(&rq->sg[0], p, sizeof(struct virtio_net_hdr));
559
560         /* rq->sg[1] for data packet, from offset */
561         offset = sizeof(struct padded_vnet_hdr);
562         sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
563
564         /* chain first in list head */
565         first->private = (unsigned long)list;
566         err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
567                                   first, gfp);
568         if (err < 0)
569                 give_pages(rq, first);
570
571         return err;
572 }
573
574 static int add_recvbuf_mergeable(struct receive_queue *rq, gfp_t gfp)
575 {
576         struct virtnet_info *vi = rq->vq->vdev->priv;
577         char *buf = NULL;
578         int err;
579
580         if (gfp & __GFP_WAIT) {
581                 if (skb_page_frag_refill(MERGE_BUFFER_LEN, &vi->alloc_frag,
582                                          gfp)) {
583                         buf = (char *)page_address(vi->alloc_frag.page) +
584                               vi->alloc_frag.offset;
585                         get_page(vi->alloc_frag.page);
586                         vi->alloc_frag.offset += MERGE_BUFFER_LEN;
587                 }
588         } else {
589                 buf = netdev_alloc_frag(MERGE_BUFFER_LEN);
590         }
591         if (!buf)
592                 return -ENOMEM;
593
594         sg_init_one(rq->sg, buf, MERGE_BUFFER_LEN);
595         err = virtqueue_add_inbuf(rq->vq, rq->sg, 1, buf, gfp);
596         if (err < 0)
597                 put_page(virt_to_head_page(buf));
598
599         return err;
600 }
601
602 /*
603  * Returns false if we couldn't fill entirely (OOM).
604  *
605  * Normally run in the receive path, but can also be run from ndo_open
606  * before we're receiving packets, or from refill_work which is
607  * careful to disable receiving (using napi_disable).
608  */
609 static bool try_fill_recv(struct receive_queue *rq, gfp_t gfp)
610 {
611         struct virtnet_info *vi = rq->vq->vdev->priv;
612         int err;
613         bool oom;
614
615         do {
616                 if (vi->mergeable_rx_bufs)
617                         err = add_recvbuf_mergeable(rq, gfp);
618                 else if (vi->big_packets)
619                         err = add_recvbuf_big(rq, gfp);
620                 else
621                         err = add_recvbuf_small(rq, gfp);
622
623                 oom = err == -ENOMEM;
624                 if (err)
625                         break;
626         } while (rq->vq->num_free);
627         if (unlikely(!virtqueue_kick(rq->vq)))
628                 return false;
629         return !oom;
630 }
631
632 static void skb_recv_done(struct virtqueue *rvq)
633 {
634         struct virtnet_info *vi = rvq->vdev->priv;
635         struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
636
637         /* Schedule NAPI, Suppress further interrupts if successful. */
638         if (napi_schedule_prep(&rq->napi)) {
639                 virtqueue_disable_cb(rvq);
640                 __napi_schedule(&rq->napi);
641         }
642 }
643
644 static void virtnet_napi_enable(struct receive_queue *rq)
645 {
646         napi_enable(&rq->napi);
647
648         /* If all buffers were filled by other side before we napi_enabled, we
649          * won't get another interrupt, so process any outstanding packets
650          * now.  virtnet_poll wants re-enable the queue, so we disable here.
651          * We synchronize against interrupts via NAPI_STATE_SCHED */
652         if (napi_schedule_prep(&rq->napi)) {
653                 virtqueue_disable_cb(rq->vq);
654                 local_bh_disable();
655                 __napi_schedule(&rq->napi);
656                 local_bh_enable();
657         }
658 }
659
660 static void refill_work(struct work_struct *work)
661 {
662         struct virtnet_info *vi =
663                 container_of(work, struct virtnet_info, refill.work);
664         bool still_empty;
665         int i;
666
667         for (i = 0; i < vi->curr_queue_pairs; i++) {
668                 struct receive_queue *rq = &vi->rq[i];
669
670                 napi_disable(&rq->napi);
671                 still_empty = !try_fill_recv(rq, GFP_KERNEL);
672                 virtnet_napi_enable(rq);
673
674                 /* In theory, this can happen: if we don't get any buffers in
675                  * we will *never* try to fill again.
676                  */
677                 if (still_empty)
678                         schedule_delayed_work(&vi->refill, HZ/2);
679         }
680 }
681
682 static int virtnet_poll(struct napi_struct *napi, int budget)
683 {
684         struct receive_queue *rq =
685                 container_of(napi, struct receive_queue, napi);
686         struct virtnet_info *vi = rq->vq->vdev->priv;
687         void *buf;
688         unsigned int r, len, received = 0;
689
690 again:
691         while (received < budget &&
692                (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
693                 receive_buf(rq, buf, len);
694                 received++;
695         }
696
697         if (rq->vq->num_free > virtqueue_get_vring_size(rq->vq) / 2) {
698                 if (!try_fill_recv(rq, GFP_ATOMIC))
699                         schedule_delayed_work(&vi->refill, 0);
700         }
701
702         /* Out of packets? */
703         if (received < budget) {
704                 r = virtqueue_enable_cb_prepare(rq->vq);
705                 napi_complete(napi);
706                 if (unlikely(virtqueue_poll(rq->vq, r)) &&
707                     napi_schedule_prep(napi)) {
708                         virtqueue_disable_cb(rq->vq);
709                         __napi_schedule(napi);
710                         goto again;
711                 }
712         }
713
714         return received;
715 }
716
717 static int virtnet_open(struct net_device *dev)
718 {
719         struct virtnet_info *vi = netdev_priv(dev);
720         int i;
721
722         for (i = 0; i < vi->max_queue_pairs; i++) {
723                 if (i < vi->curr_queue_pairs)
724                         /* Make sure we have some buffers: if oom use wq. */
725                         if (!try_fill_recv(&vi->rq[i], GFP_KERNEL))
726                                 schedule_delayed_work(&vi->refill, 0);
727                 virtnet_napi_enable(&vi->rq[i]);
728         }
729
730         return 0;
731 }
732
733 static void free_old_xmit_skbs(struct send_queue *sq)
734 {
735         struct sk_buff *skb;
736         unsigned int len;
737         struct virtnet_info *vi = sq->vq->vdev->priv;
738         struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
739
740         while ((skb = virtqueue_get_buf(sq->vq, &len)) != NULL) {
741                 pr_debug("Sent skb %p\n", skb);
742
743                 u64_stats_update_begin(&stats->tx_syncp);
744                 stats->tx_bytes += skb->len;
745                 stats->tx_packets++;
746                 u64_stats_update_end(&stats->tx_syncp);
747
748                 dev_kfree_skb_any(skb);
749         }
750 }
751
752 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
753 {
754         struct skb_vnet_hdr *hdr;
755         const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
756         struct virtnet_info *vi = sq->vq->vdev->priv;
757         unsigned num_sg;
758         unsigned hdr_len;
759         bool can_push;
760
761         pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
762         if (vi->mergeable_rx_bufs)
763                 hdr_len = sizeof hdr->mhdr;
764         else
765                 hdr_len = sizeof hdr->hdr;
766
767         can_push = vi->any_header_sg &&
768                 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
769                 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
770         /* Even if we can, don't push here yet as this would skew
771          * csum_start offset below. */
772         if (can_push)
773                 hdr = (struct skb_vnet_hdr *)(skb->data - hdr_len);
774         else
775                 hdr = skb_vnet_hdr(skb);
776
777         if (skb->ip_summed == CHECKSUM_PARTIAL) {
778                 hdr->hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
779                 hdr->hdr.csum_start = skb_checksum_start_offset(skb);
780                 hdr->hdr.csum_offset = skb->csum_offset;
781         } else {
782                 hdr->hdr.flags = 0;
783                 hdr->hdr.csum_offset = hdr->hdr.csum_start = 0;
784         }
785
786         if (skb_is_gso(skb)) {
787                 hdr->hdr.hdr_len = skb_headlen(skb);
788                 hdr->hdr.gso_size = skb_shinfo(skb)->gso_size;
789                 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4)
790                         hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
791                 else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6)
792                         hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
793                 else if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP)
794                         hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
795                 else
796                         BUG();
797                 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCP_ECN)
798                         hdr->hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
799         } else {
800                 hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
801                 hdr->hdr.gso_size = hdr->hdr.hdr_len = 0;
802         }
803
804         if (vi->mergeable_rx_bufs)
805                 hdr->mhdr.num_buffers = 0;
806
807         if (can_push) {
808                 __skb_push(skb, hdr_len);
809                 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
810                 /* Pull header back to avoid skew in tx bytes calculations. */
811                 __skb_pull(skb, hdr_len);
812         } else {
813                 sg_set_buf(sq->sg, hdr, hdr_len);
814                 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len) + 1;
815         }
816         return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
817 }
818
819 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
820 {
821         struct virtnet_info *vi = netdev_priv(dev);
822         int qnum = skb_get_queue_mapping(skb);
823         struct send_queue *sq = &vi->sq[qnum];
824         int err;
825
826         /* Free up any pending old buffers before queueing new ones. */
827         free_old_xmit_skbs(sq);
828
829         /* Try to transmit */
830         err = xmit_skb(sq, skb);
831
832         /* This should not happen! */
833         if (unlikely(err) || unlikely(!virtqueue_kick(sq->vq))) {
834                 dev->stats.tx_fifo_errors++;
835                 if (net_ratelimit())
836                         dev_warn(&dev->dev,
837                                  "Unexpected TXQ (%d) queue failure: %d\n", qnum, err);
838                 dev->stats.tx_dropped++;
839                 kfree_skb(skb);
840                 return NETDEV_TX_OK;
841         }
842
843         /* Don't wait up for transmitted skbs to be freed. */
844         skb_orphan(skb);
845         nf_reset(skb);
846
847         /* Apparently nice girls don't return TX_BUSY; stop the queue
848          * before it gets out of hand.  Naturally, this wastes entries. */
849         if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
850                 netif_stop_subqueue(dev, qnum);
851                 if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
852                         /* More just got used, free them then recheck. */
853                         free_old_xmit_skbs(sq);
854                         if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
855                                 netif_start_subqueue(dev, qnum);
856                                 virtqueue_disable_cb(sq->vq);
857                         }
858                 }
859         }
860
861         return NETDEV_TX_OK;
862 }
863
864 /*
865  * Send command via the control virtqueue and check status.  Commands
866  * supported by the hypervisor, as indicated by feature bits, should
867  * never fail unless improperly formatted.
868  */
869 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
870                                  struct scatterlist *out)
871 {
872         struct scatterlist *sgs[4], hdr, stat;
873         struct virtio_net_ctrl_hdr ctrl;
874         virtio_net_ctrl_ack status = ~0;
875         unsigned out_num = 0, tmp;
876
877         /* Caller should know better */
878         BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
879
880         ctrl.class = class;
881         ctrl.cmd = cmd;
882         /* Add header */
883         sg_init_one(&hdr, &ctrl, sizeof(ctrl));
884         sgs[out_num++] = &hdr;
885
886         if (out)
887                 sgs[out_num++] = out;
888
889         /* Add return status. */
890         sg_init_one(&stat, &status, sizeof(status));
891         sgs[out_num] = &stat;
892
893         BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
894         BUG_ON(virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC) < 0);
895
896         if (unlikely(!virtqueue_kick(vi->cvq)))
897                 return status == VIRTIO_NET_OK;
898
899         /* Spin for a response, the kick causes an ioport write, trapping
900          * into the hypervisor, so the request should be handled immediately.
901          */
902         while (!virtqueue_get_buf(vi->cvq, &tmp) &&
903                !virtqueue_is_broken(vi->cvq))
904                 cpu_relax();
905
906         return status == VIRTIO_NET_OK;
907 }
908
909 static int virtnet_set_mac_address(struct net_device *dev, void *p)
910 {
911         struct virtnet_info *vi = netdev_priv(dev);
912         struct virtio_device *vdev = vi->vdev;
913         int ret;
914         struct sockaddr *addr = p;
915         struct scatterlist sg;
916
917         ret = eth_prepare_mac_addr_change(dev, p);
918         if (ret)
919                 return ret;
920
921         if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
922                 sg_init_one(&sg, addr->sa_data, dev->addr_len);
923                 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
924                                           VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
925                         dev_warn(&vdev->dev,
926                                  "Failed to set mac address by vq command.\n");
927                         return -EINVAL;
928                 }
929         } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
930                 unsigned int i;
931
932                 /* Naturally, this has an atomicity problem. */
933                 for (i = 0; i < dev->addr_len; i++)
934                         virtio_cwrite8(vdev,
935                                        offsetof(struct virtio_net_config, mac) +
936                                        i, addr->sa_data[i]);
937         }
938
939         eth_commit_mac_addr_change(dev, p);
940
941         return 0;
942 }
943
944 static struct rtnl_link_stats64 *virtnet_stats(struct net_device *dev,
945                                                struct rtnl_link_stats64 *tot)
946 {
947         struct virtnet_info *vi = netdev_priv(dev);
948         int cpu;
949         unsigned int start;
950
951         for_each_possible_cpu(cpu) {
952                 struct virtnet_stats *stats = per_cpu_ptr(vi->stats, cpu);
953                 u64 tpackets, tbytes, rpackets, rbytes;
954
955                 do {
956                         start = u64_stats_fetch_begin_bh(&stats->tx_syncp);
957                         tpackets = stats->tx_packets;
958                         tbytes   = stats->tx_bytes;
959                 } while (u64_stats_fetch_retry_bh(&stats->tx_syncp, start));
960
961                 do {
962                         start = u64_stats_fetch_begin_bh(&stats->rx_syncp);
963                         rpackets = stats->rx_packets;
964                         rbytes   = stats->rx_bytes;
965                 } while (u64_stats_fetch_retry_bh(&stats->rx_syncp, start));
966
967                 tot->rx_packets += rpackets;
968                 tot->tx_packets += tpackets;
969                 tot->rx_bytes   += rbytes;
970                 tot->tx_bytes   += tbytes;
971         }
972
973         tot->tx_dropped = dev->stats.tx_dropped;
974         tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
975         tot->rx_dropped = dev->stats.rx_dropped;
976         tot->rx_length_errors = dev->stats.rx_length_errors;
977         tot->rx_frame_errors = dev->stats.rx_frame_errors;
978
979         return tot;
980 }
981
982 #ifdef CONFIG_NET_POLL_CONTROLLER
983 static void virtnet_netpoll(struct net_device *dev)
984 {
985         struct virtnet_info *vi = netdev_priv(dev);
986         int i;
987
988         for (i = 0; i < vi->curr_queue_pairs; i++)
989                 napi_schedule(&vi->rq[i].napi);
990 }
991 #endif
992
993 static void virtnet_ack_link_announce(struct virtnet_info *vi)
994 {
995         rtnl_lock();
996         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
997                                   VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
998                 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
999         rtnl_unlock();
1000 }
1001
1002 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1003 {
1004         struct scatterlist sg;
1005         struct virtio_net_ctrl_mq s;
1006         struct net_device *dev = vi->dev;
1007
1008         if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
1009                 return 0;
1010
1011         s.virtqueue_pairs = queue_pairs;
1012         sg_init_one(&sg, &s, sizeof(s));
1013
1014         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
1015                                   VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
1016                 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
1017                          queue_pairs);
1018                 return -EINVAL;
1019         } else {
1020                 vi->curr_queue_pairs = queue_pairs;
1021                 /* virtnet_open() will refill when device is going to up. */
1022                 if (dev->flags & IFF_UP)
1023                         schedule_delayed_work(&vi->refill, 0);
1024         }
1025
1026         return 0;
1027 }
1028
1029 static int virtnet_close(struct net_device *dev)
1030 {
1031         struct virtnet_info *vi = netdev_priv(dev);
1032         int i;
1033
1034         /* Make sure refill_work doesn't re-enable napi! */
1035         cancel_delayed_work_sync(&vi->refill);
1036
1037         for (i = 0; i < vi->max_queue_pairs; i++)
1038                 napi_disable(&vi->rq[i].napi);
1039
1040         return 0;
1041 }
1042
1043 static void virtnet_set_rx_mode(struct net_device *dev)
1044 {
1045         struct virtnet_info *vi = netdev_priv(dev);
1046         struct scatterlist sg[2];
1047         u8 promisc, allmulti;
1048         struct virtio_net_ctrl_mac *mac_data;
1049         struct netdev_hw_addr *ha;
1050         int uc_count;
1051         int mc_count;
1052         void *buf;
1053         int i;
1054
1055         /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
1056         if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
1057                 return;
1058
1059         promisc = ((dev->flags & IFF_PROMISC) != 0);
1060         allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
1061
1062         sg_init_one(sg, &promisc, sizeof(promisc));
1063
1064         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1065                                   VIRTIO_NET_CTRL_RX_PROMISC, sg))
1066                 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
1067                          promisc ? "en" : "dis");
1068
1069         sg_init_one(sg, &allmulti, sizeof(allmulti));
1070
1071         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1072                                   VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
1073                 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
1074                          allmulti ? "en" : "dis");
1075
1076         uc_count = netdev_uc_count(dev);
1077         mc_count = netdev_mc_count(dev);
1078         /* MAC filter - use one buffer for both lists */
1079         buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
1080                       (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
1081         mac_data = buf;
1082         if (!buf)
1083                 return;
1084
1085         sg_init_table(sg, 2);
1086
1087         /* Store the unicast list and count in the front of the buffer */
1088         mac_data->entries = uc_count;
1089         i = 0;
1090         netdev_for_each_uc_addr(ha, dev)
1091                 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1092
1093         sg_set_buf(&sg[0], mac_data,
1094                    sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
1095
1096         /* multicast list and count fill the end */
1097         mac_data = (void *)&mac_data->macs[uc_count][0];
1098
1099         mac_data->entries = mc_count;
1100         i = 0;
1101         netdev_for_each_mc_addr(ha, dev)
1102                 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1103
1104         sg_set_buf(&sg[1], mac_data,
1105                    sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
1106
1107         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1108                                   VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
1109                 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
1110
1111         kfree(buf);
1112 }
1113
1114 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
1115                                    __be16 proto, u16 vid)
1116 {
1117         struct virtnet_info *vi = netdev_priv(dev);
1118         struct scatterlist sg;
1119
1120         sg_init_one(&sg, &vid, sizeof(vid));
1121
1122         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1123                                   VIRTIO_NET_CTRL_VLAN_ADD, &sg))
1124                 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
1125         return 0;
1126 }
1127
1128 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
1129                                     __be16 proto, u16 vid)
1130 {
1131         struct virtnet_info *vi = netdev_priv(dev);
1132         struct scatterlist sg;
1133
1134         sg_init_one(&sg, &vid, sizeof(vid));
1135
1136         if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1137                                   VIRTIO_NET_CTRL_VLAN_DEL, &sg))
1138                 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
1139         return 0;
1140 }
1141
1142 static void virtnet_clean_affinity(struct virtnet_info *vi, long hcpu)
1143 {
1144         int i;
1145
1146         if (vi->affinity_hint_set) {
1147                 for (i = 0; i < vi->max_queue_pairs; i++) {
1148                         virtqueue_set_affinity(vi->rq[i].vq, -1);
1149                         virtqueue_set_affinity(vi->sq[i].vq, -1);
1150                 }
1151
1152                 vi->affinity_hint_set = false;
1153         }
1154 }
1155
1156 static void virtnet_set_affinity(struct virtnet_info *vi)
1157 {
1158         int i;
1159         int cpu;
1160
1161         /* In multiqueue mode, when the number of cpu is equal to the number of
1162          * queue pairs, we let the queue pairs to be private to one cpu by
1163          * setting the affinity hint to eliminate the contention.
1164          */
1165         if (vi->curr_queue_pairs == 1 ||
1166             vi->max_queue_pairs != num_online_cpus()) {
1167                 virtnet_clean_affinity(vi, -1);
1168                 return;
1169         }
1170
1171         i = 0;
1172         for_each_online_cpu(cpu) {
1173                 virtqueue_set_affinity(vi->rq[i].vq, cpu);
1174                 virtqueue_set_affinity(vi->sq[i].vq, cpu);
1175                 netif_set_xps_queue(vi->dev, cpumask_of(cpu), i);
1176                 i++;
1177         }
1178
1179         vi->affinity_hint_set = true;
1180 }
1181
1182 static int virtnet_cpu_callback(struct notifier_block *nfb,
1183                                 unsigned long action, void *hcpu)
1184 {
1185         struct virtnet_info *vi = container_of(nfb, struct virtnet_info, nb);
1186
1187         switch(action & ~CPU_TASKS_FROZEN) {
1188         case CPU_ONLINE:
1189         case CPU_DOWN_FAILED:
1190         case CPU_DEAD:
1191                 virtnet_set_affinity(vi);
1192                 break;
1193         case CPU_DOWN_PREPARE:
1194                 virtnet_clean_affinity(vi, (long)hcpu);
1195                 break;
1196         default:
1197                 break;
1198         }
1199
1200         return NOTIFY_OK;
1201 }
1202
1203 static void virtnet_get_ringparam(struct net_device *dev,
1204                                 struct ethtool_ringparam *ring)
1205 {
1206         struct virtnet_info *vi = netdev_priv(dev);
1207
1208         ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
1209         ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
1210         ring->rx_pending = ring->rx_max_pending;
1211         ring->tx_pending = ring->tx_max_pending;
1212 }
1213
1214
1215 static void virtnet_get_drvinfo(struct net_device *dev,
1216                                 struct ethtool_drvinfo *info)
1217 {
1218         struct virtnet_info *vi = netdev_priv(dev);
1219         struct virtio_device *vdev = vi->vdev;
1220
1221         strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
1222         strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
1223         strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
1224
1225 }
1226
1227 /* TODO: Eliminate OOO packets during switching */
1228 static int virtnet_set_channels(struct net_device *dev,
1229                                 struct ethtool_channels *channels)
1230 {
1231         struct virtnet_info *vi = netdev_priv(dev);
1232         u16 queue_pairs = channels->combined_count;
1233         int err;
1234
1235         /* We don't support separate rx/tx channels.
1236          * We don't allow setting 'other' channels.
1237          */
1238         if (channels->rx_count || channels->tx_count || channels->other_count)
1239                 return -EINVAL;
1240
1241         if (queue_pairs > vi->max_queue_pairs)
1242                 return -EINVAL;
1243
1244         get_online_cpus();
1245         err = virtnet_set_queues(vi, queue_pairs);
1246         if (!err) {
1247                 netif_set_real_num_tx_queues(dev, queue_pairs);
1248                 netif_set_real_num_rx_queues(dev, queue_pairs);
1249
1250                 virtnet_set_affinity(vi);
1251         }
1252         put_online_cpus();
1253
1254         return err;
1255 }
1256
1257 static void virtnet_get_channels(struct net_device *dev,
1258                                  struct ethtool_channels *channels)
1259 {
1260         struct virtnet_info *vi = netdev_priv(dev);
1261
1262         channels->combined_count = vi->curr_queue_pairs;
1263         channels->max_combined = vi->max_queue_pairs;
1264         channels->max_other = 0;
1265         channels->rx_count = 0;
1266         channels->tx_count = 0;
1267         channels->other_count = 0;
1268 }
1269
1270 static const struct ethtool_ops virtnet_ethtool_ops = {
1271         .get_drvinfo = virtnet_get_drvinfo,
1272         .get_link = ethtool_op_get_link,
1273         .get_ringparam = virtnet_get_ringparam,
1274         .set_channels = virtnet_set_channels,
1275         .get_channels = virtnet_get_channels,
1276 };
1277
1278 #define MIN_MTU 68
1279 #define MAX_MTU 65535
1280
1281 static int virtnet_change_mtu(struct net_device *dev, int new_mtu)
1282 {
1283         if (new_mtu < MIN_MTU || new_mtu > MAX_MTU)
1284                 return -EINVAL;
1285         dev->mtu = new_mtu;
1286         return 0;
1287 }
1288
1289 static const struct net_device_ops virtnet_netdev = {
1290         .ndo_open            = virtnet_open,
1291         .ndo_stop            = virtnet_close,
1292         .ndo_start_xmit      = start_xmit,
1293         .ndo_validate_addr   = eth_validate_addr,
1294         .ndo_set_mac_address = virtnet_set_mac_address,
1295         .ndo_set_rx_mode     = virtnet_set_rx_mode,
1296         .ndo_change_mtu      = virtnet_change_mtu,
1297         .ndo_get_stats64     = virtnet_stats,
1298         .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
1299         .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
1300 #ifdef CONFIG_NET_POLL_CONTROLLER
1301         .ndo_poll_controller = virtnet_netpoll,
1302 #endif
1303 };
1304
1305 static void virtnet_config_changed_work(struct work_struct *work)
1306 {
1307         struct virtnet_info *vi =
1308                 container_of(work, struct virtnet_info, config_work);
1309         u16 v;
1310
1311         mutex_lock(&vi->config_lock);
1312         if (!vi->config_enable)
1313                 goto done;
1314
1315         if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
1316                                  struct virtio_net_config, status, &v) < 0)
1317                 goto done;
1318
1319         if (v & VIRTIO_NET_S_ANNOUNCE) {
1320                 netdev_notify_peers(vi->dev);
1321                 virtnet_ack_link_announce(vi);
1322         }
1323
1324         /* Ignore unknown (future) status bits */
1325         v &= VIRTIO_NET_S_LINK_UP;
1326
1327         if (vi->status == v)
1328                 goto done;
1329
1330         vi->status = v;
1331
1332         if (vi->status & VIRTIO_NET_S_LINK_UP) {
1333                 netif_carrier_on(vi->dev);
1334                 netif_tx_wake_all_queues(vi->dev);
1335         } else {
1336                 netif_carrier_off(vi->dev);
1337                 netif_tx_stop_all_queues(vi->dev);
1338         }
1339 done:
1340         mutex_unlock(&vi->config_lock);
1341 }
1342
1343 static void virtnet_config_changed(struct virtio_device *vdev)
1344 {
1345         struct virtnet_info *vi = vdev->priv;
1346
1347         schedule_work(&vi->config_work);
1348 }
1349
1350 static void virtnet_free_queues(struct virtnet_info *vi)
1351 {
1352         int i;
1353
1354         for (i = 0; i < vi->max_queue_pairs; i++)
1355                 netif_napi_del(&vi->rq[i].napi);
1356
1357         kfree(vi->rq);
1358         kfree(vi->sq);
1359 }
1360
1361 static void free_receive_bufs(struct virtnet_info *vi)
1362 {
1363         int i;
1364
1365         for (i = 0; i < vi->max_queue_pairs; i++) {
1366                 while (vi->rq[i].pages)
1367                         __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
1368         }
1369 }
1370
1371 static void free_unused_bufs(struct virtnet_info *vi)
1372 {
1373         void *buf;
1374         int i;
1375
1376         for (i = 0; i < vi->max_queue_pairs; i++) {
1377                 struct virtqueue *vq = vi->sq[i].vq;
1378                 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
1379                         dev_kfree_skb(buf);
1380         }
1381
1382         for (i = 0; i < vi->max_queue_pairs; i++) {
1383                 struct virtqueue *vq = vi->rq[i].vq;
1384
1385                 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
1386                         if (vi->mergeable_rx_bufs)
1387                                 put_page(virt_to_head_page(buf));
1388                         else if (vi->big_packets)
1389                                 give_pages(&vi->rq[i], buf);
1390                         else
1391                                 dev_kfree_skb(buf);
1392                 }
1393         }
1394 }
1395
1396 static void virtnet_del_vqs(struct virtnet_info *vi)
1397 {
1398         struct virtio_device *vdev = vi->vdev;
1399
1400         virtnet_clean_affinity(vi, -1);
1401
1402         vdev->config->del_vqs(vdev);
1403
1404         virtnet_free_queues(vi);
1405 }
1406
1407 static int virtnet_find_vqs(struct virtnet_info *vi)
1408 {
1409         vq_callback_t **callbacks;
1410         struct virtqueue **vqs;
1411         int ret = -ENOMEM;
1412         int i, total_vqs;
1413         const char **names;
1414
1415         /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
1416          * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
1417          * possible control vq.
1418          */
1419         total_vqs = vi->max_queue_pairs * 2 +
1420                     virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
1421
1422         /* Allocate space for find_vqs parameters */
1423         vqs = kzalloc(total_vqs * sizeof(*vqs), GFP_KERNEL);
1424         if (!vqs)
1425                 goto err_vq;
1426         callbacks = kmalloc(total_vqs * sizeof(*callbacks), GFP_KERNEL);
1427         if (!callbacks)
1428                 goto err_callback;
1429         names = kmalloc(total_vqs * sizeof(*names), GFP_KERNEL);
1430         if (!names)
1431                 goto err_names;
1432
1433         /* Parameters for control virtqueue, if any */
1434         if (vi->has_cvq) {
1435                 callbacks[total_vqs - 1] = NULL;
1436                 names[total_vqs - 1] = "control";
1437         }
1438
1439         /* Allocate/initialize parameters for send/receive virtqueues */
1440         for (i = 0; i < vi->max_queue_pairs; i++) {
1441                 callbacks[rxq2vq(i)] = skb_recv_done;
1442                 callbacks[txq2vq(i)] = skb_xmit_done;
1443                 sprintf(vi->rq[i].name, "input.%d", i);
1444                 sprintf(vi->sq[i].name, "output.%d", i);
1445                 names[rxq2vq(i)] = vi->rq[i].name;
1446                 names[txq2vq(i)] = vi->sq[i].name;
1447         }
1448
1449         ret = vi->vdev->config->find_vqs(vi->vdev, total_vqs, vqs, callbacks,
1450                                          names);
1451         if (ret)
1452                 goto err_find;
1453
1454         if (vi->has_cvq) {
1455                 vi->cvq = vqs[total_vqs - 1];
1456                 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
1457                         vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
1458         }
1459
1460         for (i = 0; i < vi->max_queue_pairs; i++) {
1461                 vi->rq[i].vq = vqs[rxq2vq(i)];
1462                 vi->sq[i].vq = vqs[txq2vq(i)];
1463         }
1464
1465         kfree(names);
1466         kfree(callbacks);
1467         kfree(vqs);
1468
1469         return 0;
1470
1471 err_find:
1472         kfree(names);
1473 err_names:
1474         kfree(callbacks);
1475 err_callback:
1476         kfree(vqs);
1477 err_vq:
1478         return ret;
1479 }
1480
1481 static int virtnet_alloc_queues(struct virtnet_info *vi)
1482 {
1483         int i;
1484
1485         vi->sq = kzalloc(sizeof(*vi->sq) * vi->max_queue_pairs, GFP_KERNEL);
1486         if (!vi->sq)
1487                 goto err_sq;
1488         vi->rq = kzalloc(sizeof(*vi->rq) * vi->max_queue_pairs, GFP_KERNEL);
1489         if (!vi->rq)
1490                 goto err_rq;
1491
1492         INIT_DELAYED_WORK(&vi->refill, refill_work);
1493         for (i = 0; i < vi->max_queue_pairs; i++) {
1494                 vi->rq[i].pages = NULL;
1495                 netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
1496                                napi_weight);
1497
1498                 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
1499                 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
1500         }
1501
1502         return 0;
1503
1504 err_rq:
1505         kfree(vi->sq);
1506 err_sq:
1507         return -ENOMEM;
1508 }
1509
1510 static int init_vqs(struct virtnet_info *vi)
1511 {
1512         int ret;
1513
1514         /* Allocate send & receive queues */
1515         ret = virtnet_alloc_queues(vi);
1516         if (ret)
1517                 goto err;
1518
1519         ret = virtnet_find_vqs(vi);
1520         if (ret)
1521                 goto err_free;
1522
1523         get_online_cpus();
1524         virtnet_set_affinity(vi);
1525         put_online_cpus();
1526
1527         return 0;
1528
1529 err_free:
1530         virtnet_free_queues(vi);
1531 err:
1532         return ret;
1533 }
1534
1535 static int virtnet_probe(struct virtio_device *vdev)
1536 {
1537         int i, err;
1538         struct net_device *dev;
1539         struct virtnet_info *vi;
1540         u16 max_queue_pairs;
1541
1542         /* Find if host supports multiqueue virtio_net device */
1543         err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
1544                                    struct virtio_net_config,
1545                                    max_virtqueue_pairs, &max_queue_pairs);
1546
1547         /* We need at least 2 queue's */
1548         if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
1549             max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
1550             !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
1551                 max_queue_pairs = 1;
1552
1553         /* Allocate ourselves a network device with room for our info */
1554         dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
1555         if (!dev)
1556                 return -ENOMEM;
1557
1558         /* Set up network device as normal. */
1559         dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
1560         dev->netdev_ops = &virtnet_netdev;
1561         dev->features = NETIF_F_HIGHDMA;
1562
1563         SET_ETHTOOL_OPS(dev, &virtnet_ethtool_ops);
1564         SET_NETDEV_DEV(dev, &vdev->dev);
1565
1566         /* Do we support "hardware" checksums? */
1567         if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
1568                 /* This opens up the world of extra features. */
1569                 dev->hw_features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
1570                 if (csum)
1571                         dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
1572
1573                 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
1574                         dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
1575                                 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
1576                 }
1577                 /* Individual feature bits: what can host handle? */
1578                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
1579                         dev->hw_features |= NETIF_F_TSO;
1580                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
1581                         dev->hw_features |= NETIF_F_TSO6;
1582                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
1583                         dev->hw_features |= NETIF_F_TSO_ECN;
1584                 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
1585                         dev->hw_features |= NETIF_F_UFO;
1586
1587                 if (gso)
1588                         dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
1589                 /* (!csum && gso) case will be fixed by register_netdev() */
1590         }
1591         if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
1592                 dev->features |= NETIF_F_RXCSUM;
1593
1594         dev->vlan_features = dev->features;
1595
1596         /* Configuration may specify what MAC to use.  Otherwise random. */
1597         if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
1598                 virtio_cread_bytes(vdev,
1599                                    offsetof(struct virtio_net_config, mac),
1600                                    dev->dev_addr, dev->addr_len);
1601         else
1602                 eth_hw_addr_random(dev);
1603
1604         /* Set up our device-specific information */
1605         vi = netdev_priv(dev);
1606         vi->dev = dev;
1607         vi->vdev = vdev;
1608         vdev->priv = vi;
1609         vi->stats = alloc_percpu(struct virtnet_stats);
1610         err = -ENOMEM;
1611         if (vi->stats == NULL)
1612                 goto free;
1613
1614         for_each_possible_cpu(i) {
1615                 struct virtnet_stats *virtnet_stats;
1616                 virtnet_stats = per_cpu_ptr(vi->stats, i);
1617                 u64_stats_init(&virtnet_stats->tx_syncp);
1618                 u64_stats_init(&virtnet_stats->rx_syncp);
1619         }
1620
1621         mutex_init(&vi->config_lock);
1622         vi->config_enable = true;
1623         INIT_WORK(&vi->config_work, virtnet_config_changed_work);
1624
1625         /* If we can receive ANY GSO packets, we must allocate large ones. */
1626         if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
1627             virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
1628             virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN))
1629                 vi->big_packets = true;
1630
1631         if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
1632                 vi->mergeable_rx_bufs = true;
1633
1634         if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT))
1635                 vi->any_header_sg = true;
1636
1637         if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
1638                 vi->has_cvq = true;
1639
1640         /* Use single tx/rx queue pair as default */
1641         vi->curr_queue_pairs = 1;
1642         vi->max_queue_pairs = max_queue_pairs;
1643
1644         /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
1645         err = init_vqs(vi);
1646         if (err)
1647                 goto free_stats;
1648
1649         netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
1650         netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
1651
1652         err = register_netdev(dev);
1653         if (err) {
1654                 pr_debug("virtio_net: registering device failed\n");
1655                 goto free_vqs;
1656         }
1657
1658         /* Last of all, set up some receive buffers. */
1659         for (i = 0; i < vi->curr_queue_pairs; i++) {
1660                 try_fill_recv(&vi->rq[i], GFP_KERNEL);
1661
1662                 /* If we didn't even get one input buffer, we're useless. */
1663                 if (vi->rq[i].vq->num_free ==
1664                     virtqueue_get_vring_size(vi->rq[i].vq)) {
1665                         free_unused_bufs(vi);
1666                         err = -ENOMEM;
1667                         goto free_recv_bufs;
1668                 }
1669         }
1670
1671         vi->nb.notifier_call = &virtnet_cpu_callback;
1672         err = register_hotcpu_notifier(&vi->nb);
1673         if (err) {
1674                 pr_debug("virtio_net: registering cpu notifier failed\n");
1675                 goto free_recv_bufs;
1676         }
1677
1678         /* Assume link up if device can't report link status,
1679            otherwise get link status from config. */
1680         if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
1681                 netif_carrier_off(dev);
1682                 schedule_work(&vi->config_work);
1683         } else {
1684                 vi->status = VIRTIO_NET_S_LINK_UP;
1685                 netif_carrier_on(dev);
1686         }
1687
1688         pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
1689                  dev->name, max_queue_pairs);
1690
1691         return 0;
1692
1693 free_recv_bufs:
1694         free_receive_bufs(vi);
1695         unregister_netdev(dev);
1696 free_vqs:
1697         cancel_delayed_work_sync(&vi->refill);
1698         virtnet_del_vqs(vi);
1699         if (vi->alloc_frag.page)
1700                 put_page(vi->alloc_frag.page);
1701 free_stats:
1702         free_percpu(vi->stats);
1703 free:
1704         free_netdev(dev);
1705         return err;
1706 }
1707
1708 static void remove_vq_common(struct virtnet_info *vi)
1709 {
1710         vi->vdev->config->reset(vi->vdev);
1711
1712         /* Free unused buffers in both send and recv, if any. */
1713         free_unused_bufs(vi);
1714
1715         free_receive_bufs(vi);
1716
1717         virtnet_del_vqs(vi);
1718 }
1719
1720 static void virtnet_remove(struct virtio_device *vdev)
1721 {
1722         struct virtnet_info *vi = vdev->priv;
1723
1724         unregister_hotcpu_notifier(&vi->nb);
1725
1726         /* Prevent config work handler from accessing the device. */
1727         mutex_lock(&vi->config_lock);
1728         vi->config_enable = false;
1729         mutex_unlock(&vi->config_lock);
1730
1731         unregister_netdev(vi->dev);
1732
1733         remove_vq_common(vi);
1734         if (vi->alloc_frag.page)
1735                 put_page(vi->alloc_frag.page);
1736
1737         flush_work(&vi->config_work);
1738
1739         free_percpu(vi->stats);
1740         free_netdev(vi->dev);
1741 }
1742
1743 #ifdef CONFIG_PM_SLEEP
1744 static int virtnet_freeze(struct virtio_device *vdev)
1745 {
1746         struct virtnet_info *vi = vdev->priv;
1747         int i;
1748
1749         unregister_hotcpu_notifier(&vi->nb);
1750
1751         /* Prevent config work handler from accessing the device */
1752         mutex_lock(&vi->config_lock);
1753         vi->config_enable = false;
1754         mutex_unlock(&vi->config_lock);
1755
1756         netif_device_detach(vi->dev);
1757         cancel_delayed_work_sync(&vi->refill);
1758
1759         if (netif_running(vi->dev))
1760                 for (i = 0; i < vi->max_queue_pairs; i++) {
1761                         napi_disable(&vi->rq[i].napi);
1762                         netif_napi_del(&vi->rq[i].napi);
1763                 }
1764
1765         remove_vq_common(vi);
1766
1767         flush_work(&vi->config_work);
1768
1769         return 0;
1770 }
1771
1772 static int virtnet_restore(struct virtio_device *vdev)
1773 {
1774         struct virtnet_info *vi = vdev->priv;
1775         int err, i;
1776
1777         err = init_vqs(vi);
1778         if (err)
1779                 return err;
1780
1781         if (netif_running(vi->dev)) {
1782                 for (i = 0; i < vi->curr_queue_pairs; i++)
1783                         if (!try_fill_recv(&vi->rq[i], GFP_KERNEL))
1784                                 schedule_delayed_work(&vi->refill, 0);
1785
1786                 for (i = 0; i < vi->max_queue_pairs; i++)
1787                         virtnet_napi_enable(&vi->rq[i]);
1788         }
1789
1790         netif_device_attach(vi->dev);
1791
1792         mutex_lock(&vi->config_lock);
1793         vi->config_enable = true;
1794         mutex_unlock(&vi->config_lock);
1795
1796         rtnl_lock();
1797         virtnet_set_queues(vi, vi->curr_queue_pairs);
1798         rtnl_unlock();
1799
1800         err = register_hotcpu_notifier(&vi->nb);
1801         if (err)
1802                 return err;
1803
1804         return 0;
1805 }
1806 #endif
1807
1808 static struct virtio_device_id id_table[] = {
1809         { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
1810         { 0 },
1811 };
1812
1813 static unsigned int features[] = {
1814         VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM,
1815         VIRTIO_NET_F_GSO, VIRTIO_NET_F_MAC,
1816         VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6,
1817         VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6,
1818         VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO,
1819         VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ,
1820         VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN,
1821         VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ,
1822         VIRTIO_NET_F_CTRL_MAC_ADDR,
1823         VIRTIO_F_ANY_LAYOUT,
1824 };
1825
1826 static struct virtio_driver virtio_net_driver = {
1827         .feature_table = features,
1828         .feature_table_size = ARRAY_SIZE(features),
1829         .driver.name =  KBUILD_MODNAME,
1830         .driver.owner = THIS_MODULE,
1831         .id_table =     id_table,
1832         .probe =        virtnet_probe,
1833         .remove =       virtnet_remove,
1834         .config_changed = virtnet_config_changed,
1835 #ifdef CONFIG_PM_SLEEP
1836         .freeze =       virtnet_freeze,
1837         .restore =      virtnet_restore,
1838 #endif
1839 };
1840
1841 module_virtio_driver(virtio_net_driver);
1842
1843 MODULE_DEVICE_TABLE(virtio, id_table);
1844 MODULE_DESCRIPTION("Virtio network driver");
1845 MODULE_LICENSE("GPL");