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