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