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