]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - drivers/net/virtio_net.c
5ef484dd30e76bc6857d4cbcaaee009bc1e0de91
[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 unsigned int received;
1213 bool xdp_xmit = false;
1214
1215 virtnet_poll_cleantx(rq);
1216
1217 received = virtnet_receive(rq, budget, &xdp_xmit);
1218
1219 /* Out of packets? */
1220 if (received < budget)
1221 virtqueue_napi_complete(napi, rq->vq, received);
1222
1223 if (xdp_xmit)
1224 xdp_do_flush_map();
1225
1226 return received;
1227 }
1228
1229 static int virtnet_open(struct net_device *dev)
1230 {
1231 struct virtnet_info *vi = netdev_priv(dev);
1232 int i;
1233
1234 for (i = 0; i < vi->max_queue_pairs; i++) {
1235 if (i < vi->curr_queue_pairs)
1236 /* Make sure we have some buffers: if oom use wq. */
1237 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1238 schedule_delayed_work(&vi->refill, 0);
1239 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1240 virtnet_napi_tx_enable(vi, vi->sq[i].vq, &vi->sq[i].napi);
1241 }
1242
1243 return 0;
1244 }
1245
1246 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1247 {
1248 struct send_queue *sq = container_of(napi, struct send_queue, napi);
1249 struct virtnet_info *vi = sq->vq->vdev->priv;
1250 struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, vq2txq(sq->vq));
1251
1252 __netif_tx_lock(txq, raw_smp_processor_id());
1253 free_old_xmit_skbs(sq);
1254 __netif_tx_unlock(txq);
1255
1256 virtqueue_napi_complete(napi, sq->vq, 0);
1257
1258 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1259 netif_tx_wake_queue(txq);
1260
1261 return 0;
1262 }
1263
1264 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1265 {
1266 struct virtio_net_hdr_mrg_rxbuf *hdr;
1267 const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1268 struct virtnet_info *vi = sq->vq->vdev->priv;
1269 int num_sg;
1270 unsigned hdr_len = vi->hdr_len;
1271 bool can_push;
1272
1273 pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1274
1275 can_push = vi->any_header_sg &&
1276 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1277 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1278 /* Even if we can, don't push here yet as this would skew
1279 * csum_start offset below. */
1280 if (can_push)
1281 hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1282 else
1283 hdr = skb_vnet_hdr(skb);
1284
1285 if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1286 virtio_is_little_endian(vi->vdev), false))
1287 BUG();
1288
1289 if (vi->mergeable_rx_bufs)
1290 hdr->num_buffers = 0;
1291
1292 sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1293 if (can_push) {
1294 __skb_push(skb, hdr_len);
1295 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1296 if (unlikely(num_sg < 0))
1297 return num_sg;
1298 /* Pull header back to avoid skew in tx bytes calculations. */
1299 __skb_pull(skb, hdr_len);
1300 } else {
1301 sg_set_buf(sq->sg, hdr, hdr_len);
1302 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
1303 if (unlikely(num_sg < 0))
1304 return num_sg;
1305 num_sg++;
1306 }
1307 return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1308 }
1309
1310 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1311 {
1312 struct virtnet_info *vi = netdev_priv(dev);
1313 int qnum = skb_get_queue_mapping(skb);
1314 struct send_queue *sq = &vi->sq[qnum];
1315 int err;
1316 struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1317 bool kick = !skb->xmit_more;
1318 bool use_napi = sq->napi.weight;
1319
1320 /* Free up any pending old buffers before queueing new ones. */
1321 free_old_xmit_skbs(sq);
1322
1323 if (use_napi && kick)
1324 virtqueue_enable_cb_delayed(sq->vq);
1325
1326 /* timestamp packet in software */
1327 skb_tx_timestamp(skb);
1328
1329 /* Try to transmit */
1330 err = xmit_skb(sq, skb);
1331
1332 /* This should not happen! */
1333 if (unlikely(err)) {
1334 dev->stats.tx_fifo_errors++;
1335 if (net_ratelimit())
1336 dev_warn(&dev->dev,
1337 "Unexpected TXQ (%d) queue failure: %d\n", qnum, err);
1338 dev->stats.tx_dropped++;
1339 dev_kfree_skb_any(skb);
1340 return NETDEV_TX_OK;
1341 }
1342
1343 /* Don't wait up for transmitted skbs to be freed. */
1344 if (!use_napi) {
1345 skb_orphan(skb);
1346 nf_reset(skb);
1347 }
1348
1349 /* If running out of space, stop queue to avoid getting packets that we
1350 * are then unable to transmit.
1351 * An alternative would be to force queuing layer to requeue the skb by
1352 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
1353 * returned in a normal path of operation: it means that driver is not
1354 * maintaining the TX queue stop/start state properly, and causes
1355 * the stack to do a non-trivial amount of useless work.
1356 * Since most packets only take 1 or 2 ring slots, stopping the queue
1357 * early means 16 slots are typically wasted.
1358 */
1359 if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1360 netif_stop_subqueue(dev, qnum);
1361 if (!use_napi &&
1362 unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1363 /* More just got used, free them then recheck. */
1364 free_old_xmit_skbs(sq);
1365 if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1366 netif_start_subqueue(dev, qnum);
1367 virtqueue_disable_cb(sq->vq);
1368 }
1369 }
1370 }
1371
1372 if (kick || netif_xmit_stopped(txq))
1373 virtqueue_kick(sq->vq);
1374
1375 return NETDEV_TX_OK;
1376 }
1377
1378 /*
1379 * Send command via the control virtqueue and check status. Commands
1380 * supported by the hypervisor, as indicated by feature bits, should
1381 * never fail unless improperly formatted.
1382 */
1383 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1384 struct scatterlist *out)
1385 {
1386 struct scatterlist *sgs[4], hdr, stat;
1387 unsigned out_num = 0, tmp;
1388
1389 /* Caller should know better */
1390 BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1391
1392 vi->ctrl->status = ~0;
1393 vi->ctrl->hdr.class = class;
1394 vi->ctrl->hdr.cmd = cmd;
1395 /* Add header */
1396 sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
1397 sgs[out_num++] = &hdr;
1398
1399 if (out)
1400 sgs[out_num++] = out;
1401
1402 /* Add return status. */
1403 sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
1404 sgs[out_num] = &stat;
1405
1406 BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1407 virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1408
1409 if (unlikely(!virtqueue_kick(vi->cvq)))
1410 return vi->ctrl->status == VIRTIO_NET_OK;
1411
1412 /* Spin for a response, the kick causes an ioport write, trapping
1413 * into the hypervisor, so the request should be handled immediately.
1414 */
1415 while (!virtqueue_get_buf(vi->cvq, &tmp) &&
1416 !virtqueue_is_broken(vi->cvq))
1417 cpu_relax();
1418
1419 return vi->ctrl->status == VIRTIO_NET_OK;
1420 }
1421
1422 static int virtnet_set_mac_address(struct net_device *dev, void *p)
1423 {
1424 struct virtnet_info *vi = netdev_priv(dev);
1425 struct virtio_device *vdev = vi->vdev;
1426 int ret;
1427 struct sockaddr *addr;
1428 struct scatterlist sg;
1429
1430 addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
1431 if (!addr)
1432 return -ENOMEM;
1433
1434 ret = eth_prepare_mac_addr_change(dev, addr);
1435 if (ret)
1436 goto out;
1437
1438 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1439 sg_init_one(&sg, addr->sa_data, dev->addr_len);
1440 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1441 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
1442 dev_warn(&vdev->dev,
1443 "Failed to set mac address by vq command.\n");
1444 ret = -EINVAL;
1445 goto out;
1446 }
1447 } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
1448 !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1449 unsigned int i;
1450
1451 /* Naturally, this has an atomicity problem. */
1452 for (i = 0; i < dev->addr_len; i++)
1453 virtio_cwrite8(vdev,
1454 offsetof(struct virtio_net_config, mac) +
1455 i, addr->sa_data[i]);
1456 }
1457
1458 eth_commit_mac_addr_change(dev, p);
1459 ret = 0;
1460
1461 out:
1462 kfree(addr);
1463 return ret;
1464 }
1465
1466 static void virtnet_stats(struct net_device *dev,
1467 struct rtnl_link_stats64 *tot)
1468 {
1469 struct virtnet_info *vi = netdev_priv(dev);
1470 int cpu;
1471 unsigned int start;
1472
1473 for_each_possible_cpu(cpu) {
1474 struct virtnet_stats *stats = per_cpu_ptr(vi->stats, cpu);
1475 u64 tpackets, tbytes, rpackets, rbytes;
1476
1477 do {
1478 start = u64_stats_fetch_begin_irq(&stats->tx_syncp);
1479 tpackets = stats->tx_packets;
1480 tbytes = stats->tx_bytes;
1481 } while (u64_stats_fetch_retry_irq(&stats->tx_syncp, start));
1482
1483 do {
1484 start = u64_stats_fetch_begin_irq(&stats->rx_syncp);
1485 rpackets = stats->rx_packets;
1486 rbytes = stats->rx_bytes;
1487 } while (u64_stats_fetch_retry_irq(&stats->rx_syncp, start));
1488
1489 tot->rx_packets += rpackets;
1490 tot->tx_packets += tpackets;
1491 tot->rx_bytes += rbytes;
1492 tot->tx_bytes += tbytes;
1493 }
1494
1495 tot->tx_dropped = dev->stats.tx_dropped;
1496 tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
1497 tot->rx_dropped = dev->stats.rx_dropped;
1498 tot->rx_length_errors = dev->stats.rx_length_errors;
1499 tot->rx_frame_errors = dev->stats.rx_frame_errors;
1500 }
1501
1502 #ifdef CONFIG_NET_POLL_CONTROLLER
1503 static void virtnet_netpoll(struct net_device *dev)
1504 {
1505 struct virtnet_info *vi = netdev_priv(dev);
1506 int i;
1507
1508 for (i = 0; i < vi->curr_queue_pairs; i++)
1509 napi_schedule(&vi->rq[i].napi);
1510 }
1511 #endif
1512
1513 static void virtnet_ack_link_announce(struct virtnet_info *vi)
1514 {
1515 rtnl_lock();
1516 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
1517 VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
1518 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
1519 rtnl_unlock();
1520 }
1521
1522 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1523 {
1524 struct scatterlist sg;
1525 struct net_device *dev = vi->dev;
1526
1527 if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
1528 return 0;
1529
1530 vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
1531 sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
1532
1533 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
1534 VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
1535 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
1536 queue_pairs);
1537 return -EINVAL;
1538 } else {
1539 vi->curr_queue_pairs = queue_pairs;
1540 /* virtnet_open() will refill when device is going to up. */
1541 if (dev->flags & IFF_UP)
1542 schedule_delayed_work(&vi->refill, 0);
1543 }
1544
1545 return 0;
1546 }
1547
1548 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1549 {
1550 int err;
1551
1552 rtnl_lock();
1553 err = _virtnet_set_queues(vi, queue_pairs);
1554 rtnl_unlock();
1555 return err;
1556 }
1557
1558 static int virtnet_close(struct net_device *dev)
1559 {
1560 struct virtnet_info *vi = netdev_priv(dev);
1561 int i;
1562
1563 /* Make sure refill_work doesn't re-enable napi! */
1564 cancel_delayed_work_sync(&vi->refill);
1565
1566 for (i = 0; i < vi->max_queue_pairs; i++) {
1567 napi_disable(&vi->rq[i].napi);
1568 virtnet_napi_tx_disable(&vi->sq[i].napi);
1569 }
1570
1571 return 0;
1572 }
1573
1574 static void virtnet_set_rx_mode(struct net_device *dev)
1575 {
1576 struct virtnet_info *vi = netdev_priv(dev);
1577 struct scatterlist sg[2];
1578 struct virtio_net_ctrl_mac *mac_data;
1579 struct netdev_hw_addr *ha;
1580 int uc_count;
1581 int mc_count;
1582 void *buf;
1583 int i;
1584
1585 /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
1586 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
1587 return;
1588
1589 vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
1590 vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
1591
1592 sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
1593
1594 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1595 VIRTIO_NET_CTRL_RX_PROMISC, sg))
1596 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
1597 vi->ctrl->promisc ? "en" : "dis");
1598
1599 sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
1600
1601 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1602 VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
1603 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
1604 vi->ctrl->allmulti ? "en" : "dis");
1605
1606 uc_count = netdev_uc_count(dev);
1607 mc_count = netdev_mc_count(dev);
1608 /* MAC filter - use one buffer for both lists */
1609 buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
1610 (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
1611 mac_data = buf;
1612 if (!buf)
1613 return;
1614
1615 sg_init_table(sg, 2);
1616
1617 /* Store the unicast list and count in the front of the buffer */
1618 mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
1619 i = 0;
1620 netdev_for_each_uc_addr(ha, dev)
1621 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1622
1623 sg_set_buf(&sg[0], mac_data,
1624 sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
1625
1626 /* multicast list and count fill the end */
1627 mac_data = (void *)&mac_data->macs[uc_count][0];
1628
1629 mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
1630 i = 0;
1631 netdev_for_each_mc_addr(ha, dev)
1632 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1633
1634 sg_set_buf(&sg[1], mac_data,
1635 sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
1636
1637 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1638 VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
1639 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
1640
1641 kfree(buf);
1642 }
1643
1644 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
1645 __be16 proto, u16 vid)
1646 {
1647 struct virtnet_info *vi = netdev_priv(dev);
1648 struct scatterlist sg;
1649
1650 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
1651 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
1652
1653 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1654 VIRTIO_NET_CTRL_VLAN_ADD, &sg))
1655 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
1656 return 0;
1657 }
1658
1659 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
1660 __be16 proto, u16 vid)
1661 {
1662 struct virtnet_info *vi = netdev_priv(dev);
1663 struct scatterlist sg;
1664
1665 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
1666 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
1667
1668 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1669 VIRTIO_NET_CTRL_VLAN_DEL, &sg))
1670 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
1671 return 0;
1672 }
1673
1674 static void virtnet_clean_affinity(struct virtnet_info *vi, long hcpu)
1675 {
1676 int i;
1677
1678 if (vi->affinity_hint_set) {
1679 for (i = 0; i < vi->max_queue_pairs; i++) {
1680 virtqueue_set_affinity(vi->rq[i].vq, -1);
1681 virtqueue_set_affinity(vi->sq[i].vq, -1);
1682 }
1683
1684 vi->affinity_hint_set = false;
1685 }
1686 }
1687
1688 static void virtnet_set_affinity(struct virtnet_info *vi)
1689 {
1690 int i;
1691 int cpu;
1692
1693 /* In multiqueue mode, when the number of cpu is equal to the number of
1694 * queue pairs, we let the queue pairs to be private to one cpu by
1695 * setting the affinity hint to eliminate the contention.
1696 */
1697 if (vi->curr_queue_pairs == 1 ||
1698 vi->max_queue_pairs != num_online_cpus()) {
1699 virtnet_clean_affinity(vi, -1);
1700 return;
1701 }
1702
1703 i = 0;
1704 for_each_online_cpu(cpu) {
1705 virtqueue_set_affinity(vi->rq[i].vq, cpu);
1706 virtqueue_set_affinity(vi->sq[i].vq, cpu);
1707 netif_set_xps_queue(vi->dev, cpumask_of(cpu), i);
1708 i++;
1709 }
1710
1711 vi->affinity_hint_set = true;
1712 }
1713
1714 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
1715 {
1716 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1717 node);
1718 virtnet_set_affinity(vi);
1719 return 0;
1720 }
1721
1722 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
1723 {
1724 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1725 node_dead);
1726 virtnet_set_affinity(vi);
1727 return 0;
1728 }
1729
1730 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
1731 {
1732 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1733 node);
1734
1735 virtnet_clean_affinity(vi, cpu);
1736 return 0;
1737 }
1738
1739 static enum cpuhp_state virtionet_online;
1740
1741 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
1742 {
1743 int ret;
1744
1745 ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
1746 if (ret)
1747 return ret;
1748 ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
1749 &vi->node_dead);
1750 if (!ret)
1751 return ret;
1752 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
1753 return ret;
1754 }
1755
1756 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
1757 {
1758 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
1759 cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
1760 &vi->node_dead);
1761 }
1762
1763 static void virtnet_get_ringparam(struct net_device *dev,
1764 struct ethtool_ringparam *ring)
1765 {
1766 struct virtnet_info *vi = netdev_priv(dev);
1767
1768 ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
1769 ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
1770 ring->rx_pending = ring->rx_max_pending;
1771 ring->tx_pending = ring->tx_max_pending;
1772 }
1773
1774
1775 static void virtnet_get_drvinfo(struct net_device *dev,
1776 struct ethtool_drvinfo *info)
1777 {
1778 struct virtnet_info *vi = netdev_priv(dev);
1779 struct virtio_device *vdev = vi->vdev;
1780
1781 strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
1782 strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
1783 strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
1784
1785 }
1786
1787 /* TODO: Eliminate OOO packets during switching */
1788 static int virtnet_set_channels(struct net_device *dev,
1789 struct ethtool_channels *channels)
1790 {
1791 struct virtnet_info *vi = netdev_priv(dev);
1792 u16 queue_pairs = channels->combined_count;
1793 int err;
1794
1795 /* We don't support separate rx/tx channels.
1796 * We don't allow setting 'other' channels.
1797 */
1798 if (channels->rx_count || channels->tx_count || channels->other_count)
1799 return -EINVAL;
1800
1801 if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
1802 return -EINVAL;
1803
1804 /* For now we don't support modifying channels while XDP is loaded
1805 * also when XDP is loaded all RX queues have XDP programs so we only
1806 * need to check a single RX queue.
1807 */
1808 if (vi->rq[0].xdp_prog)
1809 return -EINVAL;
1810
1811 get_online_cpus();
1812 err = _virtnet_set_queues(vi, queue_pairs);
1813 if (!err) {
1814 netif_set_real_num_tx_queues(dev, queue_pairs);
1815 netif_set_real_num_rx_queues(dev, queue_pairs);
1816
1817 virtnet_set_affinity(vi);
1818 }
1819 put_online_cpus();
1820
1821 return err;
1822 }
1823
1824 static void virtnet_get_channels(struct net_device *dev,
1825 struct ethtool_channels *channels)
1826 {
1827 struct virtnet_info *vi = netdev_priv(dev);
1828
1829 channels->combined_count = vi->curr_queue_pairs;
1830 channels->max_combined = vi->max_queue_pairs;
1831 channels->max_other = 0;
1832 channels->rx_count = 0;
1833 channels->tx_count = 0;
1834 channels->other_count = 0;
1835 }
1836
1837 /* Check if the user is trying to change anything besides speed/duplex */
1838 static bool
1839 virtnet_validate_ethtool_cmd(const struct ethtool_link_ksettings *cmd)
1840 {
1841 struct ethtool_link_ksettings diff1 = *cmd;
1842 struct ethtool_link_ksettings diff2 = {};
1843
1844 /* cmd is always set so we need to clear it, validate the port type
1845 * and also without autonegotiation we can ignore advertising
1846 */
1847 diff1.base.speed = 0;
1848 diff2.base.port = PORT_OTHER;
1849 ethtool_link_ksettings_zero_link_mode(&diff1, advertising);
1850 diff1.base.duplex = 0;
1851 diff1.base.cmd = 0;
1852 diff1.base.link_mode_masks_nwords = 0;
1853
1854 return !memcmp(&diff1.base, &diff2.base, sizeof(diff1.base)) &&
1855 bitmap_empty(diff1.link_modes.supported,
1856 __ETHTOOL_LINK_MODE_MASK_NBITS) &&
1857 bitmap_empty(diff1.link_modes.advertising,
1858 __ETHTOOL_LINK_MODE_MASK_NBITS) &&
1859 bitmap_empty(diff1.link_modes.lp_advertising,
1860 __ETHTOOL_LINK_MODE_MASK_NBITS);
1861 }
1862
1863 static int virtnet_set_link_ksettings(struct net_device *dev,
1864 const struct ethtool_link_ksettings *cmd)
1865 {
1866 struct virtnet_info *vi = netdev_priv(dev);
1867 u32 speed;
1868
1869 speed = cmd->base.speed;
1870 /* don't allow custom speed and duplex */
1871 if (!ethtool_validate_speed(speed) ||
1872 !ethtool_validate_duplex(cmd->base.duplex) ||
1873 !virtnet_validate_ethtool_cmd(cmd))
1874 return -EINVAL;
1875 vi->speed = speed;
1876 vi->duplex = cmd->base.duplex;
1877
1878 return 0;
1879 }
1880
1881 static int virtnet_get_link_ksettings(struct net_device *dev,
1882 struct ethtool_link_ksettings *cmd)
1883 {
1884 struct virtnet_info *vi = netdev_priv(dev);
1885
1886 cmd->base.speed = vi->speed;
1887 cmd->base.duplex = vi->duplex;
1888 cmd->base.port = PORT_OTHER;
1889
1890 return 0;
1891 }
1892
1893 static void virtnet_init_settings(struct net_device *dev)
1894 {
1895 struct virtnet_info *vi = netdev_priv(dev);
1896
1897 vi->speed = SPEED_UNKNOWN;
1898 vi->duplex = DUPLEX_UNKNOWN;
1899 }
1900
1901 static const struct ethtool_ops virtnet_ethtool_ops = {
1902 .get_drvinfo = virtnet_get_drvinfo,
1903 .get_link = ethtool_op_get_link,
1904 .get_ringparam = virtnet_get_ringparam,
1905 .set_channels = virtnet_set_channels,
1906 .get_channels = virtnet_get_channels,
1907 .get_ts_info = ethtool_op_get_ts_info,
1908 .get_link_ksettings = virtnet_get_link_ksettings,
1909 .set_link_ksettings = virtnet_set_link_ksettings,
1910 };
1911
1912 static void virtnet_freeze_down(struct virtio_device *vdev)
1913 {
1914 struct virtnet_info *vi = vdev->priv;
1915 int i;
1916
1917 /* Make sure no work handler is accessing the device */
1918 flush_work(&vi->config_work);
1919
1920 netif_device_detach(vi->dev);
1921 netif_tx_disable(vi->dev);
1922 cancel_delayed_work_sync(&vi->refill);
1923
1924 if (netif_running(vi->dev)) {
1925 for (i = 0; i < vi->max_queue_pairs; i++) {
1926 napi_disable(&vi->rq[i].napi);
1927 virtnet_napi_tx_disable(&vi->sq[i].napi);
1928 }
1929 }
1930 }
1931
1932 static int init_vqs(struct virtnet_info *vi);
1933
1934 static int virtnet_restore_up(struct virtio_device *vdev)
1935 {
1936 struct virtnet_info *vi = vdev->priv;
1937 int err, i;
1938
1939 err = init_vqs(vi);
1940 if (err)
1941 return err;
1942
1943 virtio_device_ready(vdev);
1944
1945 if (netif_running(vi->dev)) {
1946 for (i = 0; i < vi->curr_queue_pairs; i++)
1947 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1948 schedule_delayed_work(&vi->refill, 0);
1949
1950 for (i = 0; i < vi->max_queue_pairs; i++) {
1951 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1952 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
1953 &vi->sq[i].napi);
1954 }
1955 }
1956
1957 netif_device_attach(vi->dev);
1958 return err;
1959 }
1960
1961 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
1962 {
1963 struct scatterlist sg;
1964 vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
1965
1966 sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
1967
1968 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
1969 VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
1970 dev_warn(&vi->dev->dev, "Fail to set guest offload. \n");
1971 return -EINVAL;
1972 }
1973
1974 return 0;
1975 }
1976
1977 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
1978 {
1979 u64 offloads = 0;
1980
1981 if (!vi->guest_offloads)
1982 return 0;
1983
1984 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM))
1985 offloads = 1ULL << VIRTIO_NET_F_GUEST_CSUM;
1986
1987 return virtnet_set_guest_offloads(vi, offloads);
1988 }
1989
1990 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
1991 {
1992 u64 offloads = vi->guest_offloads;
1993
1994 if (!vi->guest_offloads)
1995 return 0;
1996 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM))
1997 offloads |= 1ULL << VIRTIO_NET_F_GUEST_CSUM;
1998
1999 return virtnet_set_guest_offloads(vi, offloads);
2000 }
2001
2002 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
2003 struct netlink_ext_ack *extack)
2004 {
2005 unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
2006 struct virtnet_info *vi = netdev_priv(dev);
2007 struct bpf_prog *old_prog;
2008 u16 xdp_qp = 0, curr_qp;
2009 int i, err;
2010
2011 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
2012 && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
2013 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
2014 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
2015 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO))) {
2016 NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing LRO, disable LRO first");
2017 return -EOPNOTSUPP;
2018 }
2019
2020 if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
2021 NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
2022 return -EINVAL;
2023 }
2024
2025 if (dev->mtu > max_sz) {
2026 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
2027 netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
2028 return -EINVAL;
2029 }
2030
2031 curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
2032 if (prog)
2033 xdp_qp = nr_cpu_ids;
2034
2035 /* XDP requires extra queues for XDP_TX */
2036 if (curr_qp + xdp_qp > vi->max_queue_pairs) {
2037 NL_SET_ERR_MSG_MOD(extack, "Too few free TX rings available");
2038 netdev_warn(dev, "request %i queues but max is %i\n",
2039 curr_qp + xdp_qp, vi->max_queue_pairs);
2040 return -ENOMEM;
2041 }
2042
2043 if (prog) {
2044 prog = bpf_prog_add(prog, vi->max_queue_pairs - 1);
2045 if (IS_ERR(prog))
2046 return PTR_ERR(prog);
2047 }
2048
2049 /* Make sure NAPI is not using any XDP TX queues for RX. */
2050 if (netif_running(dev))
2051 for (i = 0; i < vi->max_queue_pairs; i++)
2052 napi_disable(&vi->rq[i].napi);
2053
2054 netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
2055 err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
2056 if (err)
2057 goto err;
2058 vi->xdp_queue_pairs = xdp_qp;
2059
2060 for (i = 0; i < vi->max_queue_pairs; i++) {
2061 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
2062 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
2063 if (i == 0) {
2064 if (!old_prog)
2065 virtnet_clear_guest_offloads(vi);
2066 if (!prog)
2067 virtnet_restore_guest_offloads(vi);
2068 }
2069 if (old_prog)
2070 bpf_prog_put(old_prog);
2071 if (netif_running(dev))
2072 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2073 }
2074
2075 return 0;
2076
2077 err:
2078 for (i = 0; i < vi->max_queue_pairs; i++)
2079 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2080 if (prog)
2081 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
2082 return err;
2083 }
2084
2085 static u32 virtnet_xdp_query(struct net_device *dev)
2086 {
2087 struct virtnet_info *vi = netdev_priv(dev);
2088 const struct bpf_prog *xdp_prog;
2089 int i;
2090
2091 for (i = 0; i < vi->max_queue_pairs; i++) {
2092 xdp_prog = rtnl_dereference(vi->rq[i].xdp_prog);
2093 if (xdp_prog)
2094 return xdp_prog->aux->id;
2095 }
2096 return 0;
2097 }
2098
2099 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
2100 {
2101 switch (xdp->command) {
2102 case XDP_SETUP_PROG:
2103 return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
2104 case XDP_QUERY_PROG:
2105 xdp->prog_id = virtnet_xdp_query(dev);
2106 xdp->prog_attached = !!xdp->prog_id;
2107 return 0;
2108 default:
2109 return -EINVAL;
2110 }
2111 }
2112
2113 static const struct net_device_ops virtnet_netdev = {
2114 .ndo_open = virtnet_open,
2115 .ndo_stop = virtnet_close,
2116 .ndo_start_xmit = start_xmit,
2117 .ndo_validate_addr = eth_validate_addr,
2118 .ndo_set_mac_address = virtnet_set_mac_address,
2119 .ndo_set_rx_mode = virtnet_set_rx_mode,
2120 .ndo_get_stats64 = virtnet_stats,
2121 .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
2122 .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
2123 #ifdef CONFIG_NET_POLL_CONTROLLER
2124 .ndo_poll_controller = virtnet_netpoll,
2125 #endif
2126 .ndo_bpf = virtnet_xdp,
2127 .ndo_xdp_xmit = virtnet_xdp_xmit,
2128 .ndo_xdp_flush = virtnet_xdp_flush,
2129 .ndo_features_check = passthru_features_check,
2130 };
2131
2132 static void virtnet_config_changed_work(struct work_struct *work)
2133 {
2134 struct virtnet_info *vi =
2135 container_of(work, struct virtnet_info, config_work);
2136 u16 v;
2137
2138 if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
2139 struct virtio_net_config, status, &v) < 0)
2140 return;
2141
2142 if (v & VIRTIO_NET_S_ANNOUNCE) {
2143 netdev_notify_peers(vi->dev);
2144 virtnet_ack_link_announce(vi);
2145 }
2146
2147 /* Ignore unknown (future) status bits */
2148 v &= VIRTIO_NET_S_LINK_UP;
2149
2150 if (vi->status == v)
2151 return;
2152
2153 vi->status = v;
2154
2155 if (vi->status & VIRTIO_NET_S_LINK_UP) {
2156 netif_carrier_on(vi->dev);
2157 netif_tx_wake_all_queues(vi->dev);
2158 } else {
2159 netif_carrier_off(vi->dev);
2160 netif_tx_stop_all_queues(vi->dev);
2161 }
2162 }
2163
2164 static void virtnet_config_changed(struct virtio_device *vdev)
2165 {
2166 struct virtnet_info *vi = vdev->priv;
2167
2168 schedule_work(&vi->config_work);
2169 }
2170
2171 static void virtnet_free_queues(struct virtnet_info *vi)
2172 {
2173 int i;
2174
2175 for (i = 0; i < vi->max_queue_pairs; i++) {
2176 napi_hash_del(&vi->rq[i].napi);
2177 netif_napi_del(&vi->rq[i].napi);
2178 netif_napi_del(&vi->sq[i].napi);
2179 }
2180
2181 /* We called napi_hash_del() before netif_napi_del(),
2182 * we need to respect an RCU grace period before freeing vi->rq
2183 */
2184 synchronize_net();
2185
2186 kfree(vi->rq);
2187 kfree(vi->sq);
2188 kfree(vi->ctrl);
2189 }
2190
2191 static void _free_receive_bufs(struct virtnet_info *vi)
2192 {
2193 struct bpf_prog *old_prog;
2194 int i;
2195
2196 for (i = 0; i < vi->max_queue_pairs; i++) {
2197 while (vi->rq[i].pages)
2198 __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
2199
2200 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
2201 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
2202 if (old_prog)
2203 bpf_prog_put(old_prog);
2204 }
2205 }
2206
2207 static void free_receive_bufs(struct virtnet_info *vi)
2208 {
2209 rtnl_lock();
2210 _free_receive_bufs(vi);
2211 rtnl_unlock();
2212 }
2213
2214 static void free_receive_page_frags(struct virtnet_info *vi)
2215 {
2216 int i;
2217 for (i = 0; i < vi->max_queue_pairs; i++)
2218 if (vi->rq[i].alloc_frag.page)
2219 put_page(vi->rq[i].alloc_frag.page);
2220 }
2221
2222 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
2223 {
2224 if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
2225 return false;
2226 else if (q < vi->curr_queue_pairs)
2227 return true;
2228 else
2229 return false;
2230 }
2231
2232 static void free_unused_bufs(struct virtnet_info *vi)
2233 {
2234 void *buf;
2235 int i;
2236
2237 for (i = 0; i < vi->max_queue_pairs; i++) {
2238 struct virtqueue *vq = vi->sq[i].vq;
2239 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2240 if (!is_xdp_raw_buffer_queue(vi, i))
2241 dev_kfree_skb(buf);
2242 else
2243 put_page(virt_to_head_page(buf));
2244 }
2245 }
2246
2247 for (i = 0; i < vi->max_queue_pairs; i++) {
2248 struct virtqueue *vq = vi->rq[i].vq;
2249
2250 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2251 if (vi->mergeable_rx_bufs) {
2252 put_page(virt_to_head_page(buf));
2253 } else if (vi->big_packets) {
2254 give_pages(&vi->rq[i], buf);
2255 } else {
2256 put_page(virt_to_head_page(buf));
2257 }
2258 }
2259 }
2260 }
2261
2262 static void virtnet_del_vqs(struct virtnet_info *vi)
2263 {
2264 struct virtio_device *vdev = vi->vdev;
2265
2266 virtnet_clean_affinity(vi, -1);
2267
2268 vdev->config->del_vqs(vdev);
2269
2270 virtnet_free_queues(vi);
2271 }
2272
2273 /* How large should a single buffer be so a queue full of these can fit at
2274 * least one full packet?
2275 * Logic below assumes the mergeable buffer header is used.
2276 */
2277 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
2278 {
2279 const unsigned int hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2280 unsigned int rq_size = virtqueue_get_vring_size(vq);
2281 unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
2282 unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
2283 unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
2284
2285 return max(max(min_buf_len, hdr_len) - hdr_len,
2286 (unsigned int)GOOD_PACKET_LEN);
2287 }
2288
2289 static int virtnet_find_vqs(struct virtnet_info *vi)
2290 {
2291 vq_callback_t **callbacks;
2292 struct virtqueue **vqs;
2293 int ret = -ENOMEM;
2294 int i, total_vqs;
2295 const char **names;
2296 bool *ctx;
2297
2298 /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
2299 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
2300 * possible control vq.
2301 */
2302 total_vqs = vi->max_queue_pairs * 2 +
2303 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
2304
2305 /* Allocate space for find_vqs parameters */
2306 vqs = kzalloc(total_vqs * sizeof(*vqs), GFP_KERNEL);
2307 if (!vqs)
2308 goto err_vq;
2309 callbacks = kmalloc(total_vqs * sizeof(*callbacks), GFP_KERNEL);
2310 if (!callbacks)
2311 goto err_callback;
2312 names = kmalloc(total_vqs * sizeof(*names), GFP_KERNEL);
2313 if (!names)
2314 goto err_names;
2315 if (!vi->big_packets || vi->mergeable_rx_bufs) {
2316 ctx = kzalloc(total_vqs * sizeof(*ctx), GFP_KERNEL);
2317 if (!ctx)
2318 goto err_ctx;
2319 } else {
2320 ctx = NULL;
2321 }
2322
2323 /* Parameters for control virtqueue, if any */
2324 if (vi->has_cvq) {
2325 callbacks[total_vqs - 1] = NULL;
2326 names[total_vqs - 1] = "control";
2327 }
2328
2329 /* Allocate/initialize parameters for send/receive virtqueues */
2330 for (i = 0; i < vi->max_queue_pairs; i++) {
2331 callbacks[rxq2vq(i)] = skb_recv_done;
2332 callbacks[txq2vq(i)] = skb_xmit_done;
2333 sprintf(vi->rq[i].name, "input.%d", i);
2334 sprintf(vi->sq[i].name, "output.%d", i);
2335 names[rxq2vq(i)] = vi->rq[i].name;
2336 names[txq2vq(i)] = vi->sq[i].name;
2337 if (ctx)
2338 ctx[rxq2vq(i)] = true;
2339 }
2340
2341 ret = vi->vdev->config->find_vqs(vi->vdev, total_vqs, vqs, callbacks,
2342 names, ctx, NULL);
2343 if (ret)
2344 goto err_find;
2345
2346 if (vi->has_cvq) {
2347 vi->cvq = vqs[total_vqs - 1];
2348 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
2349 vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
2350 }
2351
2352 for (i = 0; i < vi->max_queue_pairs; i++) {
2353 vi->rq[i].vq = vqs[rxq2vq(i)];
2354 vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
2355 vi->sq[i].vq = vqs[txq2vq(i)];
2356 }
2357
2358 kfree(names);
2359 kfree(callbacks);
2360 kfree(vqs);
2361 kfree(ctx);
2362
2363 return 0;
2364
2365 err_find:
2366 kfree(ctx);
2367 err_ctx:
2368 kfree(names);
2369 err_names:
2370 kfree(callbacks);
2371 err_callback:
2372 kfree(vqs);
2373 err_vq:
2374 return ret;
2375 }
2376
2377 static int virtnet_alloc_queues(struct virtnet_info *vi)
2378 {
2379 int i;
2380
2381 vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
2382 if (!vi->ctrl)
2383 goto err_ctrl;
2384 vi->sq = kzalloc(sizeof(*vi->sq) * vi->max_queue_pairs, GFP_KERNEL);
2385 if (!vi->sq)
2386 goto err_sq;
2387 vi->rq = kzalloc(sizeof(*vi->rq) * vi->max_queue_pairs, GFP_KERNEL);
2388 if (!vi->rq)
2389 goto err_rq;
2390
2391 INIT_DELAYED_WORK(&vi->refill, refill_work);
2392 for (i = 0; i < vi->max_queue_pairs; i++) {
2393 vi->rq[i].pages = NULL;
2394 netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
2395 napi_weight);
2396 netif_tx_napi_add(vi->dev, &vi->sq[i].napi, virtnet_poll_tx,
2397 napi_tx ? napi_weight : 0);
2398
2399 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
2400 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
2401 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
2402 }
2403
2404 return 0;
2405
2406 err_rq:
2407 kfree(vi->sq);
2408 err_sq:
2409 kfree(vi->ctrl);
2410 err_ctrl:
2411 return -ENOMEM;
2412 }
2413
2414 static int init_vqs(struct virtnet_info *vi)
2415 {
2416 int ret;
2417
2418 /* Allocate send & receive queues */
2419 ret = virtnet_alloc_queues(vi);
2420 if (ret)
2421 goto err;
2422
2423 ret = virtnet_find_vqs(vi);
2424 if (ret)
2425 goto err_free;
2426
2427 get_online_cpus();
2428 virtnet_set_affinity(vi);
2429 put_online_cpus();
2430
2431 return 0;
2432
2433 err_free:
2434 virtnet_free_queues(vi);
2435 err:
2436 return ret;
2437 }
2438
2439 #ifdef CONFIG_SYSFS
2440 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
2441 char *buf)
2442 {
2443 struct virtnet_info *vi = netdev_priv(queue->dev);
2444 unsigned int queue_index = get_netdev_rx_queue_index(queue);
2445 struct ewma_pkt_len *avg;
2446
2447 BUG_ON(queue_index >= vi->max_queue_pairs);
2448 avg = &vi->rq[queue_index].mrg_avg_pkt_len;
2449 return sprintf(buf, "%u\n",
2450 get_mergeable_buf_len(&vi->rq[queue_index], avg));
2451 }
2452
2453 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
2454 __ATTR_RO(mergeable_rx_buffer_size);
2455
2456 static struct attribute *virtio_net_mrg_rx_attrs[] = {
2457 &mergeable_rx_buffer_size_attribute.attr,
2458 NULL
2459 };
2460
2461 static const struct attribute_group virtio_net_mrg_rx_group = {
2462 .name = "virtio_net",
2463 .attrs = virtio_net_mrg_rx_attrs
2464 };
2465 #endif
2466
2467 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
2468 unsigned int fbit,
2469 const char *fname, const char *dname)
2470 {
2471 if (!virtio_has_feature(vdev, fbit))
2472 return false;
2473
2474 dev_err(&vdev->dev, "device advertises feature %s but not %s",
2475 fname, dname);
2476
2477 return true;
2478 }
2479
2480 #define VIRTNET_FAIL_ON(vdev, fbit, dbit) \
2481 virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
2482
2483 static bool virtnet_validate_features(struct virtio_device *vdev)
2484 {
2485 if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
2486 (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
2487 "VIRTIO_NET_F_CTRL_VQ") ||
2488 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
2489 "VIRTIO_NET_F_CTRL_VQ") ||
2490 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
2491 "VIRTIO_NET_F_CTRL_VQ") ||
2492 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
2493 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
2494 "VIRTIO_NET_F_CTRL_VQ"))) {
2495 return false;
2496 }
2497
2498 return true;
2499 }
2500
2501 #define MIN_MTU ETH_MIN_MTU
2502 #define MAX_MTU ETH_MAX_MTU
2503
2504 static int virtnet_validate(struct virtio_device *vdev)
2505 {
2506 if (!vdev->config->get) {
2507 dev_err(&vdev->dev, "%s failure: config access disabled\n",
2508 __func__);
2509 return -EINVAL;
2510 }
2511
2512 if (!virtnet_validate_features(vdev))
2513 return -EINVAL;
2514
2515 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
2516 int mtu = virtio_cread16(vdev,
2517 offsetof(struct virtio_net_config,
2518 mtu));
2519 if (mtu < MIN_MTU)
2520 __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
2521 }
2522
2523 return 0;
2524 }
2525
2526 static int virtnet_probe(struct virtio_device *vdev)
2527 {
2528 int i, err;
2529 struct net_device *dev;
2530 struct virtnet_info *vi;
2531 u16 max_queue_pairs;
2532 int mtu;
2533
2534 /* Find if host supports multiqueue virtio_net device */
2535 err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
2536 struct virtio_net_config,
2537 max_virtqueue_pairs, &max_queue_pairs);
2538
2539 /* We need at least 2 queue's */
2540 if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
2541 max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
2542 !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
2543 max_queue_pairs = 1;
2544
2545 /* Allocate ourselves a network device with room for our info */
2546 dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
2547 if (!dev)
2548 return -ENOMEM;
2549
2550 /* Set up network device as normal. */
2551 dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
2552 dev->netdev_ops = &virtnet_netdev;
2553 dev->features = NETIF_F_HIGHDMA;
2554
2555 dev->ethtool_ops = &virtnet_ethtool_ops;
2556 SET_NETDEV_DEV(dev, &vdev->dev);
2557
2558 /* Do we support "hardware" checksums? */
2559 if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
2560 /* This opens up the world of extra features. */
2561 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
2562 if (csum)
2563 dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
2564
2565 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
2566 dev->hw_features |= NETIF_F_TSO
2567 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
2568 }
2569 /* Individual feature bits: what can host handle? */
2570 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
2571 dev->hw_features |= NETIF_F_TSO;
2572 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
2573 dev->hw_features |= NETIF_F_TSO6;
2574 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
2575 dev->hw_features |= NETIF_F_TSO_ECN;
2576
2577 dev->features |= NETIF_F_GSO_ROBUST;
2578
2579 if (gso)
2580 dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
2581 /* (!csum && gso) case will be fixed by register_netdev() */
2582 }
2583 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
2584 dev->features |= NETIF_F_RXCSUM;
2585
2586 dev->vlan_features = dev->features;
2587
2588 /* MTU range: 68 - 65535 */
2589 dev->min_mtu = MIN_MTU;
2590 dev->max_mtu = MAX_MTU;
2591
2592 /* Configuration may specify what MAC to use. Otherwise random. */
2593 if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
2594 virtio_cread_bytes(vdev,
2595 offsetof(struct virtio_net_config, mac),
2596 dev->dev_addr, dev->addr_len);
2597 else
2598 eth_hw_addr_random(dev);
2599
2600 /* Set up our device-specific information */
2601 vi = netdev_priv(dev);
2602 vi->dev = dev;
2603 vi->vdev = vdev;
2604 vdev->priv = vi;
2605 vi->stats = alloc_percpu(struct virtnet_stats);
2606 err = -ENOMEM;
2607 if (vi->stats == NULL)
2608 goto free;
2609
2610 for_each_possible_cpu(i) {
2611 struct virtnet_stats *virtnet_stats;
2612 virtnet_stats = per_cpu_ptr(vi->stats, i);
2613 u64_stats_init(&virtnet_stats->tx_syncp);
2614 u64_stats_init(&virtnet_stats->rx_syncp);
2615 }
2616
2617 INIT_WORK(&vi->config_work, virtnet_config_changed_work);
2618
2619 /* If we can receive ANY GSO packets, we must allocate large ones. */
2620 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
2621 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
2622 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
2623 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
2624 vi->big_packets = true;
2625
2626 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
2627 vi->mergeable_rx_bufs = true;
2628
2629 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
2630 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
2631 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2632 else
2633 vi->hdr_len = sizeof(struct virtio_net_hdr);
2634
2635 if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
2636 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
2637 vi->any_header_sg = true;
2638
2639 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
2640 vi->has_cvq = true;
2641
2642 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
2643 mtu = virtio_cread16(vdev,
2644 offsetof(struct virtio_net_config,
2645 mtu));
2646 if (mtu < dev->min_mtu) {
2647 /* Should never trigger: MTU was previously validated
2648 * in virtnet_validate.
2649 */
2650 dev_err(&vdev->dev, "device MTU appears to have changed "
2651 "it is now %d < %d", mtu, dev->min_mtu);
2652 goto free_stats;
2653 }
2654
2655 dev->mtu = mtu;
2656 dev->max_mtu = mtu;
2657
2658 /* TODO: size buffers correctly in this case. */
2659 if (dev->mtu > ETH_DATA_LEN)
2660 vi->big_packets = true;
2661 }
2662
2663 if (vi->any_header_sg)
2664 dev->needed_headroom = vi->hdr_len;
2665
2666 /* Enable multiqueue by default */
2667 if (num_online_cpus() >= max_queue_pairs)
2668 vi->curr_queue_pairs = max_queue_pairs;
2669 else
2670 vi->curr_queue_pairs = num_online_cpus();
2671 vi->max_queue_pairs = max_queue_pairs;
2672
2673 /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
2674 err = init_vqs(vi);
2675 if (err)
2676 goto free_stats;
2677
2678 #ifdef CONFIG_SYSFS
2679 if (vi->mergeable_rx_bufs)
2680 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
2681 #endif
2682 netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
2683 netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
2684
2685 virtnet_init_settings(dev);
2686
2687 err = register_netdev(dev);
2688 if (err) {
2689 pr_debug("virtio_net: registering device failed\n");
2690 goto free_vqs;
2691 }
2692
2693 virtio_device_ready(vdev);
2694
2695 err = virtnet_cpu_notif_add(vi);
2696 if (err) {
2697 pr_debug("virtio_net: registering cpu notifier failed\n");
2698 goto free_unregister_netdev;
2699 }
2700
2701 virtnet_set_queues(vi, vi->curr_queue_pairs);
2702
2703 /* Assume link up if device can't report link status,
2704 otherwise get link status from config. */
2705 netif_carrier_off(dev);
2706 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
2707 schedule_work(&vi->config_work);
2708 } else {
2709 vi->status = VIRTIO_NET_S_LINK_UP;
2710 netif_carrier_on(dev);
2711 }
2712
2713 for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
2714 if (virtio_has_feature(vi->vdev, guest_offloads[i]))
2715 set_bit(guest_offloads[i], &vi->guest_offloads);
2716
2717 pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
2718 dev->name, max_queue_pairs);
2719
2720 return 0;
2721
2722 free_unregister_netdev:
2723 vi->vdev->config->reset(vdev);
2724
2725 unregister_netdev(dev);
2726 free_vqs:
2727 cancel_delayed_work_sync(&vi->refill);
2728 free_receive_page_frags(vi);
2729 virtnet_del_vqs(vi);
2730 free_stats:
2731 free_percpu(vi->stats);
2732 free:
2733 free_netdev(dev);
2734 return err;
2735 }
2736
2737 static void remove_vq_common(struct virtnet_info *vi)
2738 {
2739 vi->vdev->config->reset(vi->vdev);
2740
2741 /* Free unused buffers in both send and recv, if any. */
2742 free_unused_bufs(vi);
2743
2744 free_receive_bufs(vi);
2745
2746 free_receive_page_frags(vi);
2747
2748 virtnet_del_vqs(vi);
2749 }
2750
2751 static void virtnet_remove(struct virtio_device *vdev)
2752 {
2753 struct virtnet_info *vi = vdev->priv;
2754
2755 virtnet_cpu_notif_remove(vi);
2756
2757 /* Make sure no work handler is accessing the device. */
2758 flush_work(&vi->config_work);
2759
2760 unregister_netdev(vi->dev);
2761
2762 remove_vq_common(vi);
2763
2764 free_percpu(vi->stats);
2765 free_netdev(vi->dev);
2766 }
2767
2768 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
2769 {
2770 struct virtnet_info *vi = vdev->priv;
2771
2772 virtnet_cpu_notif_remove(vi);
2773 virtnet_freeze_down(vdev);
2774 remove_vq_common(vi);
2775
2776 return 0;
2777 }
2778
2779 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
2780 {
2781 struct virtnet_info *vi = vdev->priv;
2782 int err;
2783
2784 err = virtnet_restore_up(vdev);
2785 if (err)
2786 return err;
2787 virtnet_set_queues(vi, vi->curr_queue_pairs);
2788
2789 err = virtnet_cpu_notif_add(vi);
2790 if (err)
2791 return err;
2792
2793 return 0;
2794 }
2795
2796 static struct virtio_device_id id_table[] = {
2797 { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
2798 { 0 },
2799 };
2800
2801 #define VIRTNET_FEATURES \
2802 VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
2803 VIRTIO_NET_F_MAC, \
2804 VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
2805 VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
2806 VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
2807 VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
2808 VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
2809 VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
2810 VIRTIO_NET_F_CTRL_MAC_ADDR, \
2811 VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS
2812
2813 static unsigned int features[] = {
2814 VIRTNET_FEATURES,
2815 };
2816
2817 static unsigned int features_legacy[] = {
2818 VIRTNET_FEATURES,
2819 VIRTIO_NET_F_GSO,
2820 VIRTIO_F_ANY_LAYOUT,
2821 };
2822
2823 static struct virtio_driver virtio_net_driver = {
2824 .feature_table = features,
2825 .feature_table_size = ARRAY_SIZE(features),
2826 .feature_table_legacy = features_legacy,
2827 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
2828 .driver.name = KBUILD_MODNAME,
2829 .driver.owner = THIS_MODULE,
2830 .id_table = id_table,
2831 .validate = virtnet_validate,
2832 .probe = virtnet_probe,
2833 .remove = virtnet_remove,
2834 .config_changed = virtnet_config_changed,
2835 #ifdef CONFIG_PM_SLEEP
2836 .freeze = virtnet_freeze,
2837 .restore = virtnet_restore,
2838 #endif
2839 };
2840
2841 static __init int virtio_net_driver_init(void)
2842 {
2843 int ret;
2844
2845 ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
2846 virtnet_cpu_online,
2847 virtnet_cpu_down_prep);
2848 if (ret < 0)
2849 goto out;
2850 virtionet_online = ret;
2851 ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
2852 NULL, virtnet_cpu_dead);
2853 if (ret)
2854 goto err_dead;
2855
2856 ret = register_virtio_driver(&virtio_net_driver);
2857 if (ret)
2858 goto err_virtio;
2859 return 0;
2860 err_virtio:
2861 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
2862 err_dead:
2863 cpuhp_remove_multi_state(virtionet_online);
2864 out:
2865 return ret;
2866 }
2867 module_init(virtio_net_driver_init);
2868
2869 static __exit void virtio_net_driver_exit(void)
2870 {
2871 unregister_virtio_driver(&virtio_net_driver);
2872 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
2873 cpuhp_remove_multi_state(virtionet_online);
2874 }
2875 module_exit(virtio_net_driver_exit);
2876
2877 MODULE_DEVICE_TABLE(virtio, id_table);
2878 MODULE_DESCRIPTION("Virtio network driver");
2879 MODULE_LICENSE("GPL");