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