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