xref: /openbmc/linux/drivers/net/virtio_net.c (revision fa0f1ba7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* A network driver using virtio.
3  *
4  * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
5  */
6 //#define DEBUG
7 #include <linux/netdevice.h>
8 #include <linux/etherdevice.h>
9 #include <linux/ethtool.h>
10 #include <linux/module.h>
11 #include <linux/virtio.h>
12 #include <linux/virtio_net.h>
13 #include <linux/bpf.h>
14 #include <linux/bpf_trace.h>
15 #include <linux/scatterlist.h>
16 #include <linux/if_vlan.h>
17 #include <linux/slab.h>
18 #include <linux/cpu.h>
19 #include <linux/average.h>
20 #include <linux/filter.h>
21 #include <linux/kernel.h>
22 #include <net/route.h>
23 #include <net/xdp.h>
24 #include <net/net_failover.h>
25 
26 static int napi_weight = NAPI_POLL_WEIGHT;
27 module_param(napi_weight, int, 0444);
28 
29 static bool csum = true, gso = true, napi_tx = true;
30 module_param(csum, bool, 0444);
31 module_param(gso, bool, 0444);
32 module_param(napi_tx, bool, 0644);
33 
34 /* FIXME: MTU in config. */
35 #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
36 #define GOOD_COPY_LEN	128
37 
38 #define VIRTNET_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
39 
40 /* Amount of XDP headroom to prepend to packets for use by xdp_adjust_head */
41 #define VIRTIO_XDP_HEADROOM 256
42 
43 /* Separating two types of XDP xmit */
44 #define VIRTIO_XDP_TX		BIT(0)
45 #define VIRTIO_XDP_REDIR	BIT(1)
46 
47 #define VIRTIO_XDP_FLAG	BIT(0)
48 
49 /* RX packet size EWMA. The average packet size is used to determine the packet
50  * buffer size when refilling RX rings. As the entire RX ring may be refilled
51  * at once, the weight is chosen so that the EWMA will be insensitive to short-
52  * term, transient changes in packet size.
53  */
54 DECLARE_EWMA(pkt_len, 0, 64)
55 
56 #define VIRTNET_DRIVER_VERSION "1.0.0"
57 
58 static const unsigned long guest_offloads[] = {
59 	VIRTIO_NET_F_GUEST_TSO4,
60 	VIRTIO_NET_F_GUEST_TSO6,
61 	VIRTIO_NET_F_GUEST_ECN,
62 	VIRTIO_NET_F_GUEST_UFO,
63 	VIRTIO_NET_F_GUEST_CSUM,
64 	VIRTIO_NET_F_GUEST_USO4,
65 	VIRTIO_NET_F_GUEST_USO6
66 };
67 
68 #define GUEST_OFFLOAD_GRO_HW_MASK ((1ULL << VIRTIO_NET_F_GUEST_TSO4) | \
69 				(1ULL << VIRTIO_NET_F_GUEST_TSO6) | \
70 				(1ULL << VIRTIO_NET_F_GUEST_ECN)  | \
71 				(1ULL << VIRTIO_NET_F_GUEST_UFO)  | \
72 				(1ULL << VIRTIO_NET_F_GUEST_USO4) | \
73 				(1ULL << VIRTIO_NET_F_GUEST_USO6))
74 
75 struct virtnet_stat_desc {
76 	char desc[ETH_GSTRING_LEN];
77 	size_t offset;
78 };
79 
80 struct virtnet_sq_stats {
81 	struct u64_stats_sync syncp;
82 	u64 packets;
83 	u64 bytes;
84 	u64 xdp_tx;
85 	u64 xdp_tx_drops;
86 	u64 kicks;
87 	u64 tx_timeouts;
88 };
89 
90 struct virtnet_rq_stats {
91 	struct u64_stats_sync syncp;
92 	u64 packets;
93 	u64 bytes;
94 	u64 drops;
95 	u64 xdp_packets;
96 	u64 xdp_tx;
97 	u64 xdp_redirects;
98 	u64 xdp_drops;
99 	u64 kicks;
100 };
101 
102 #define VIRTNET_SQ_STAT(m)	offsetof(struct virtnet_sq_stats, m)
103 #define VIRTNET_RQ_STAT(m)	offsetof(struct virtnet_rq_stats, m)
104 
105 static const struct virtnet_stat_desc virtnet_sq_stats_desc[] = {
106 	{ "packets",		VIRTNET_SQ_STAT(packets) },
107 	{ "bytes",		VIRTNET_SQ_STAT(bytes) },
108 	{ "xdp_tx",		VIRTNET_SQ_STAT(xdp_tx) },
109 	{ "xdp_tx_drops",	VIRTNET_SQ_STAT(xdp_tx_drops) },
110 	{ "kicks",		VIRTNET_SQ_STAT(kicks) },
111 	{ "tx_timeouts",	VIRTNET_SQ_STAT(tx_timeouts) },
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[16];
138 
139 	struct virtnet_sq_stats stats;
140 
141 	struct napi_struct napi;
142 
143 	/* Record whether sq is in reset state. */
144 	bool reset;
145 };
146 
147 /* Internal representation of a receive virtqueue */
148 struct receive_queue {
149 	/* Virtqueue associated with this receive_queue */
150 	struct virtqueue *vq;
151 
152 	struct napi_struct napi;
153 
154 	struct bpf_prog __rcu *xdp_prog;
155 
156 	struct virtnet_rq_stats stats;
157 
158 	/* Chain pages by the private ptr. */
159 	struct page *pages;
160 
161 	/* Average packet length for mergeable receive buffers. */
162 	struct ewma_pkt_len mrg_avg_pkt_len;
163 
164 	/* Page frag for packet buffer allocation. */
165 	struct page_frag alloc_frag;
166 
167 	/* RX: fragments + linear part + virtio header */
168 	struct scatterlist sg[MAX_SKB_FRAGS + 2];
169 
170 	/* Min single buffer size for mergeable buffers case. */
171 	unsigned int min_buf_len;
172 
173 	/* Name of this receive queue: input.$index */
174 	char name[16];
175 
176 	struct xdp_rxq_info xdp_rxq;
177 };
178 
179 /* This structure can contain rss message with maximum settings for indirection table and keysize
180  * Note, that default structure that describes RSS configuration virtio_net_rss_config
181  * contains same info but can't handle table values.
182  * In any case, structure would be passed to virtio hw through sg_buf split by parts
183  * because table sizes may be differ according to the device configuration.
184  */
185 #define VIRTIO_NET_RSS_MAX_KEY_SIZE     40
186 #define VIRTIO_NET_RSS_MAX_TABLE_LEN    128
187 struct virtio_net_ctrl_rss {
188 	u32 hash_types;
189 	u16 indirection_table_mask;
190 	u16 unclassified_queue;
191 	u16 indirection_table[VIRTIO_NET_RSS_MAX_TABLE_LEN];
192 	u16 max_tx_vq;
193 	u8 hash_key_length;
194 	u8 key[VIRTIO_NET_RSS_MAX_KEY_SIZE];
195 };
196 
197 /* Control VQ buffers: protected by the rtnl lock */
198 struct control_buf {
199 	struct virtio_net_ctrl_hdr hdr;
200 	virtio_net_ctrl_ack status;
201 	struct virtio_net_ctrl_mq mq;
202 	u8 promisc;
203 	u8 allmulti;
204 	__virtio16 vid;
205 	__virtio64 offloads;
206 	struct virtio_net_ctrl_rss rss;
207 };
208 
209 struct virtnet_info {
210 	struct virtio_device *vdev;
211 	struct virtqueue *cvq;
212 	struct net_device *dev;
213 	struct send_queue *sq;
214 	struct receive_queue *rq;
215 	unsigned int status;
216 
217 	/* Max # of queue pairs supported by the device */
218 	u16 max_queue_pairs;
219 
220 	/* # of queue pairs currently used by the driver */
221 	u16 curr_queue_pairs;
222 
223 	/* # of XDP queue pairs currently used by the driver */
224 	u16 xdp_queue_pairs;
225 
226 	/* xdp_queue_pairs may be 0, when xdp is already loaded. So add this. */
227 	bool xdp_enabled;
228 
229 	/* I like... big packets and I cannot lie! */
230 	bool big_packets;
231 
232 	/* number of sg entries allocated for big packets */
233 	unsigned int big_packets_num_skbfrags;
234 
235 	/* Host will merge rx buffers for big packets (shake it! shake it!) */
236 	bool mergeable_rx_bufs;
237 
238 	/* Host supports rss and/or hash report */
239 	bool has_rss;
240 	bool has_rss_hash_report;
241 	u8 rss_key_size;
242 	u16 rss_indir_table_size;
243 	u32 rss_hash_types_supported;
244 	u32 rss_hash_types_saved;
245 
246 	/* Has control virtqueue */
247 	bool has_cvq;
248 
249 	/* Host can handle any s/g split between our header and packet data */
250 	bool any_header_sg;
251 
252 	/* Packet virtio header size */
253 	u8 hdr_len;
254 
255 	/* Work struct for delayed refilling if we run low on memory. */
256 	struct delayed_work refill;
257 
258 	/* Is delayed refill enabled? */
259 	bool refill_enabled;
260 
261 	/* The lock to synchronize the access to refill_enabled */
262 	spinlock_t refill_lock;
263 
264 	/* Work struct for config space updates */
265 	struct work_struct config_work;
266 
267 	/* Does the affinity hint is set for virtqueues? */
268 	bool affinity_hint_set;
269 
270 	/* CPU hotplug instances for online & dead */
271 	struct hlist_node node;
272 	struct hlist_node node_dead;
273 
274 	struct control_buf *ctrl;
275 
276 	/* Ethtool settings */
277 	u8 duplex;
278 	u32 speed;
279 
280 	/* Interrupt coalescing settings */
281 	u32 tx_usecs;
282 	u32 rx_usecs;
283 	u32 tx_max_packets;
284 	u32 rx_max_packets;
285 
286 	unsigned long guest_offloads;
287 	unsigned long guest_offloads_capable;
288 
289 	/* failover when STANDBY feature enabled */
290 	struct failover *failover;
291 };
292 
293 struct padded_vnet_hdr {
294 	struct virtio_net_hdr_v1_hash hdr;
295 	/*
296 	 * hdr is in a separate sg buffer, and data sg buffer shares same page
297 	 * with this header sg. This padding makes next sg 16 byte aligned
298 	 * after the header.
299 	 */
300 	char padding[12];
301 };
302 
303 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf);
304 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf);
305 
306 static bool is_xdp_frame(void *ptr)
307 {
308 	return (unsigned long)ptr & VIRTIO_XDP_FLAG;
309 }
310 
311 static void *xdp_to_ptr(struct xdp_frame *ptr)
312 {
313 	return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
314 }
315 
316 static struct xdp_frame *ptr_to_xdp(void *ptr)
317 {
318 	return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
319 }
320 
321 /* Converting between virtqueue no. and kernel tx/rx queue no.
322  * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
323  */
324 static int vq2txq(struct virtqueue *vq)
325 {
326 	return (vq->index - 1) / 2;
327 }
328 
329 static int txq2vq(int txq)
330 {
331 	return txq * 2 + 1;
332 }
333 
334 static int vq2rxq(struct virtqueue *vq)
335 {
336 	return vq->index / 2;
337 }
338 
339 static int rxq2vq(int rxq)
340 {
341 	return rxq * 2;
342 }
343 
344 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
345 {
346 	return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
347 }
348 
349 /*
350  * private is used to chain pages for big packets, put the whole
351  * most recent used list in the beginning for reuse
352  */
353 static void give_pages(struct receive_queue *rq, struct page *page)
354 {
355 	struct page *end;
356 
357 	/* Find end of list, sew whole thing into vi->rq.pages. */
358 	for (end = page; end->private; end = (struct page *)end->private);
359 	end->private = (unsigned long)rq->pages;
360 	rq->pages = page;
361 }
362 
363 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
364 {
365 	struct page *p = rq->pages;
366 
367 	if (p) {
368 		rq->pages = (struct page *)p->private;
369 		/* clear private here, it is used to chain pages */
370 		p->private = 0;
371 	} else
372 		p = alloc_page(gfp_mask);
373 	return p;
374 }
375 
376 static void enable_delayed_refill(struct virtnet_info *vi)
377 {
378 	spin_lock_bh(&vi->refill_lock);
379 	vi->refill_enabled = true;
380 	spin_unlock_bh(&vi->refill_lock);
381 }
382 
383 static void disable_delayed_refill(struct virtnet_info *vi)
384 {
385 	spin_lock_bh(&vi->refill_lock);
386 	vi->refill_enabled = false;
387 	spin_unlock_bh(&vi->refill_lock);
388 }
389 
390 static void virtqueue_napi_schedule(struct napi_struct *napi,
391 				    struct virtqueue *vq)
392 {
393 	if (napi_schedule_prep(napi)) {
394 		virtqueue_disable_cb(vq);
395 		__napi_schedule(napi);
396 	}
397 }
398 
399 static void virtqueue_napi_complete(struct napi_struct *napi,
400 				    struct virtqueue *vq, int processed)
401 {
402 	int opaque;
403 
404 	opaque = virtqueue_enable_cb_prepare(vq);
405 	if (napi_complete_done(napi, processed)) {
406 		if (unlikely(virtqueue_poll(vq, opaque)))
407 			virtqueue_napi_schedule(napi, vq);
408 	} else {
409 		virtqueue_disable_cb(vq);
410 	}
411 }
412 
413 static void skb_xmit_done(struct virtqueue *vq)
414 {
415 	struct virtnet_info *vi = vq->vdev->priv;
416 	struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
417 
418 	/* Suppress further interrupts. */
419 	virtqueue_disable_cb(vq);
420 
421 	if (napi->weight)
422 		virtqueue_napi_schedule(napi, vq);
423 	else
424 		/* We were probably waiting for more output buffers. */
425 		netif_wake_subqueue(vi->dev, vq2txq(vq));
426 }
427 
428 #define MRG_CTX_HEADER_SHIFT 22
429 static void *mergeable_len_to_ctx(unsigned int truesize,
430 				  unsigned int headroom)
431 {
432 	return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
433 }
434 
435 static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
436 {
437 	return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
438 }
439 
440 static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
441 {
442 	return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
443 }
444 
445 /* Called from bottom half context */
446 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
447 				   struct receive_queue *rq,
448 				   struct page *page, unsigned int offset,
449 				   unsigned int len, unsigned int truesize,
450 				   unsigned int headroom)
451 {
452 	struct sk_buff *skb;
453 	struct virtio_net_hdr_mrg_rxbuf *hdr;
454 	unsigned int copy, hdr_len, hdr_padded_len;
455 	struct page *page_to_free = NULL;
456 	int tailroom, shinfo_size;
457 	char *p, *hdr_p, *buf;
458 
459 	p = page_address(page) + offset;
460 	hdr_p = p;
461 
462 	hdr_len = vi->hdr_len;
463 	if (vi->mergeable_rx_bufs)
464 		hdr_padded_len = hdr_len;
465 	else
466 		hdr_padded_len = sizeof(struct padded_vnet_hdr);
467 
468 	buf = p - headroom;
469 	len -= hdr_len;
470 	offset += hdr_padded_len;
471 	p += hdr_padded_len;
472 	tailroom = truesize - headroom  - hdr_padded_len - len;
473 
474 	shinfo_size = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
475 
476 	/* copy small packet so we can reuse these pages */
477 	if (!NET_IP_ALIGN && len > GOOD_COPY_LEN && tailroom >= shinfo_size) {
478 		skb = build_skb(buf, truesize);
479 		if (unlikely(!skb))
480 			return NULL;
481 
482 		skb_reserve(skb, p - buf);
483 		skb_put(skb, len);
484 
485 		page = (struct page *)page->private;
486 		if (page)
487 			give_pages(rq, page);
488 		goto ok;
489 	}
490 
491 	/* copy small packet so we can reuse these pages for small data */
492 	skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
493 	if (unlikely(!skb))
494 		return NULL;
495 
496 	/* Copy all frame if it fits skb->head, otherwise
497 	 * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
498 	 */
499 	if (len <= skb_tailroom(skb))
500 		copy = len;
501 	else
502 		copy = ETH_HLEN;
503 	skb_put_data(skb, p, copy);
504 
505 	len -= copy;
506 	offset += copy;
507 
508 	if (vi->mergeable_rx_bufs) {
509 		if (len)
510 			skb_add_rx_frag(skb, 0, page, offset, len, truesize);
511 		else
512 			page_to_free = page;
513 		goto ok;
514 	}
515 
516 	/*
517 	 * Verify that we can indeed put this data into a skb.
518 	 * This is here to handle cases when the device erroneously
519 	 * tries to receive more than is possible. This is usually
520 	 * the case of a broken device.
521 	 */
522 	if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
523 		net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
524 		dev_kfree_skb(skb);
525 		return NULL;
526 	}
527 	BUG_ON(offset >= PAGE_SIZE);
528 	while (len) {
529 		unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
530 		skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
531 				frag_size, truesize);
532 		len -= frag_size;
533 		page = (struct page *)page->private;
534 		offset = 0;
535 	}
536 
537 	if (page)
538 		give_pages(rq, page);
539 
540 ok:
541 	hdr = skb_vnet_hdr(skb);
542 	memcpy(hdr, hdr_p, hdr_len);
543 	if (page_to_free)
544 		put_page(page_to_free);
545 
546 	return skb;
547 }
548 
549 static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
550 {
551 	unsigned int len;
552 	unsigned int packets = 0;
553 	unsigned int bytes = 0;
554 	void *ptr;
555 
556 	while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
557 		if (likely(!is_xdp_frame(ptr))) {
558 			struct sk_buff *skb = ptr;
559 
560 			pr_debug("Sent skb %p\n", skb);
561 
562 			bytes += skb->len;
563 			napi_consume_skb(skb, in_napi);
564 		} else {
565 			struct xdp_frame *frame = ptr_to_xdp(ptr);
566 
567 			bytes += xdp_get_frame_len(frame);
568 			xdp_return_frame(frame);
569 		}
570 		packets++;
571 	}
572 
573 	/* Avoid overhead when no packets have been processed
574 	 * happens when called speculatively from start_xmit.
575 	 */
576 	if (!packets)
577 		return;
578 
579 	u64_stats_update_begin(&sq->stats.syncp);
580 	sq->stats.bytes += bytes;
581 	sq->stats.packets += packets;
582 	u64_stats_update_end(&sq->stats.syncp);
583 }
584 
585 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
586 {
587 	if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
588 		return false;
589 	else if (q < vi->curr_queue_pairs)
590 		return true;
591 	else
592 		return false;
593 }
594 
595 static void check_sq_full_and_disable(struct virtnet_info *vi,
596 				      struct net_device *dev,
597 				      struct send_queue *sq)
598 {
599 	bool use_napi = sq->napi.weight;
600 	int qnum;
601 
602 	qnum = sq - vi->sq;
603 
604 	/* If running out of space, stop queue to avoid getting packets that we
605 	 * are then unable to transmit.
606 	 * An alternative would be to force queuing layer to requeue the skb by
607 	 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
608 	 * returned in a normal path of operation: it means that driver is not
609 	 * maintaining the TX queue stop/start state properly, and causes
610 	 * the stack to do a non-trivial amount of useless work.
611 	 * Since most packets only take 1 or 2 ring slots, stopping the queue
612 	 * early means 16 slots are typically wasted.
613 	 */
614 	if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
615 		netif_stop_subqueue(dev, qnum);
616 		if (use_napi) {
617 			if (unlikely(!virtqueue_enable_cb_delayed(sq->vq)))
618 				virtqueue_napi_schedule(&sq->napi, sq->vq);
619 		} else if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
620 			/* More just got used, free them then recheck. */
621 			free_old_xmit_skbs(sq, false);
622 			if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
623 				netif_start_subqueue(dev, qnum);
624 				virtqueue_disable_cb(sq->vq);
625 			}
626 		}
627 	}
628 }
629 
630 static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
631 				   struct send_queue *sq,
632 				   struct xdp_frame *xdpf)
633 {
634 	struct virtio_net_hdr_mrg_rxbuf *hdr;
635 	struct skb_shared_info *shinfo;
636 	u8 nr_frags = 0;
637 	int err, i;
638 
639 	if (unlikely(xdpf->headroom < vi->hdr_len))
640 		return -EOVERFLOW;
641 
642 	if (unlikely(xdp_frame_has_frags(xdpf))) {
643 		shinfo = xdp_get_shared_info_from_frame(xdpf);
644 		nr_frags = shinfo->nr_frags;
645 	}
646 
647 	/* In wrapping function virtnet_xdp_xmit(), we need to free
648 	 * up the pending old buffers, where we need to calculate the
649 	 * position of skb_shared_info in xdp_get_frame_len() and
650 	 * xdp_return_frame(), which will involve to xdpf->data and
651 	 * xdpf->headroom. Therefore, we need to update the value of
652 	 * headroom synchronously here.
653 	 */
654 	xdpf->headroom -= vi->hdr_len;
655 	xdpf->data -= vi->hdr_len;
656 	/* Zero header and leave csum up to XDP layers */
657 	hdr = xdpf->data;
658 	memset(hdr, 0, vi->hdr_len);
659 	xdpf->len   += vi->hdr_len;
660 
661 	sg_init_table(sq->sg, nr_frags + 1);
662 	sg_set_buf(sq->sg, xdpf->data, xdpf->len);
663 	for (i = 0; i < nr_frags; i++) {
664 		skb_frag_t *frag = &shinfo->frags[i];
665 
666 		sg_set_page(&sq->sg[i + 1], skb_frag_page(frag),
667 			    skb_frag_size(frag), skb_frag_off(frag));
668 	}
669 
670 	err = virtqueue_add_outbuf(sq->vq, sq->sg, nr_frags + 1,
671 				   xdp_to_ptr(xdpf), GFP_ATOMIC);
672 	if (unlikely(err))
673 		return -ENOSPC; /* Caller handle free/refcnt */
674 
675 	return 0;
676 }
677 
678 /* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
679  * the current cpu, so it does not need to be locked.
680  *
681  * Here we use marco instead of inline functions because we have to deal with
682  * three issues at the same time: 1. the choice of sq. 2. judge and execute the
683  * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
684  * functions to perfectly solve these three problems at the same time.
685  */
686 #define virtnet_xdp_get_sq(vi) ({                                       \
687 	int cpu = smp_processor_id();                                   \
688 	struct netdev_queue *txq;                                       \
689 	typeof(vi) v = (vi);                                            \
690 	unsigned int qp;                                                \
691 									\
692 	if (v->curr_queue_pairs > nr_cpu_ids) {                         \
693 		qp = v->curr_queue_pairs - v->xdp_queue_pairs;          \
694 		qp += cpu;                                              \
695 		txq = netdev_get_tx_queue(v->dev, qp);                  \
696 		__netif_tx_acquire(txq);                                \
697 	} else {                                                        \
698 		qp = cpu % v->curr_queue_pairs;                         \
699 		txq = netdev_get_tx_queue(v->dev, qp);                  \
700 		__netif_tx_lock(txq, cpu);                              \
701 	}                                                               \
702 	v->sq + qp;                                                     \
703 })
704 
705 #define virtnet_xdp_put_sq(vi, q) {                                     \
706 	struct netdev_queue *txq;                                       \
707 	typeof(vi) v = (vi);                                            \
708 									\
709 	txq = netdev_get_tx_queue(v->dev, (q) - v->sq);                 \
710 	if (v->curr_queue_pairs > nr_cpu_ids)                           \
711 		__netif_tx_release(txq);                                \
712 	else                                                            \
713 		__netif_tx_unlock(txq);                                 \
714 }
715 
716 static int virtnet_xdp_xmit(struct net_device *dev,
717 			    int n, struct xdp_frame **frames, u32 flags)
718 {
719 	struct virtnet_info *vi = netdev_priv(dev);
720 	struct receive_queue *rq = vi->rq;
721 	struct bpf_prog *xdp_prog;
722 	struct send_queue *sq;
723 	unsigned int len;
724 	int packets = 0;
725 	int bytes = 0;
726 	int nxmit = 0;
727 	int kicks = 0;
728 	void *ptr;
729 	int ret;
730 	int i;
731 
732 	/* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
733 	 * indicate XDP resources have been successfully allocated.
734 	 */
735 	xdp_prog = rcu_access_pointer(rq->xdp_prog);
736 	if (!xdp_prog)
737 		return -ENXIO;
738 
739 	sq = virtnet_xdp_get_sq(vi);
740 
741 	if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
742 		ret = -EINVAL;
743 		goto out;
744 	}
745 
746 	/* Free up any pending old buffers before queueing new ones. */
747 	while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
748 		if (likely(is_xdp_frame(ptr))) {
749 			struct xdp_frame *frame = ptr_to_xdp(ptr);
750 
751 			bytes += xdp_get_frame_len(frame);
752 			xdp_return_frame(frame);
753 		} else {
754 			struct sk_buff *skb = ptr;
755 
756 			bytes += skb->len;
757 			napi_consume_skb(skb, false);
758 		}
759 		packets++;
760 	}
761 
762 	for (i = 0; i < n; i++) {
763 		struct xdp_frame *xdpf = frames[i];
764 
765 		if (__virtnet_xdp_xmit_one(vi, sq, xdpf))
766 			break;
767 		nxmit++;
768 	}
769 	ret = nxmit;
770 
771 	if (!is_xdp_raw_buffer_queue(vi, sq - vi->sq))
772 		check_sq_full_and_disable(vi, dev, sq);
773 
774 	if (flags & XDP_XMIT_FLUSH) {
775 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
776 			kicks = 1;
777 	}
778 out:
779 	u64_stats_update_begin(&sq->stats.syncp);
780 	sq->stats.bytes += bytes;
781 	sq->stats.packets += packets;
782 	sq->stats.xdp_tx += n;
783 	sq->stats.xdp_tx_drops += n - nxmit;
784 	sq->stats.kicks += kicks;
785 	u64_stats_update_end(&sq->stats.syncp);
786 
787 	virtnet_xdp_put_sq(vi, sq);
788 	return ret;
789 }
790 
791 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
792 {
793 	return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
794 }
795 
796 /* We copy the packet for XDP in the following cases:
797  *
798  * 1) Packet is scattered across multiple rx buffers.
799  * 2) Headroom space is insufficient.
800  *
801  * This is inefficient but it's a temporary condition that
802  * we hit right after XDP is enabled and until queue is refilled
803  * with large buffers with sufficient headroom - so it should affect
804  * at most queue size packets.
805  * Afterwards, the conditions to enable
806  * XDP should preclude the underlying device from sending packets
807  * across multiple buffers (num_buf > 1), and we make sure buffers
808  * have enough headroom.
809  */
810 static struct page *xdp_linearize_page(struct receive_queue *rq,
811 				       int *num_buf,
812 				       struct page *p,
813 				       int offset,
814 				       int page_off,
815 				       unsigned int *len)
816 {
817 	struct page *page = alloc_page(GFP_ATOMIC);
818 
819 	if (!page)
820 		return NULL;
821 
822 	memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
823 	page_off += *len;
824 
825 	while (--*num_buf) {
826 		int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
827 		unsigned int buflen;
828 		void *buf;
829 		int off;
830 
831 		buf = virtqueue_get_buf(rq->vq, &buflen);
832 		if (unlikely(!buf))
833 			goto err_buf;
834 
835 		p = virt_to_head_page(buf);
836 		off = buf - page_address(p);
837 
838 		/* guard against a misconfigured or uncooperative backend that
839 		 * is sending packet larger than the MTU.
840 		 */
841 		if ((page_off + buflen + tailroom) > PAGE_SIZE) {
842 			put_page(p);
843 			goto err_buf;
844 		}
845 
846 		memcpy(page_address(page) + page_off,
847 		       page_address(p) + off, buflen);
848 		page_off += buflen;
849 		put_page(p);
850 	}
851 
852 	/* Headroom does not contribute to packet length */
853 	*len = page_off - VIRTIO_XDP_HEADROOM;
854 	return page;
855 err_buf:
856 	__free_pages(page, 0);
857 	return NULL;
858 }
859 
860 static struct sk_buff *receive_small(struct net_device *dev,
861 				     struct virtnet_info *vi,
862 				     struct receive_queue *rq,
863 				     void *buf, void *ctx,
864 				     unsigned int len,
865 				     unsigned int *xdp_xmit,
866 				     struct virtnet_rq_stats *stats)
867 {
868 	struct sk_buff *skb;
869 	struct bpf_prog *xdp_prog;
870 	unsigned int xdp_headroom = (unsigned long)ctx;
871 	unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
872 	unsigned int headroom = vi->hdr_len + header_offset;
873 	unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
874 			      SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
875 	struct page *page = virt_to_head_page(buf);
876 	unsigned int delta = 0;
877 	struct page *xdp_page;
878 	int err;
879 	unsigned int metasize = 0;
880 
881 	len -= vi->hdr_len;
882 	stats->bytes += len;
883 
884 	if (unlikely(len > GOOD_PACKET_LEN)) {
885 		pr_debug("%s: rx error: len %u exceeds max size %d\n",
886 			 dev->name, len, GOOD_PACKET_LEN);
887 		dev->stats.rx_length_errors++;
888 		goto err;
889 	}
890 
891 	if (likely(!vi->xdp_enabled)) {
892 		xdp_prog = NULL;
893 		goto skip_xdp;
894 	}
895 
896 	rcu_read_lock();
897 	xdp_prog = rcu_dereference(rq->xdp_prog);
898 	if (xdp_prog) {
899 		struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
900 		struct xdp_frame *xdpf;
901 		struct xdp_buff xdp;
902 		void *orig_data;
903 		u32 act;
904 
905 		if (unlikely(hdr->hdr.gso_type))
906 			goto err_xdp;
907 
908 		if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
909 			int offset = buf - page_address(page) + header_offset;
910 			unsigned int tlen = len + vi->hdr_len;
911 			int num_buf = 1;
912 
913 			xdp_headroom = virtnet_get_headroom(vi);
914 			header_offset = VIRTNET_RX_PAD + xdp_headroom;
915 			headroom = vi->hdr_len + header_offset;
916 			buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
917 				 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
918 			xdp_page = xdp_linearize_page(rq, &num_buf, page,
919 						      offset, header_offset,
920 						      &tlen);
921 			if (!xdp_page)
922 				goto err_xdp;
923 
924 			buf = page_address(xdp_page);
925 			put_page(page);
926 			page = xdp_page;
927 		}
928 
929 		xdp_init_buff(&xdp, buflen, &rq->xdp_rxq);
930 		xdp_prepare_buff(&xdp, buf + VIRTNET_RX_PAD + vi->hdr_len,
931 				 xdp_headroom, len, true);
932 		orig_data = xdp.data;
933 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
934 		stats->xdp_packets++;
935 
936 		switch (act) {
937 		case XDP_PASS:
938 			/* Recalculate length in case bpf program changed it */
939 			delta = orig_data - xdp.data;
940 			len = xdp.data_end - xdp.data;
941 			metasize = xdp.data - xdp.data_meta;
942 			break;
943 		case XDP_TX:
944 			stats->xdp_tx++;
945 			xdpf = xdp_convert_buff_to_frame(&xdp);
946 			if (unlikely(!xdpf))
947 				goto err_xdp;
948 			err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
949 			if (unlikely(!err)) {
950 				xdp_return_frame_rx_napi(xdpf);
951 			} else if (unlikely(err < 0)) {
952 				trace_xdp_exception(vi->dev, xdp_prog, act);
953 				goto err_xdp;
954 			}
955 			*xdp_xmit |= VIRTIO_XDP_TX;
956 			rcu_read_unlock();
957 			goto xdp_xmit;
958 		case XDP_REDIRECT:
959 			stats->xdp_redirects++;
960 			err = xdp_do_redirect(dev, &xdp, xdp_prog);
961 			if (err)
962 				goto err_xdp;
963 			*xdp_xmit |= VIRTIO_XDP_REDIR;
964 			rcu_read_unlock();
965 			goto xdp_xmit;
966 		default:
967 			bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
968 			fallthrough;
969 		case XDP_ABORTED:
970 			trace_xdp_exception(vi->dev, xdp_prog, act);
971 			goto err_xdp;
972 		case XDP_DROP:
973 			goto err_xdp;
974 		}
975 	}
976 	rcu_read_unlock();
977 
978 skip_xdp:
979 	skb = build_skb(buf, buflen);
980 	if (!skb)
981 		goto err;
982 	skb_reserve(skb, headroom - delta);
983 	skb_put(skb, len);
984 	if (!xdp_prog) {
985 		buf += header_offset;
986 		memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
987 	} /* keep zeroed vnet hdr since XDP is loaded */
988 
989 	if (metasize)
990 		skb_metadata_set(skb, metasize);
991 
992 	return skb;
993 
994 err_xdp:
995 	rcu_read_unlock();
996 	stats->xdp_drops++;
997 err:
998 	stats->drops++;
999 	put_page(page);
1000 xdp_xmit:
1001 	return NULL;
1002 }
1003 
1004 static struct sk_buff *receive_big(struct net_device *dev,
1005 				   struct virtnet_info *vi,
1006 				   struct receive_queue *rq,
1007 				   void *buf,
1008 				   unsigned int len,
1009 				   struct virtnet_rq_stats *stats)
1010 {
1011 	struct page *page = buf;
1012 	struct sk_buff *skb =
1013 		page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, 0);
1014 
1015 	stats->bytes += len - vi->hdr_len;
1016 	if (unlikely(!skb))
1017 		goto err;
1018 
1019 	return skb;
1020 
1021 err:
1022 	stats->drops++;
1023 	give_pages(rq, page);
1024 	return NULL;
1025 }
1026 
1027 /* Why not use xdp_build_skb_from_frame() ?
1028  * XDP core assumes that xdp frags are PAGE_SIZE in length, while in
1029  * virtio-net there are 2 points that do not match its requirements:
1030  *  1. The size of the prefilled buffer is not fixed before xdp is set.
1031  *  2. xdp_build_skb_from_frame() does more checks that we don't need,
1032  *     like eth_type_trans() (which virtio-net does in receive_buf()).
1033  */
1034 static struct sk_buff *build_skb_from_xdp_buff(struct net_device *dev,
1035 					       struct virtnet_info *vi,
1036 					       struct xdp_buff *xdp,
1037 					       unsigned int xdp_frags_truesz)
1038 {
1039 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
1040 	unsigned int headroom, data_len;
1041 	struct sk_buff *skb;
1042 	int metasize;
1043 	u8 nr_frags;
1044 
1045 	if (unlikely(xdp->data_end > xdp_data_hard_end(xdp))) {
1046 		pr_debug("Error building skb as missing reserved tailroom for xdp");
1047 		return NULL;
1048 	}
1049 
1050 	if (unlikely(xdp_buff_has_frags(xdp)))
1051 		nr_frags = sinfo->nr_frags;
1052 
1053 	skb = build_skb(xdp->data_hard_start, xdp->frame_sz);
1054 	if (unlikely(!skb))
1055 		return NULL;
1056 
1057 	headroom = xdp->data - xdp->data_hard_start;
1058 	data_len = xdp->data_end - xdp->data;
1059 	skb_reserve(skb, headroom);
1060 	__skb_put(skb, data_len);
1061 
1062 	metasize = xdp->data - xdp->data_meta;
1063 	metasize = metasize > 0 ? metasize : 0;
1064 	if (metasize)
1065 		skb_metadata_set(skb, metasize);
1066 
1067 	if (unlikely(xdp_buff_has_frags(xdp)))
1068 		xdp_update_skb_shared_info(skb, nr_frags,
1069 					   sinfo->xdp_frags_size,
1070 					   xdp_frags_truesz,
1071 					   xdp_buff_is_frag_pfmemalloc(xdp));
1072 
1073 	return skb;
1074 }
1075 
1076 /* TODO: build xdp in big mode */
1077 static int virtnet_build_xdp_buff_mrg(struct net_device *dev,
1078 				      struct virtnet_info *vi,
1079 				      struct receive_queue *rq,
1080 				      struct xdp_buff *xdp,
1081 				      void *buf,
1082 				      unsigned int len,
1083 				      unsigned int frame_sz,
1084 				      int *num_buf,
1085 				      unsigned int *xdp_frags_truesize,
1086 				      struct virtnet_rq_stats *stats)
1087 {
1088 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1089 	unsigned int headroom, tailroom, room;
1090 	unsigned int truesize, cur_frag_size;
1091 	struct skb_shared_info *shinfo;
1092 	unsigned int xdp_frags_truesz = 0;
1093 	struct page *page;
1094 	skb_frag_t *frag;
1095 	int offset;
1096 	void *ctx;
1097 
1098 	xdp_init_buff(xdp, frame_sz, &rq->xdp_rxq);
1099 	xdp_prepare_buff(xdp, buf - VIRTIO_XDP_HEADROOM,
1100 			 VIRTIO_XDP_HEADROOM + vi->hdr_len, len - vi->hdr_len, true);
1101 
1102 	if (!*num_buf)
1103 		return 0;
1104 
1105 	if (*num_buf > 1) {
1106 		/* If we want to build multi-buffer xdp, we need
1107 		 * to specify that the flags of xdp_buff have the
1108 		 * XDP_FLAGS_HAS_FRAG bit.
1109 		 */
1110 		if (!xdp_buff_has_frags(xdp))
1111 			xdp_buff_set_frags_flag(xdp);
1112 
1113 		shinfo = xdp_get_shared_info_from_buff(xdp);
1114 		shinfo->nr_frags = 0;
1115 		shinfo->xdp_frags_size = 0;
1116 	}
1117 
1118 	if (*num_buf > MAX_SKB_FRAGS + 1)
1119 		return -EINVAL;
1120 
1121 	while (--*num_buf > 0) {
1122 		buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1123 		if (unlikely(!buf)) {
1124 			pr_debug("%s: rx error: %d buffers out of %d missing\n",
1125 				 dev->name, *num_buf,
1126 				 virtio16_to_cpu(vi->vdev, hdr->num_buffers));
1127 			dev->stats.rx_length_errors++;
1128 			return -EINVAL;
1129 		}
1130 
1131 		stats->bytes += len;
1132 		page = virt_to_head_page(buf);
1133 		offset = buf - page_address(page);
1134 
1135 		truesize = mergeable_ctx_to_truesize(ctx);
1136 		headroom = mergeable_ctx_to_headroom(ctx);
1137 		tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1138 		room = SKB_DATA_ALIGN(headroom + tailroom);
1139 
1140 		cur_frag_size = truesize;
1141 		xdp_frags_truesz += cur_frag_size;
1142 		if (unlikely(len > truesize - room || cur_frag_size > PAGE_SIZE)) {
1143 			put_page(page);
1144 			pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1145 				 dev->name, len, (unsigned long)(truesize - room));
1146 			dev->stats.rx_length_errors++;
1147 			return -EINVAL;
1148 		}
1149 
1150 		frag = &shinfo->frags[shinfo->nr_frags++];
1151 		__skb_frag_set_page(frag, page);
1152 		skb_frag_off_set(frag, offset);
1153 		skb_frag_size_set(frag, len);
1154 		if (page_is_pfmemalloc(page))
1155 			xdp_buff_set_frag_pfmemalloc(xdp);
1156 
1157 		shinfo->xdp_frags_size += len;
1158 	}
1159 
1160 	*xdp_frags_truesize = xdp_frags_truesz;
1161 	return 0;
1162 }
1163 
1164 static struct sk_buff *receive_mergeable(struct net_device *dev,
1165 					 struct virtnet_info *vi,
1166 					 struct receive_queue *rq,
1167 					 void *buf,
1168 					 void *ctx,
1169 					 unsigned int len,
1170 					 unsigned int *xdp_xmit,
1171 					 struct virtnet_rq_stats *stats)
1172 {
1173 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1174 	int num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
1175 	struct page *page = virt_to_head_page(buf);
1176 	int offset = buf - page_address(page);
1177 	struct sk_buff *head_skb, *curr_skb;
1178 	struct bpf_prog *xdp_prog;
1179 	unsigned int truesize = mergeable_ctx_to_truesize(ctx);
1180 	unsigned int headroom = mergeable_ctx_to_headroom(ctx);
1181 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1182 	unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1183 	unsigned int frame_sz, xdp_room;
1184 	int err;
1185 
1186 	head_skb = NULL;
1187 	stats->bytes += len - vi->hdr_len;
1188 
1189 	if (unlikely(len > truesize - room)) {
1190 		pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1191 			 dev->name, len, (unsigned long)(truesize - room));
1192 		dev->stats.rx_length_errors++;
1193 		goto err_skb;
1194 	}
1195 
1196 	if (likely(!vi->xdp_enabled)) {
1197 		xdp_prog = NULL;
1198 		goto skip_xdp;
1199 	}
1200 
1201 	rcu_read_lock();
1202 	xdp_prog = rcu_dereference(rq->xdp_prog);
1203 	if (xdp_prog) {
1204 		unsigned int xdp_frags_truesz = 0;
1205 		struct skb_shared_info *shinfo;
1206 		struct xdp_frame *xdpf;
1207 		struct page *xdp_page;
1208 		struct xdp_buff xdp;
1209 		void *data;
1210 		u32 act;
1211 		int i;
1212 
1213 		/* Transient failure which in theory could occur if
1214 		 * in-flight packets from before XDP was enabled reach
1215 		 * the receive path after XDP is loaded.
1216 		 */
1217 		if (unlikely(hdr->hdr.gso_type))
1218 			goto err_xdp;
1219 
1220 		/* Now XDP core assumes frag size is PAGE_SIZE, but buffers
1221 		 * with headroom may add hole in truesize, which
1222 		 * make their length exceed PAGE_SIZE. So we disabled the
1223 		 * hole mechanism for xdp. See add_recvbuf_mergeable().
1224 		 */
1225 		frame_sz = truesize;
1226 
1227 		/* This happens when headroom is not enough because
1228 		 * of the buffer was prefilled before XDP is set.
1229 		 * This should only happen for the first several packets.
1230 		 * In fact, vq reset can be used here to help us clean up
1231 		 * the prefilled buffers, but many existing devices do not
1232 		 * support it, and we don't want to bother users who are
1233 		 * using xdp normally.
1234 		 */
1235 		if (!xdp_prog->aux->xdp_has_frags &&
1236 		    (num_buf > 1 || headroom < virtnet_get_headroom(vi))) {
1237 			/* linearize data for XDP */
1238 			xdp_page = xdp_linearize_page(rq, &num_buf,
1239 						      page, offset,
1240 						      VIRTIO_XDP_HEADROOM,
1241 						      &len);
1242 			frame_sz = PAGE_SIZE;
1243 
1244 			if (!xdp_page)
1245 				goto err_xdp;
1246 			offset = VIRTIO_XDP_HEADROOM;
1247 		} else if (unlikely(headroom < virtnet_get_headroom(vi))) {
1248 			xdp_room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
1249 						  sizeof(struct skb_shared_info));
1250 			if (len + xdp_room > PAGE_SIZE)
1251 				goto err_xdp;
1252 
1253 			xdp_page = alloc_page(GFP_ATOMIC);
1254 			if (!xdp_page)
1255 				goto err_xdp;
1256 
1257 			memcpy(page_address(xdp_page) + VIRTIO_XDP_HEADROOM,
1258 			       page_address(page) + offset, len);
1259 			frame_sz = PAGE_SIZE;
1260 			offset = VIRTIO_XDP_HEADROOM;
1261 		} else {
1262 			xdp_page = page;
1263 		}
1264 
1265 		data = page_address(xdp_page) + offset;
1266 		err = virtnet_build_xdp_buff_mrg(dev, vi, rq, &xdp, data, len, frame_sz,
1267 						 &num_buf, &xdp_frags_truesz, stats);
1268 		if (unlikely(err))
1269 			goto err_xdp_frags;
1270 
1271 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
1272 		stats->xdp_packets++;
1273 
1274 		switch (act) {
1275 		case XDP_PASS:
1276 			if (unlikely(xdp_page != page))
1277 				put_page(page);
1278 			head_skb = build_skb_from_xdp_buff(dev, vi, &xdp, xdp_frags_truesz);
1279 			rcu_read_unlock();
1280 			return head_skb;
1281 		case XDP_TX:
1282 			stats->xdp_tx++;
1283 			xdpf = xdp_convert_buff_to_frame(&xdp);
1284 			if (unlikely(!xdpf)) {
1285 				netdev_dbg(dev, "convert buff to frame failed for xdp\n");
1286 				goto err_xdp_frags;
1287 			}
1288 			err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
1289 			if (unlikely(!err)) {
1290 				xdp_return_frame_rx_napi(xdpf);
1291 			} else if (unlikely(err < 0)) {
1292 				trace_xdp_exception(vi->dev, xdp_prog, act);
1293 				goto err_xdp_frags;
1294 			}
1295 			*xdp_xmit |= VIRTIO_XDP_TX;
1296 			if (unlikely(xdp_page != page))
1297 				put_page(page);
1298 			rcu_read_unlock();
1299 			goto xdp_xmit;
1300 		case XDP_REDIRECT:
1301 			stats->xdp_redirects++;
1302 			err = xdp_do_redirect(dev, &xdp, xdp_prog);
1303 			if (err)
1304 				goto err_xdp_frags;
1305 			*xdp_xmit |= VIRTIO_XDP_REDIR;
1306 			if (unlikely(xdp_page != page))
1307 				put_page(page);
1308 			rcu_read_unlock();
1309 			goto xdp_xmit;
1310 		default:
1311 			bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
1312 			fallthrough;
1313 		case XDP_ABORTED:
1314 			trace_xdp_exception(vi->dev, xdp_prog, act);
1315 			fallthrough;
1316 		case XDP_DROP:
1317 			goto err_xdp_frags;
1318 		}
1319 err_xdp_frags:
1320 		if (unlikely(xdp_page != page))
1321 			__free_pages(xdp_page, 0);
1322 
1323 		if (xdp_buff_has_frags(&xdp)) {
1324 			shinfo = xdp_get_shared_info_from_buff(&xdp);
1325 			for (i = 0; i < shinfo->nr_frags; i++) {
1326 				xdp_page = skb_frag_page(&shinfo->frags[i]);
1327 				put_page(xdp_page);
1328 			}
1329 		}
1330 
1331 		goto err_xdp;
1332 	}
1333 	rcu_read_unlock();
1334 
1335 skip_xdp:
1336 	head_skb = page_to_skb(vi, rq, page, offset, len, truesize, headroom);
1337 	curr_skb = head_skb;
1338 
1339 	if (unlikely(!curr_skb))
1340 		goto err_skb;
1341 	while (--num_buf) {
1342 		int num_skb_frags;
1343 
1344 		buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1345 		if (unlikely(!buf)) {
1346 			pr_debug("%s: rx error: %d buffers out of %d missing\n",
1347 				 dev->name, num_buf,
1348 				 virtio16_to_cpu(vi->vdev,
1349 						 hdr->num_buffers));
1350 			dev->stats.rx_length_errors++;
1351 			goto err_buf;
1352 		}
1353 
1354 		stats->bytes += len;
1355 		page = virt_to_head_page(buf);
1356 
1357 		truesize = mergeable_ctx_to_truesize(ctx);
1358 		headroom = mergeable_ctx_to_headroom(ctx);
1359 		tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1360 		room = SKB_DATA_ALIGN(headroom + tailroom);
1361 		if (unlikely(len > truesize - room)) {
1362 			pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1363 				 dev->name, len, (unsigned long)(truesize - room));
1364 			dev->stats.rx_length_errors++;
1365 			goto err_skb;
1366 		}
1367 
1368 		num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1369 		if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1370 			struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1371 
1372 			if (unlikely(!nskb))
1373 				goto err_skb;
1374 			if (curr_skb == head_skb)
1375 				skb_shinfo(curr_skb)->frag_list = nskb;
1376 			else
1377 				curr_skb->next = nskb;
1378 			curr_skb = nskb;
1379 			head_skb->truesize += nskb->truesize;
1380 			num_skb_frags = 0;
1381 		}
1382 		if (curr_skb != head_skb) {
1383 			head_skb->data_len += len;
1384 			head_skb->len += len;
1385 			head_skb->truesize += truesize;
1386 		}
1387 		offset = buf - page_address(page);
1388 		if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1389 			put_page(page);
1390 			skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1391 					     len, truesize);
1392 		} else {
1393 			skb_add_rx_frag(curr_skb, num_skb_frags, page,
1394 					offset, len, truesize);
1395 		}
1396 	}
1397 
1398 	ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1399 	return head_skb;
1400 
1401 err_xdp:
1402 	rcu_read_unlock();
1403 	stats->xdp_drops++;
1404 err_skb:
1405 	put_page(page);
1406 	while (num_buf-- > 1) {
1407 		buf = virtqueue_get_buf(rq->vq, &len);
1408 		if (unlikely(!buf)) {
1409 			pr_debug("%s: rx error: %d buffers missing\n",
1410 				 dev->name, num_buf);
1411 			dev->stats.rx_length_errors++;
1412 			break;
1413 		}
1414 		stats->bytes += len;
1415 		page = virt_to_head_page(buf);
1416 		put_page(page);
1417 	}
1418 err_buf:
1419 	stats->drops++;
1420 	dev_kfree_skb(head_skb);
1421 xdp_xmit:
1422 	return NULL;
1423 }
1424 
1425 static void virtio_skb_set_hash(const struct virtio_net_hdr_v1_hash *hdr_hash,
1426 				struct sk_buff *skb)
1427 {
1428 	enum pkt_hash_types rss_hash_type;
1429 
1430 	if (!hdr_hash || !skb)
1431 		return;
1432 
1433 	switch (__le16_to_cpu(hdr_hash->hash_report)) {
1434 	case VIRTIO_NET_HASH_REPORT_TCPv4:
1435 	case VIRTIO_NET_HASH_REPORT_UDPv4:
1436 	case VIRTIO_NET_HASH_REPORT_TCPv6:
1437 	case VIRTIO_NET_HASH_REPORT_UDPv6:
1438 	case VIRTIO_NET_HASH_REPORT_TCPv6_EX:
1439 	case VIRTIO_NET_HASH_REPORT_UDPv6_EX:
1440 		rss_hash_type = PKT_HASH_TYPE_L4;
1441 		break;
1442 	case VIRTIO_NET_HASH_REPORT_IPv4:
1443 	case VIRTIO_NET_HASH_REPORT_IPv6:
1444 	case VIRTIO_NET_HASH_REPORT_IPv6_EX:
1445 		rss_hash_type = PKT_HASH_TYPE_L3;
1446 		break;
1447 	case VIRTIO_NET_HASH_REPORT_NONE:
1448 	default:
1449 		rss_hash_type = PKT_HASH_TYPE_NONE;
1450 	}
1451 	skb_set_hash(skb, __le32_to_cpu(hdr_hash->hash_value), rss_hash_type);
1452 }
1453 
1454 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1455 			void *buf, unsigned int len, void **ctx,
1456 			unsigned int *xdp_xmit,
1457 			struct virtnet_rq_stats *stats)
1458 {
1459 	struct net_device *dev = vi->dev;
1460 	struct sk_buff *skb;
1461 	struct virtio_net_hdr_mrg_rxbuf *hdr;
1462 
1463 	if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1464 		pr_debug("%s: short packet %i\n", dev->name, len);
1465 		dev->stats.rx_length_errors++;
1466 		virtnet_rq_free_unused_buf(rq->vq, buf);
1467 		return;
1468 	}
1469 
1470 	if (vi->mergeable_rx_bufs)
1471 		skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1472 					stats);
1473 	else if (vi->big_packets)
1474 		skb = receive_big(dev, vi, rq, buf, len, stats);
1475 	else
1476 		skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1477 
1478 	if (unlikely(!skb))
1479 		return;
1480 
1481 	hdr = skb_vnet_hdr(skb);
1482 	if (dev->features & NETIF_F_RXHASH && vi->has_rss_hash_report)
1483 		virtio_skb_set_hash((const struct virtio_net_hdr_v1_hash *)hdr, skb);
1484 
1485 	if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
1486 		skb->ip_summed = CHECKSUM_UNNECESSARY;
1487 
1488 	if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1489 				  virtio_is_little_endian(vi->vdev))) {
1490 		net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1491 				     dev->name, hdr->hdr.gso_type,
1492 				     hdr->hdr.gso_size);
1493 		goto frame_err;
1494 	}
1495 
1496 	skb_record_rx_queue(skb, vq2rxq(rq->vq));
1497 	skb->protocol = eth_type_trans(skb, dev);
1498 	pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1499 		 ntohs(skb->protocol), skb->len, skb->pkt_type);
1500 
1501 	napi_gro_receive(&rq->napi, skb);
1502 	return;
1503 
1504 frame_err:
1505 	dev->stats.rx_frame_errors++;
1506 	dev_kfree_skb(skb);
1507 }
1508 
1509 /* Unlike mergeable buffers, all buffers are allocated to the
1510  * same size, except for the headroom. For this reason we do
1511  * not need to use  mergeable_len_to_ctx here - it is enough
1512  * to store the headroom as the context ignoring the truesize.
1513  */
1514 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1515 			     gfp_t gfp)
1516 {
1517 	struct page_frag *alloc_frag = &rq->alloc_frag;
1518 	char *buf;
1519 	unsigned int xdp_headroom = virtnet_get_headroom(vi);
1520 	void *ctx = (void *)(unsigned long)xdp_headroom;
1521 	int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1522 	int err;
1523 
1524 	len = SKB_DATA_ALIGN(len) +
1525 	      SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1526 	if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
1527 		return -ENOMEM;
1528 
1529 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1530 	get_page(alloc_frag->page);
1531 	alloc_frag->offset += len;
1532 	sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1533 		    vi->hdr_len + GOOD_PACKET_LEN);
1534 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1535 	if (err < 0)
1536 		put_page(virt_to_head_page(buf));
1537 	return err;
1538 }
1539 
1540 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1541 			   gfp_t gfp)
1542 {
1543 	struct page *first, *list = NULL;
1544 	char *p;
1545 	int i, err, offset;
1546 
1547 	sg_init_table(rq->sg, vi->big_packets_num_skbfrags + 2);
1548 
1549 	/* page in rq->sg[vi->big_packets_num_skbfrags + 1] is list tail */
1550 	for (i = vi->big_packets_num_skbfrags + 1; i > 1; --i) {
1551 		first = get_a_page(rq, gfp);
1552 		if (!first) {
1553 			if (list)
1554 				give_pages(rq, list);
1555 			return -ENOMEM;
1556 		}
1557 		sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1558 
1559 		/* chain new page in list head to match sg */
1560 		first->private = (unsigned long)list;
1561 		list = first;
1562 	}
1563 
1564 	first = get_a_page(rq, gfp);
1565 	if (!first) {
1566 		give_pages(rq, list);
1567 		return -ENOMEM;
1568 	}
1569 	p = page_address(first);
1570 
1571 	/* rq->sg[0], rq->sg[1] share the same page */
1572 	/* a separated rq->sg[0] for header - required in case !any_header_sg */
1573 	sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1574 
1575 	/* rq->sg[1] for data packet, from offset */
1576 	offset = sizeof(struct padded_vnet_hdr);
1577 	sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1578 
1579 	/* chain first in list head */
1580 	first->private = (unsigned long)list;
1581 	err = virtqueue_add_inbuf(rq->vq, rq->sg, vi->big_packets_num_skbfrags + 2,
1582 				  first, gfp);
1583 	if (err < 0)
1584 		give_pages(rq, first);
1585 
1586 	return err;
1587 }
1588 
1589 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1590 					  struct ewma_pkt_len *avg_pkt_len,
1591 					  unsigned int room)
1592 {
1593 	struct virtnet_info *vi = rq->vq->vdev->priv;
1594 	const size_t hdr_len = vi->hdr_len;
1595 	unsigned int len;
1596 
1597 	if (room)
1598 		return PAGE_SIZE - room;
1599 
1600 	len = hdr_len +	clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1601 				rq->min_buf_len, PAGE_SIZE - hdr_len);
1602 
1603 	return ALIGN(len, L1_CACHE_BYTES);
1604 }
1605 
1606 static int add_recvbuf_mergeable(struct virtnet_info *vi,
1607 				 struct receive_queue *rq, gfp_t gfp)
1608 {
1609 	struct page_frag *alloc_frag = &rq->alloc_frag;
1610 	unsigned int headroom = virtnet_get_headroom(vi);
1611 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1612 	unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1613 	char *buf;
1614 	void *ctx;
1615 	int err;
1616 	unsigned int len, hole;
1617 
1618 	/* Extra tailroom is needed to satisfy XDP's assumption. This
1619 	 * means rx frags coalescing won't work, but consider we've
1620 	 * disabled GSO for XDP, it won't be a big issue.
1621 	 */
1622 	len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1623 	if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
1624 		return -ENOMEM;
1625 
1626 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1627 	buf += headroom; /* advance address leaving hole at front of pkt */
1628 	get_page(alloc_frag->page);
1629 	alloc_frag->offset += len + room;
1630 	hole = alloc_frag->size - alloc_frag->offset;
1631 	if (hole < len + room) {
1632 		/* To avoid internal fragmentation, if there is very likely not
1633 		 * enough space for another buffer, add the remaining space to
1634 		 * the current buffer.
1635 		 * XDP core assumes that frame_size of xdp_buff and the length
1636 		 * of the frag are PAGE_SIZE, so we disable the hole mechanism.
1637 		 */
1638 		if (!headroom)
1639 			len += hole;
1640 		alloc_frag->offset += hole;
1641 	}
1642 
1643 	sg_init_one(rq->sg, buf, len);
1644 	ctx = mergeable_len_to_ctx(len + room, headroom);
1645 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1646 	if (err < 0)
1647 		put_page(virt_to_head_page(buf));
1648 
1649 	return err;
1650 }
1651 
1652 /*
1653  * Returns false if we couldn't fill entirely (OOM).
1654  *
1655  * Normally run in the receive path, but can also be run from ndo_open
1656  * before we're receiving packets, or from refill_work which is
1657  * careful to disable receiving (using napi_disable).
1658  */
1659 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1660 			  gfp_t gfp)
1661 {
1662 	int err;
1663 	bool oom;
1664 
1665 	do {
1666 		if (vi->mergeable_rx_bufs)
1667 			err = add_recvbuf_mergeable(vi, rq, gfp);
1668 		else if (vi->big_packets)
1669 			err = add_recvbuf_big(vi, rq, gfp);
1670 		else
1671 			err = add_recvbuf_small(vi, rq, gfp);
1672 
1673 		oom = err == -ENOMEM;
1674 		if (err)
1675 			break;
1676 	} while (rq->vq->num_free);
1677 	if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
1678 		unsigned long flags;
1679 
1680 		flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1681 		rq->stats.kicks++;
1682 		u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1683 	}
1684 
1685 	return !oom;
1686 }
1687 
1688 static void skb_recv_done(struct virtqueue *rvq)
1689 {
1690 	struct virtnet_info *vi = rvq->vdev->priv;
1691 	struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1692 
1693 	virtqueue_napi_schedule(&rq->napi, rvq);
1694 }
1695 
1696 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
1697 {
1698 	napi_enable(napi);
1699 
1700 	/* If all buffers were filled by other side before we napi_enabled, we
1701 	 * won't get another interrupt, so process any outstanding packets now.
1702 	 * Call local_bh_enable after to trigger softIRQ processing.
1703 	 */
1704 	local_bh_disable();
1705 	virtqueue_napi_schedule(napi, vq);
1706 	local_bh_enable();
1707 }
1708 
1709 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1710 				   struct virtqueue *vq,
1711 				   struct napi_struct *napi)
1712 {
1713 	if (!napi->weight)
1714 		return;
1715 
1716 	/* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1717 	 * enable the feature if this is likely affine with the transmit path.
1718 	 */
1719 	if (!vi->affinity_hint_set) {
1720 		napi->weight = 0;
1721 		return;
1722 	}
1723 
1724 	return virtnet_napi_enable(vq, napi);
1725 }
1726 
1727 static void virtnet_napi_tx_disable(struct napi_struct *napi)
1728 {
1729 	if (napi->weight)
1730 		napi_disable(napi);
1731 }
1732 
1733 static void refill_work(struct work_struct *work)
1734 {
1735 	struct virtnet_info *vi =
1736 		container_of(work, struct virtnet_info, refill.work);
1737 	bool still_empty;
1738 	int i;
1739 
1740 	for (i = 0; i < vi->curr_queue_pairs; i++) {
1741 		struct receive_queue *rq = &vi->rq[i];
1742 
1743 		napi_disable(&rq->napi);
1744 		still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1745 		virtnet_napi_enable(rq->vq, &rq->napi);
1746 
1747 		/* In theory, this can happen: if we don't get any buffers in
1748 		 * we will *never* try to fill again.
1749 		 */
1750 		if (still_empty)
1751 			schedule_delayed_work(&vi->refill, HZ/2);
1752 	}
1753 }
1754 
1755 static int virtnet_receive(struct receive_queue *rq, int budget,
1756 			   unsigned int *xdp_xmit)
1757 {
1758 	struct virtnet_info *vi = rq->vq->vdev->priv;
1759 	struct virtnet_rq_stats stats = {};
1760 	unsigned int len;
1761 	void *buf;
1762 	int i;
1763 
1764 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
1765 		void *ctx;
1766 
1767 		while (stats.packets < budget &&
1768 		       (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1769 			receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1770 			stats.packets++;
1771 		}
1772 	} else {
1773 		while (stats.packets < budget &&
1774 		       (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1775 			receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1776 			stats.packets++;
1777 		}
1778 	}
1779 
1780 	if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1781 		if (!try_fill_recv(vi, rq, GFP_ATOMIC)) {
1782 			spin_lock(&vi->refill_lock);
1783 			if (vi->refill_enabled)
1784 				schedule_delayed_work(&vi->refill, 0);
1785 			spin_unlock(&vi->refill_lock);
1786 		}
1787 	}
1788 
1789 	u64_stats_update_begin(&rq->stats.syncp);
1790 	for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1791 		size_t offset = virtnet_rq_stats_desc[i].offset;
1792 		u64 *item;
1793 
1794 		item = (u64 *)((u8 *)&rq->stats + offset);
1795 		*item += *(u64 *)((u8 *)&stats + offset);
1796 	}
1797 	u64_stats_update_end(&rq->stats.syncp);
1798 
1799 	return stats.packets;
1800 }
1801 
1802 static void virtnet_poll_cleantx(struct receive_queue *rq)
1803 {
1804 	struct virtnet_info *vi = rq->vq->vdev->priv;
1805 	unsigned int index = vq2rxq(rq->vq);
1806 	struct send_queue *sq = &vi->sq[index];
1807 	struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
1808 
1809 	if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
1810 		return;
1811 
1812 	if (__netif_tx_trylock(txq)) {
1813 		if (sq->reset) {
1814 			__netif_tx_unlock(txq);
1815 			return;
1816 		}
1817 
1818 		do {
1819 			virtqueue_disable_cb(sq->vq);
1820 			free_old_xmit_skbs(sq, true);
1821 		} while (unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1822 
1823 		if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1824 			netif_tx_wake_queue(txq);
1825 
1826 		__netif_tx_unlock(txq);
1827 	}
1828 }
1829 
1830 static int virtnet_poll(struct napi_struct *napi, int budget)
1831 {
1832 	struct receive_queue *rq =
1833 		container_of(napi, struct receive_queue, napi);
1834 	struct virtnet_info *vi = rq->vq->vdev->priv;
1835 	struct send_queue *sq;
1836 	unsigned int received;
1837 	unsigned int xdp_xmit = 0;
1838 
1839 	virtnet_poll_cleantx(rq);
1840 
1841 	received = virtnet_receive(rq, budget, &xdp_xmit);
1842 
1843 	if (xdp_xmit & VIRTIO_XDP_REDIR)
1844 		xdp_do_flush();
1845 
1846 	/* Out of packets? */
1847 	if (received < budget)
1848 		virtqueue_napi_complete(napi, rq->vq, received);
1849 
1850 	if (xdp_xmit & VIRTIO_XDP_TX) {
1851 		sq = virtnet_xdp_get_sq(vi);
1852 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1853 			u64_stats_update_begin(&sq->stats.syncp);
1854 			sq->stats.kicks++;
1855 			u64_stats_update_end(&sq->stats.syncp);
1856 		}
1857 		virtnet_xdp_put_sq(vi, sq);
1858 	}
1859 
1860 	return received;
1861 }
1862 
1863 static int virtnet_open(struct net_device *dev)
1864 {
1865 	struct virtnet_info *vi = netdev_priv(dev);
1866 	int i, err;
1867 
1868 	enable_delayed_refill(vi);
1869 
1870 	for (i = 0; i < vi->max_queue_pairs; i++) {
1871 		if (i < vi->curr_queue_pairs)
1872 			/* Make sure we have some buffers: if oom use wq. */
1873 			if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1874 				schedule_delayed_work(&vi->refill, 0);
1875 
1876 		err = xdp_rxq_info_reg(&vi->rq[i].xdp_rxq, dev, i, vi->rq[i].napi.napi_id);
1877 		if (err < 0)
1878 			return err;
1879 
1880 		err = xdp_rxq_info_reg_mem_model(&vi->rq[i].xdp_rxq,
1881 						 MEM_TYPE_PAGE_SHARED, NULL);
1882 		if (err < 0) {
1883 			xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1884 			return err;
1885 		}
1886 
1887 		virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1888 		virtnet_napi_tx_enable(vi, vi->sq[i].vq, &vi->sq[i].napi);
1889 	}
1890 
1891 	return 0;
1892 }
1893 
1894 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1895 {
1896 	struct send_queue *sq = container_of(napi, struct send_queue, napi);
1897 	struct virtnet_info *vi = sq->vq->vdev->priv;
1898 	unsigned int index = vq2txq(sq->vq);
1899 	struct netdev_queue *txq;
1900 	int opaque;
1901 	bool done;
1902 
1903 	if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
1904 		/* We don't need to enable cb for XDP */
1905 		napi_complete_done(napi, 0);
1906 		return 0;
1907 	}
1908 
1909 	txq = netdev_get_tx_queue(vi->dev, index);
1910 	__netif_tx_lock(txq, raw_smp_processor_id());
1911 	virtqueue_disable_cb(sq->vq);
1912 	free_old_xmit_skbs(sq, true);
1913 
1914 	if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1915 		netif_tx_wake_queue(txq);
1916 
1917 	opaque = virtqueue_enable_cb_prepare(sq->vq);
1918 
1919 	done = napi_complete_done(napi, 0);
1920 
1921 	if (!done)
1922 		virtqueue_disable_cb(sq->vq);
1923 
1924 	__netif_tx_unlock(txq);
1925 
1926 	if (done) {
1927 		if (unlikely(virtqueue_poll(sq->vq, opaque))) {
1928 			if (napi_schedule_prep(napi)) {
1929 				__netif_tx_lock(txq, raw_smp_processor_id());
1930 				virtqueue_disable_cb(sq->vq);
1931 				__netif_tx_unlock(txq);
1932 				__napi_schedule(napi);
1933 			}
1934 		}
1935 	}
1936 
1937 	return 0;
1938 }
1939 
1940 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1941 {
1942 	struct virtio_net_hdr_mrg_rxbuf *hdr;
1943 	const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1944 	struct virtnet_info *vi = sq->vq->vdev->priv;
1945 	int num_sg;
1946 	unsigned hdr_len = vi->hdr_len;
1947 	bool can_push;
1948 
1949 	pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1950 
1951 	can_push = vi->any_header_sg &&
1952 		!((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1953 		!skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1954 	/* Even if we can, don't push here yet as this would skew
1955 	 * csum_start offset below. */
1956 	if (can_push)
1957 		hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1958 	else
1959 		hdr = skb_vnet_hdr(skb);
1960 
1961 	if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1962 				    virtio_is_little_endian(vi->vdev), false,
1963 				    0))
1964 		return -EPROTO;
1965 
1966 	if (vi->mergeable_rx_bufs)
1967 		hdr->num_buffers = 0;
1968 
1969 	sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1970 	if (can_push) {
1971 		__skb_push(skb, hdr_len);
1972 		num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1973 		if (unlikely(num_sg < 0))
1974 			return num_sg;
1975 		/* Pull header back to avoid skew in tx bytes calculations. */
1976 		__skb_pull(skb, hdr_len);
1977 	} else {
1978 		sg_set_buf(sq->sg, hdr, hdr_len);
1979 		num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
1980 		if (unlikely(num_sg < 0))
1981 			return num_sg;
1982 		num_sg++;
1983 	}
1984 	return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1985 }
1986 
1987 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1988 {
1989 	struct virtnet_info *vi = netdev_priv(dev);
1990 	int qnum = skb_get_queue_mapping(skb);
1991 	struct send_queue *sq = &vi->sq[qnum];
1992 	int err;
1993 	struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1994 	bool kick = !netdev_xmit_more();
1995 	bool use_napi = sq->napi.weight;
1996 
1997 	/* Free up any pending old buffers before queueing new ones. */
1998 	do {
1999 		if (use_napi)
2000 			virtqueue_disable_cb(sq->vq);
2001 
2002 		free_old_xmit_skbs(sq, false);
2003 
2004 	} while (use_napi && kick &&
2005 	       unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
2006 
2007 	/* timestamp packet in software */
2008 	skb_tx_timestamp(skb);
2009 
2010 	/* Try to transmit */
2011 	err = xmit_skb(sq, skb);
2012 
2013 	/* This should not happen! */
2014 	if (unlikely(err)) {
2015 		dev->stats.tx_fifo_errors++;
2016 		if (net_ratelimit())
2017 			dev_warn(&dev->dev,
2018 				 "Unexpected TXQ (%d) queue failure: %d\n",
2019 				 qnum, err);
2020 		dev->stats.tx_dropped++;
2021 		dev_kfree_skb_any(skb);
2022 		return NETDEV_TX_OK;
2023 	}
2024 
2025 	/* Don't wait up for transmitted skbs to be freed. */
2026 	if (!use_napi) {
2027 		skb_orphan(skb);
2028 		nf_reset_ct(skb);
2029 	}
2030 
2031 	check_sq_full_and_disable(vi, dev, sq);
2032 
2033 	if (kick || netif_xmit_stopped(txq)) {
2034 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
2035 			u64_stats_update_begin(&sq->stats.syncp);
2036 			sq->stats.kicks++;
2037 			u64_stats_update_end(&sq->stats.syncp);
2038 		}
2039 	}
2040 
2041 	return NETDEV_TX_OK;
2042 }
2043 
2044 static int virtnet_rx_resize(struct virtnet_info *vi,
2045 			     struct receive_queue *rq, u32 ring_num)
2046 {
2047 	bool running = netif_running(vi->dev);
2048 	int err, qindex;
2049 
2050 	qindex = rq - vi->rq;
2051 
2052 	if (running)
2053 		napi_disable(&rq->napi);
2054 
2055 	err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_free_unused_buf);
2056 	if (err)
2057 		netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
2058 
2059 	if (!try_fill_recv(vi, rq, GFP_KERNEL))
2060 		schedule_delayed_work(&vi->refill, 0);
2061 
2062 	if (running)
2063 		virtnet_napi_enable(rq->vq, &rq->napi);
2064 	return err;
2065 }
2066 
2067 static int virtnet_tx_resize(struct virtnet_info *vi,
2068 			     struct send_queue *sq, u32 ring_num)
2069 {
2070 	bool running = netif_running(vi->dev);
2071 	struct netdev_queue *txq;
2072 	int err, qindex;
2073 
2074 	qindex = sq - vi->sq;
2075 
2076 	if (running)
2077 		virtnet_napi_tx_disable(&sq->napi);
2078 
2079 	txq = netdev_get_tx_queue(vi->dev, qindex);
2080 
2081 	/* 1. wait all ximt complete
2082 	 * 2. fix the race of netif_stop_subqueue() vs netif_start_subqueue()
2083 	 */
2084 	__netif_tx_lock_bh(txq);
2085 
2086 	/* Prevent rx poll from accessing sq. */
2087 	sq->reset = true;
2088 
2089 	/* Prevent the upper layer from trying to send packets. */
2090 	netif_stop_subqueue(vi->dev, qindex);
2091 
2092 	__netif_tx_unlock_bh(txq);
2093 
2094 	err = virtqueue_resize(sq->vq, ring_num, virtnet_sq_free_unused_buf);
2095 	if (err)
2096 		netdev_err(vi->dev, "resize tx fail: tx queue index: %d err: %d\n", qindex, err);
2097 
2098 	__netif_tx_lock_bh(txq);
2099 	sq->reset = false;
2100 	netif_tx_wake_queue(txq);
2101 	__netif_tx_unlock_bh(txq);
2102 
2103 	if (running)
2104 		virtnet_napi_tx_enable(vi, sq->vq, &sq->napi);
2105 	return err;
2106 }
2107 
2108 /*
2109  * Send command via the control virtqueue and check status.  Commands
2110  * supported by the hypervisor, as indicated by feature bits, should
2111  * never fail unless improperly formatted.
2112  */
2113 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
2114 				 struct scatterlist *out)
2115 {
2116 	struct scatterlist *sgs[4], hdr, stat;
2117 	unsigned out_num = 0, tmp;
2118 	int ret;
2119 
2120 	/* Caller should know better */
2121 	BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
2122 
2123 	vi->ctrl->status = ~0;
2124 	vi->ctrl->hdr.class = class;
2125 	vi->ctrl->hdr.cmd = cmd;
2126 	/* Add header */
2127 	sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
2128 	sgs[out_num++] = &hdr;
2129 
2130 	if (out)
2131 		sgs[out_num++] = out;
2132 
2133 	/* Add return status. */
2134 	sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
2135 	sgs[out_num] = &stat;
2136 
2137 	BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
2138 	ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
2139 	if (ret < 0) {
2140 		dev_warn(&vi->vdev->dev,
2141 			 "Failed to add sgs for command vq: %d\n.", ret);
2142 		return false;
2143 	}
2144 
2145 	if (unlikely(!virtqueue_kick(vi->cvq)))
2146 		return vi->ctrl->status == VIRTIO_NET_OK;
2147 
2148 	/* Spin for a response, the kick causes an ioport write, trapping
2149 	 * into the hypervisor, so the request should be handled immediately.
2150 	 */
2151 	while (!virtqueue_get_buf(vi->cvq, &tmp) &&
2152 	       !virtqueue_is_broken(vi->cvq))
2153 		cpu_relax();
2154 
2155 	return vi->ctrl->status == VIRTIO_NET_OK;
2156 }
2157 
2158 static int virtnet_set_mac_address(struct net_device *dev, void *p)
2159 {
2160 	struct virtnet_info *vi = netdev_priv(dev);
2161 	struct virtio_device *vdev = vi->vdev;
2162 	int ret;
2163 	struct sockaddr *addr;
2164 	struct scatterlist sg;
2165 
2166 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2167 		return -EOPNOTSUPP;
2168 
2169 	addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
2170 	if (!addr)
2171 		return -ENOMEM;
2172 
2173 	ret = eth_prepare_mac_addr_change(dev, addr);
2174 	if (ret)
2175 		goto out;
2176 
2177 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
2178 		sg_init_one(&sg, addr->sa_data, dev->addr_len);
2179 		if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2180 					  VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
2181 			dev_warn(&vdev->dev,
2182 				 "Failed to set mac address by vq command.\n");
2183 			ret = -EINVAL;
2184 			goto out;
2185 		}
2186 	} else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
2187 		   !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2188 		unsigned int i;
2189 
2190 		/* Naturally, this has an atomicity problem. */
2191 		for (i = 0; i < dev->addr_len; i++)
2192 			virtio_cwrite8(vdev,
2193 				       offsetof(struct virtio_net_config, mac) +
2194 				       i, addr->sa_data[i]);
2195 	}
2196 
2197 	eth_commit_mac_addr_change(dev, p);
2198 	ret = 0;
2199 
2200 out:
2201 	kfree(addr);
2202 	return ret;
2203 }
2204 
2205 static void virtnet_stats(struct net_device *dev,
2206 			  struct rtnl_link_stats64 *tot)
2207 {
2208 	struct virtnet_info *vi = netdev_priv(dev);
2209 	unsigned int start;
2210 	int i;
2211 
2212 	for (i = 0; i < vi->max_queue_pairs; i++) {
2213 		u64 tpackets, tbytes, terrors, rpackets, rbytes, rdrops;
2214 		struct receive_queue *rq = &vi->rq[i];
2215 		struct send_queue *sq = &vi->sq[i];
2216 
2217 		do {
2218 			start = u64_stats_fetch_begin(&sq->stats.syncp);
2219 			tpackets = sq->stats.packets;
2220 			tbytes   = sq->stats.bytes;
2221 			terrors  = sq->stats.tx_timeouts;
2222 		} while (u64_stats_fetch_retry(&sq->stats.syncp, start));
2223 
2224 		do {
2225 			start = u64_stats_fetch_begin(&rq->stats.syncp);
2226 			rpackets = rq->stats.packets;
2227 			rbytes   = rq->stats.bytes;
2228 			rdrops   = rq->stats.drops;
2229 		} while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2230 
2231 		tot->rx_packets += rpackets;
2232 		tot->tx_packets += tpackets;
2233 		tot->rx_bytes   += rbytes;
2234 		tot->tx_bytes   += tbytes;
2235 		tot->rx_dropped += rdrops;
2236 		tot->tx_errors  += terrors;
2237 	}
2238 
2239 	tot->tx_dropped = dev->stats.tx_dropped;
2240 	tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
2241 	tot->rx_length_errors = dev->stats.rx_length_errors;
2242 	tot->rx_frame_errors = dev->stats.rx_frame_errors;
2243 }
2244 
2245 static void virtnet_ack_link_announce(struct virtnet_info *vi)
2246 {
2247 	rtnl_lock();
2248 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
2249 				  VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
2250 		dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
2251 	rtnl_unlock();
2252 }
2253 
2254 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2255 {
2256 	struct scatterlist sg;
2257 	struct net_device *dev = vi->dev;
2258 
2259 	if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
2260 		return 0;
2261 
2262 	vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
2263 	sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
2264 
2265 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2266 				  VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
2267 		dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
2268 			 queue_pairs);
2269 		return -EINVAL;
2270 	} else {
2271 		vi->curr_queue_pairs = queue_pairs;
2272 		/* virtnet_open() will refill when device is going to up. */
2273 		if (dev->flags & IFF_UP)
2274 			schedule_delayed_work(&vi->refill, 0);
2275 	}
2276 
2277 	return 0;
2278 }
2279 
2280 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2281 {
2282 	int err;
2283 
2284 	rtnl_lock();
2285 	err = _virtnet_set_queues(vi, queue_pairs);
2286 	rtnl_unlock();
2287 	return err;
2288 }
2289 
2290 static int virtnet_close(struct net_device *dev)
2291 {
2292 	struct virtnet_info *vi = netdev_priv(dev);
2293 	int i;
2294 
2295 	/* Make sure NAPI doesn't schedule refill work */
2296 	disable_delayed_refill(vi);
2297 	/* Make sure refill_work doesn't re-enable napi! */
2298 	cancel_delayed_work_sync(&vi->refill);
2299 
2300 	for (i = 0; i < vi->max_queue_pairs; i++) {
2301 		virtnet_napi_tx_disable(&vi->sq[i].napi);
2302 		napi_disable(&vi->rq[i].napi);
2303 		xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
2304 	}
2305 
2306 	return 0;
2307 }
2308 
2309 static void virtnet_set_rx_mode(struct net_device *dev)
2310 {
2311 	struct virtnet_info *vi = netdev_priv(dev);
2312 	struct scatterlist sg[2];
2313 	struct virtio_net_ctrl_mac *mac_data;
2314 	struct netdev_hw_addr *ha;
2315 	int uc_count;
2316 	int mc_count;
2317 	void *buf;
2318 	int i;
2319 
2320 	/* We can't dynamically set ndo_set_rx_mode, so return gracefully */
2321 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
2322 		return;
2323 
2324 	vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
2325 	vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
2326 
2327 	sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
2328 
2329 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2330 				  VIRTIO_NET_CTRL_RX_PROMISC, sg))
2331 		dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
2332 			 vi->ctrl->promisc ? "en" : "dis");
2333 
2334 	sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
2335 
2336 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2337 				  VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
2338 		dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
2339 			 vi->ctrl->allmulti ? "en" : "dis");
2340 
2341 	uc_count = netdev_uc_count(dev);
2342 	mc_count = netdev_mc_count(dev);
2343 	/* MAC filter - use one buffer for both lists */
2344 	buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
2345 		      (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
2346 	mac_data = buf;
2347 	if (!buf)
2348 		return;
2349 
2350 	sg_init_table(sg, 2);
2351 
2352 	/* Store the unicast list and count in the front of the buffer */
2353 	mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2354 	i = 0;
2355 	netdev_for_each_uc_addr(ha, dev)
2356 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2357 
2358 	sg_set_buf(&sg[0], mac_data,
2359 		   sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2360 
2361 	/* multicast list and count fill the end */
2362 	mac_data = (void *)&mac_data->macs[uc_count][0];
2363 
2364 	mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2365 	i = 0;
2366 	netdev_for_each_mc_addr(ha, dev)
2367 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2368 
2369 	sg_set_buf(&sg[1], mac_data,
2370 		   sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2371 
2372 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2373 				  VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2374 		dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2375 
2376 	kfree(buf);
2377 }
2378 
2379 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
2380 				   __be16 proto, u16 vid)
2381 {
2382 	struct virtnet_info *vi = netdev_priv(dev);
2383 	struct scatterlist sg;
2384 
2385 	vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2386 	sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2387 
2388 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2389 				  VIRTIO_NET_CTRL_VLAN_ADD, &sg))
2390 		dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
2391 	return 0;
2392 }
2393 
2394 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
2395 				    __be16 proto, u16 vid)
2396 {
2397 	struct virtnet_info *vi = netdev_priv(dev);
2398 	struct scatterlist sg;
2399 
2400 	vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2401 	sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2402 
2403 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2404 				  VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2405 		dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2406 	return 0;
2407 }
2408 
2409 static void virtnet_clean_affinity(struct virtnet_info *vi)
2410 {
2411 	int i;
2412 
2413 	if (vi->affinity_hint_set) {
2414 		for (i = 0; i < vi->max_queue_pairs; i++) {
2415 			virtqueue_set_affinity(vi->rq[i].vq, NULL);
2416 			virtqueue_set_affinity(vi->sq[i].vq, NULL);
2417 		}
2418 
2419 		vi->affinity_hint_set = false;
2420 	}
2421 }
2422 
2423 static void virtnet_set_affinity(struct virtnet_info *vi)
2424 {
2425 	cpumask_var_t mask;
2426 	int stragglers;
2427 	int group_size;
2428 	int i, j, cpu;
2429 	int num_cpu;
2430 	int stride;
2431 
2432 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2433 		virtnet_clean_affinity(vi);
2434 		return;
2435 	}
2436 
2437 	num_cpu = num_online_cpus();
2438 	stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2439 	stragglers = num_cpu >= vi->curr_queue_pairs ?
2440 			num_cpu % vi->curr_queue_pairs :
2441 			0;
2442 	cpu = cpumask_first(cpu_online_mask);
2443 
2444 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2445 		group_size = stride + (i < stragglers ? 1 : 0);
2446 
2447 		for (j = 0; j < group_size; j++) {
2448 			cpumask_set_cpu(cpu, mask);
2449 			cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2450 						nr_cpu_ids, false);
2451 		}
2452 		virtqueue_set_affinity(vi->rq[i].vq, mask);
2453 		virtqueue_set_affinity(vi->sq[i].vq, mask);
2454 		__netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2455 		cpumask_clear(mask);
2456 	}
2457 
2458 	vi->affinity_hint_set = true;
2459 	free_cpumask_var(mask);
2460 }
2461 
2462 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2463 {
2464 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2465 						   node);
2466 	virtnet_set_affinity(vi);
2467 	return 0;
2468 }
2469 
2470 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2471 {
2472 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2473 						   node_dead);
2474 	virtnet_set_affinity(vi);
2475 	return 0;
2476 }
2477 
2478 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2479 {
2480 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2481 						   node);
2482 
2483 	virtnet_clean_affinity(vi);
2484 	return 0;
2485 }
2486 
2487 static enum cpuhp_state virtionet_online;
2488 
2489 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2490 {
2491 	int ret;
2492 
2493 	ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2494 	if (ret)
2495 		return ret;
2496 	ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2497 					       &vi->node_dead);
2498 	if (!ret)
2499 		return ret;
2500 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2501 	return ret;
2502 }
2503 
2504 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2505 {
2506 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2507 	cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2508 					    &vi->node_dead);
2509 }
2510 
2511 static void virtnet_get_ringparam(struct net_device *dev,
2512 				  struct ethtool_ringparam *ring,
2513 				  struct kernel_ethtool_ringparam *kernel_ring,
2514 				  struct netlink_ext_ack *extack)
2515 {
2516 	struct virtnet_info *vi = netdev_priv(dev);
2517 
2518 	ring->rx_max_pending = vi->rq[0].vq->num_max;
2519 	ring->tx_max_pending = vi->sq[0].vq->num_max;
2520 	ring->rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2521 	ring->tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2522 }
2523 
2524 static int virtnet_set_ringparam(struct net_device *dev,
2525 				 struct ethtool_ringparam *ring,
2526 				 struct kernel_ethtool_ringparam *kernel_ring,
2527 				 struct netlink_ext_ack *extack)
2528 {
2529 	struct virtnet_info *vi = netdev_priv(dev);
2530 	u32 rx_pending, tx_pending;
2531 	struct receive_queue *rq;
2532 	struct send_queue *sq;
2533 	int i, err;
2534 
2535 	if (ring->rx_mini_pending || ring->rx_jumbo_pending)
2536 		return -EINVAL;
2537 
2538 	rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2539 	tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2540 
2541 	if (ring->rx_pending == rx_pending &&
2542 	    ring->tx_pending == tx_pending)
2543 		return 0;
2544 
2545 	if (ring->rx_pending > vi->rq[0].vq->num_max)
2546 		return -EINVAL;
2547 
2548 	if (ring->tx_pending > vi->sq[0].vq->num_max)
2549 		return -EINVAL;
2550 
2551 	for (i = 0; i < vi->max_queue_pairs; i++) {
2552 		rq = vi->rq + i;
2553 		sq = vi->sq + i;
2554 
2555 		if (ring->tx_pending != tx_pending) {
2556 			err = virtnet_tx_resize(vi, sq, ring->tx_pending);
2557 			if (err)
2558 				return err;
2559 		}
2560 
2561 		if (ring->rx_pending != rx_pending) {
2562 			err = virtnet_rx_resize(vi, rq, ring->rx_pending);
2563 			if (err)
2564 				return err;
2565 		}
2566 	}
2567 
2568 	return 0;
2569 }
2570 
2571 static bool virtnet_commit_rss_command(struct virtnet_info *vi)
2572 {
2573 	struct net_device *dev = vi->dev;
2574 	struct scatterlist sgs[4];
2575 	unsigned int sg_buf_size;
2576 
2577 	/* prepare sgs */
2578 	sg_init_table(sgs, 4);
2579 
2580 	sg_buf_size = offsetof(struct virtio_net_ctrl_rss, indirection_table);
2581 	sg_set_buf(&sgs[0], &vi->ctrl->rss, sg_buf_size);
2582 
2583 	sg_buf_size = sizeof(uint16_t) * (vi->ctrl->rss.indirection_table_mask + 1);
2584 	sg_set_buf(&sgs[1], vi->ctrl->rss.indirection_table, sg_buf_size);
2585 
2586 	sg_buf_size = offsetof(struct virtio_net_ctrl_rss, key)
2587 			- offsetof(struct virtio_net_ctrl_rss, max_tx_vq);
2588 	sg_set_buf(&sgs[2], &vi->ctrl->rss.max_tx_vq, sg_buf_size);
2589 
2590 	sg_buf_size = vi->rss_key_size;
2591 	sg_set_buf(&sgs[3], vi->ctrl->rss.key, sg_buf_size);
2592 
2593 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2594 				  vi->has_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG
2595 				  : VIRTIO_NET_CTRL_MQ_HASH_CONFIG, sgs)) {
2596 		dev_warn(&dev->dev, "VIRTIONET issue with committing RSS sgs\n");
2597 		return false;
2598 	}
2599 	return true;
2600 }
2601 
2602 static void virtnet_init_default_rss(struct virtnet_info *vi)
2603 {
2604 	u32 indir_val = 0;
2605 	int i = 0;
2606 
2607 	vi->ctrl->rss.hash_types = vi->rss_hash_types_supported;
2608 	vi->rss_hash_types_saved = vi->rss_hash_types_supported;
2609 	vi->ctrl->rss.indirection_table_mask = vi->rss_indir_table_size
2610 						? vi->rss_indir_table_size - 1 : 0;
2611 	vi->ctrl->rss.unclassified_queue = 0;
2612 
2613 	for (; i < vi->rss_indir_table_size; ++i) {
2614 		indir_val = ethtool_rxfh_indir_default(i, vi->curr_queue_pairs);
2615 		vi->ctrl->rss.indirection_table[i] = indir_val;
2616 	}
2617 
2618 	vi->ctrl->rss.max_tx_vq = vi->curr_queue_pairs;
2619 	vi->ctrl->rss.hash_key_length = vi->rss_key_size;
2620 
2621 	netdev_rss_key_fill(vi->ctrl->rss.key, vi->rss_key_size);
2622 }
2623 
2624 static void virtnet_get_hashflow(const struct virtnet_info *vi, struct ethtool_rxnfc *info)
2625 {
2626 	info->data = 0;
2627 	switch (info->flow_type) {
2628 	case TCP_V4_FLOW:
2629 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
2630 			info->data = RXH_IP_SRC | RXH_IP_DST |
2631 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2632 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2633 			info->data = RXH_IP_SRC | RXH_IP_DST;
2634 		}
2635 		break;
2636 	case TCP_V6_FLOW:
2637 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
2638 			info->data = RXH_IP_SRC | RXH_IP_DST |
2639 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2640 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2641 			info->data = RXH_IP_SRC | RXH_IP_DST;
2642 		}
2643 		break;
2644 	case UDP_V4_FLOW:
2645 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
2646 			info->data = RXH_IP_SRC | RXH_IP_DST |
2647 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2648 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2649 			info->data = RXH_IP_SRC | RXH_IP_DST;
2650 		}
2651 		break;
2652 	case UDP_V6_FLOW:
2653 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
2654 			info->data = RXH_IP_SRC | RXH_IP_DST |
2655 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2656 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2657 			info->data = RXH_IP_SRC | RXH_IP_DST;
2658 		}
2659 		break;
2660 	case IPV4_FLOW:
2661 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4)
2662 			info->data = RXH_IP_SRC | RXH_IP_DST;
2663 
2664 		break;
2665 	case IPV6_FLOW:
2666 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6)
2667 			info->data = RXH_IP_SRC | RXH_IP_DST;
2668 
2669 		break;
2670 	default:
2671 		info->data = 0;
2672 		break;
2673 	}
2674 }
2675 
2676 static bool virtnet_set_hashflow(struct virtnet_info *vi, struct ethtool_rxnfc *info)
2677 {
2678 	u32 new_hashtypes = vi->rss_hash_types_saved;
2679 	bool is_disable = info->data & RXH_DISCARD;
2680 	bool is_l4 = info->data == (RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3);
2681 
2682 	/* supports only 'sd', 'sdfn' and 'r' */
2683 	if (!((info->data == (RXH_IP_SRC | RXH_IP_DST)) | is_l4 | is_disable))
2684 		return false;
2685 
2686 	switch (info->flow_type) {
2687 	case TCP_V4_FLOW:
2688 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_TCPv4);
2689 		if (!is_disable)
2690 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2691 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0);
2692 		break;
2693 	case UDP_V4_FLOW:
2694 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_UDPv4);
2695 		if (!is_disable)
2696 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2697 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0);
2698 		break;
2699 	case IPV4_FLOW:
2700 		new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2701 		if (!is_disable)
2702 			new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2703 		break;
2704 	case TCP_V6_FLOW:
2705 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_TCPv6);
2706 		if (!is_disable)
2707 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2708 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0);
2709 		break;
2710 	case UDP_V6_FLOW:
2711 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_UDPv6);
2712 		if (!is_disable)
2713 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2714 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0);
2715 		break;
2716 	case IPV6_FLOW:
2717 		new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2718 		if (!is_disable)
2719 			new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2720 		break;
2721 	default:
2722 		/* unsupported flow */
2723 		return false;
2724 	}
2725 
2726 	/* if unsupported hashtype was set */
2727 	if (new_hashtypes != (new_hashtypes & vi->rss_hash_types_supported))
2728 		return false;
2729 
2730 	if (new_hashtypes != vi->rss_hash_types_saved) {
2731 		vi->rss_hash_types_saved = new_hashtypes;
2732 		vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
2733 		if (vi->dev->features & NETIF_F_RXHASH)
2734 			return virtnet_commit_rss_command(vi);
2735 	}
2736 
2737 	return true;
2738 }
2739 
2740 static void virtnet_get_drvinfo(struct net_device *dev,
2741 				struct ethtool_drvinfo *info)
2742 {
2743 	struct virtnet_info *vi = netdev_priv(dev);
2744 	struct virtio_device *vdev = vi->vdev;
2745 
2746 	strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2747 	strscpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2748 	strscpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2749 
2750 }
2751 
2752 /* TODO: Eliminate OOO packets during switching */
2753 static int virtnet_set_channels(struct net_device *dev,
2754 				struct ethtool_channels *channels)
2755 {
2756 	struct virtnet_info *vi = netdev_priv(dev);
2757 	u16 queue_pairs = channels->combined_count;
2758 	int err;
2759 
2760 	/* We don't support separate rx/tx channels.
2761 	 * We don't allow setting 'other' channels.
2762 	 */
2763 	if (channels->rx_count || channels->tx_count || channels->other_count)
2764 		return -EINVAL;
2765 
2766 	if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2767 		return -EINVAL;
2768 
2769 	/* For now we don't support modifying channels while XDP is loaded
2770 	 * also when XDP is loaded all RX queues have XDP programs so we only
2771 	 * need to check a single RX queue.
2772 	 */
2773 	if (vi->rq[0].xdp_prog)
2774 		return -EINVAL;
2775 
2776 	cpus_read_lock();
2777 	err = _virtnet_set_queues(vi, queue_pairs);
2778 	if (err) {
2779 		cpus_read_unlock();
2780 		goto err;
2781 	}
2782 	virtnet_set_affinity(vi);
2783 	cpus_read_unlock();
2784 
2785 	netif_set_real_num_tx_queues(dev, queue_pairs);
2786 	netif_set_real_num_rx_queues(dev, queue_pairs);
2787  err:
2788 	return err;
2789 }
2790 
2791 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2792 {
2793 	struct virtnet_info *vi = netdev_priv(dev);
2794 	unsigned int i, j;
2795 	u8 *p = data;
2796 
2797 	switch (stringset) {
2798 	case ETH_SS_STATS:
2799 		for (i = 0; i < vi->curr_queue_pairs; i++) {
2800 			for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
2801 				ethtool_sprintf(&p, "rx_queue_%u_%s", i,
2802 						virtnet_rq_stats_desc[j].desc);
2803 		}
2804 
2805 		for (i = 0; i < vi->curr_queue_pairs; i++) {
2806 			for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
2807 				ethtool_sprintf(&p, "tx_queue_%u_%s", i,
2808 						virtnet_sq_stats_desc[j].desc);
2809 		}
2810 		break;
2811 	}
2812 }
2813 
2814 static int virtnet_get_sset_count(struct net_device *dev, int sset)
2815 {
2816 	struct virtnet_info *vi = netdev_priv(dev);
2817 
2818 	switch (sset) {
2819 	case ETH_SS_STATS:
2820 		return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2821 					       VIRTNET_SQ_STATS_LEN);
2822 	default:
2823 		return -EOPNOTSUPP;
2824 	}
2825 }
2826 
2827 static void virtnet_get_ethtool_stats(struct net_device *dev,
2828 				      struct ethtool_stats *stats, u64 *data)
2829 {
2830 	struct virtnet_info *vi = netdev_priv(dev);
2831 	unsigned int idx = 0, start, i, j;
2832 	const u8 *stats_base;
2833 	size_t offset;
2834 
2835 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2836 		struct receive_queue *rq = &vi->rq[i];
2837 
2838 		stats_base = (u8 *)&rq->stats;
2839 		do {
2840 			start = u64_stats_fetch_begin(&rq->stats.syncp);
2841 			for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2842 				offset = virtnet_rq_stats_desc[j].offset;
2843 				data[idx + j] = *(u64 *)(stats_base + offset);
2844 			}
2845 		} while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2846 		idx += VIRTNET_RQ_STATS_LEN;
2847 	}
2848 
2849 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2850 		struct send_queue *sq = &vi->sq[i];
2851 
2852 		stats_base = (u8 *)&sq->stats;
2853 		do {
2854 			start = u64_stats_fetch_begin(&sq->stats.syncp);
2855 			for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2856 				offset = virtnet_sq_stats_desc[j].offset;
2857 				data[idx + j] = *(u64 *)(stats_base + offset);
2858 			}
2859 		} while (u64_stats_fetch_retry(&sq->stats.syncp, start));
2860 		idx += VIRTNET_SQ_STATS_LEN;
2861 	}
2862 }
2863 
2864 static void virtnet_get_channels(struct net_device *dev,
2865 				 struct ethtool_channels *channels)
2866 {
2867 	struct virtnet_info *vi = netdev_priv(dev);
2868 
2869 	channels->combined_count = vi->curr_queue_pairs;
2870 	channels->max_combined = vi->max_queue_pairs;
2871 	channels->max_other = 0;
2872 	channels->rx_count = 0;
2873 	channels->tx_count = 0;
2874 	channels->other_count = 0;
2875 }
2876 
2877 static int virtnet_set_link_ksettings(struct net_device *dev,
2878 				      const struct ethtool_link_ksettings *cmd)
2879 {
2880 	struct virtnet_info *vi = netdev_priv(dev);
2881 
2882 	return ethtool_virtdev_set_link_ksettings(dev, cmd,
2883 						  &vi->speed, &vi->duplex);
2884 }
2885 
2886 static int virtnet_get_link_ksettings(struct net_device *dev,
2887 				      struct ethtool_link_ksettings *cmd)
2888 {
2889 	struct virtnet_info *vi = netdev_priv(dev);
2890 
2891 	cmd->base.speed = vi->speed;
2892 	cmd->base.duplex = vi->duplex;
2893 	cmd->base.port = PORT_OTHER;
2894 
2895 	return 0;
2896 }
2897 
2898 static int virtnet_send_notf_coal_cmds(struct virtnet_info *vi,
2899 				       struct ethtool_coalesce *ec)
2900 {
2901 	struct scatterlist sgs_tx, sgs_rx;
2902 	struct virtio_net_ctrl_coal_tx coal_tx;
2903 	struct virtio_net_ctrl_coal_rx coal_rx;
2904 
2905 	coal_tx.tx_usecs = cpu_to_le32(ec->tx_coalesce_usecs);
2906 	coal_tx.tx_max_packets = cpu_to_le32(ec->tx_max_coalesced_frames);
2907 	sg_init_one(&sgs_tx, &coal_tx, sizeof(coal_tx));
2908 
2909 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2910 				  VIRTIO_NET_CTRL_NOTF_COAL_TX_SET,
2911 				  &sgs_tx))
2912 		return -EINVAL;
2913 
2914 	/* Save parameters */
2915 	vi->tx_usecs = ec->tx_coalesce_usecs;
2916 	vi->tx_max_packets = ec->tx_max_coalesced_frames;
2917 
2918 	coal_rx.rx_usecs = cpu_to_le32(ec->rx_coalesce_usecs);
2919 	coal_rx.rx_max_packets = cpu_to_le32(ec->rx_max_coalesced_frames);
2920 	sg_init_one(&sgs_rx, &coal_rx, sizeof(coal_rx));
2921 
2922 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2923 				  VIRTIO_NET_CTRL_NOTF_COAL_RX_SET,
2924 				  &sgs_rx))
2925 		return -EINVAL;
2926 
2927 	/* Save parameters */
2928 	vi->rx_usecs = ec->rx_coalesce_usecs;
2929 	vi->rx_max_packets = ec->rx_max_coalesced_frames;
2930 
2931 	return 0;
2932 }
2933 
2934 static int virtnet_coal_params_supported(struct ethtool_coalesce *ec)
2935 {
2936 	/* usecs coalescing is supported only if VIRTIO_NET_F_NOTF_COAL
2937 	 * feature is negotiated.
2938 	 */
2939 	if (ec->rx_coalesce_usecs || ec->tx_coalesce_usecs)
2940 		return -EOPNOTSUPP;
2941 
2942 	if (ec->tx_max_coalesced_frames > 1 ||
2943 	    ec->rx_max_coalesced_frames != 1)
2944 		return -EINVAL;
2945 
2946 	return 0;
2947 }
2948 
2949 static int virtnet_set_coalesce(struct net_device *dev,
2950 				struct ethtool_coalesce *ec,
2951 				struct kernel_ethtool_coalesce *kernel_coal,
2952 				struct netlink_ext_ack *extack)
2953 {
2954 	struct virtnet_info *vi = netdev_priv(dev);
2955 	int ret, i, napi_weight;
2956 	bool update_napi = false;
2957 
2958 	/* Can't change NAPI weight if the link is up */
2959 	napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
2960 	if (napi_weight ^ vi->sq[0].napi.weight) {
2961 		if (dev->flags & IFF_UP)
2962 			return -EBUSY;
2963 		else
2964 			update_napi = true;
2965 	}
2966 
2967 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL))
2968 		ret = virtnet_send_notf_coal_cmds(vi, ec);
2969 	else
2970 		ret = virtnet_coal_params_supported(ec);
2971 
2972 	if (ret)
2973 		return ret;
2974 
2975 	if (update_napi) {
2976 		for (i = 0; i < vi->max_queue_pairs; i++)
2977 			vi->sq[i].napi.weight = napi_weight;
2978 	}
2979 
2980 	return ret;
2981 }
2982 
2983 static int virtnet_get_coalesce(struct net_device *dev,
2984 				struct ethtool_coalesce *ec,
2985 				struct kernel_ethtool_coalesce *kernel_coal,
2986 				struct netlink_ext_ack *extack)
2987 {
2988 	struct virtnet_info *vi = netdev_priv(dev);
2989 
2990 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
2991 		ec->rx_coalesce_usecs = vi->rx_usecs;
2992 		ec->tx_coalesce_usecs = vi->tx_usecs;
2993 		ec->tx_max_coalesced_frames = vi->tx_max_packets;
2994 		ec->rx_max_coalesced_frames = vi->rx_max_packets;
2995 	} else {
2996 		ec->rx_max_coalesced_frames = 1;
2997 
2998 		if (vi->sq[0].napi.weight)
2999 			ec->tx_max_coalesced_frames = 1;
3000 	}
3001 
3002 	return 0;
3003 }
3004 
3005 static void virtnet_init_settings(struct net_device *dev)
3006 {
3007 	struct virtnet_info *vi = netdev_priv(dev);
3008 
3009 	vi->speed = SPEED_UNKNOWN;
3010 	vi->duplex = DUPLEX_UNKNOWN;
3011 }
3012 
3013 static void virtnet_update_settings(struct virtnet_info *vi)
3014 {
3015 	u32 speed;
3016 	u8 duplex;
3017 
3018 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
3019 		return;
3020 
3021 	virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
3022 
3023 	if (ethtool_validate_speed(speed))
3024 		vi->speed = speed;
3025 
3026 	virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
3027 
3028 	if (ethtool_validate_duplex(duplex))
3029 		vi->duplex = duplex;
3030 }
3031 
3032 static u32 virtnet_get_rxfh_key_size(struct net_device *dev)
3033 {
3034 	return ((struct virtnet_info *)netdev_priv(dev))->rss_key_size;
3035 }
3036 
3037 static u32 virtnet_get_rxfh_indir_size(struct net_device *dev)
3038 {
3039 	return ((struct virtnet_info *)netdev_priv(dev))->rss_indir_table_size;
3040 }
3041 
3042 static int virtnet_get_rxfh(struct net_device *dev, u32 *indir, u8 *key, u8 *hfunc)
3043 {
3044 	struct virtnet_info *vi = netdev_priv(dev);
3045 	int i;
3046 
3047 	if (indir) {
3048 		for (i = 0; i < vi->rss_indir_table_size; ++i)
3049 			indir[i] = vi->ctrl->rss.indirection_table[i];
3050 	}
3051 
3052 	if (key)
3053 		memcpy(key, vi->ctrl->rss.key, vi->rss_key_size);
3054 
3055 	if (hfunc)
3056 		*hfunc = ETH_RSS_HASH_TOP;
3057 
3058 	return 0;
3059 }
3060 
3061 static int virtnet_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key, const u8 hfunc)
3062 {
3063 	struct virtnet_info *vi = netdev_priv(dev);
3064 	int i;
3065 
3066 	if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
3067 		return -EOPNOTSUPP;
3068 
3069 	if (indir) {
3070 		for (i = 0; i < vi->rss_indir_table_size; ++i)
3071 			vi->ctrl->rss.indirection_table[i] = indir[i];
3072 	}
3073 	if (key)
3074 		memcpy(vi->ctrl->rss.key, key, vi->rss_key_size);
3075 
3076 	virtnet_commit_rss_command(vi);
3077 
3078 	return 0;
3079 }
3080 
3081 static int virtnet_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rule_locs)
3082 {
3083 	struct virtnet_info *vi = netdev_priv(dev);
3084 	int rc = 0;
3085 
3086 	switch (info->cmd) {
3087 	case ETHTOOL_GRXRINGS:
3088 		info->data = vi->curr_queue_pairs;
3089 		break;
3090 	case ETHTOOL_GRXFH:
3091 		virtnet_get_hashflow(vi, info);
3092 		break;
3093 	default:
3094 		rc = -EOPNOTSUPP;
3095 	}
3096 
3097 	return rc;
3098 }
3099 
3100 static int virtnet_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info)
3101 {
3102 	struct virtnet_info *vi = netdev_priv(dev);
3103 	int rc = 0;
3104 
3105 	switch (info->cmd) {
3106 	case ETHTOOL_SRXFH:
3107 		if (!virtnet_set_hashflow(vi, info))
3108 			rc = -EINVAL;
3109 
3110 		break;
3111 	default:
3112 		rc = -EOPNOTSUPP;
3113 	}
3114 
3115 	return rc;
3116 }
3117 
3118 static const struct ethtool_ops virtnet_ethtool_ops = {
3119 	.supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES |
3120 		ETHTOOL_COALESCE_USECS,
3121 	.get_drvinfo = virtnet_get_drvinfo,
3122 	.get_link = ethtool_op_get_link,
3123 	.get_ringparam = virtnet_get_ringparam,
3124 	.set_ringparam = virtnet_set_ringparam,
3125 	.get_strings = virtnet_get_strings,
3126 	.get_sset_count = virtnet_get_sset_count,
3127 	.get_ethtool_stats = virtnet_get_ethtool_stats,
3128 	.set_channels = virtnet_set_channels,
3129 	.get_channels = virtnet_get_channels,
3130 	.get_ts_info = ethtool_op_get_ts_info,
3131 	.get_link_ksettings = virtnet_get_link_ksettings,
3132 	.set_link_ksettings = virtnet_set_link_ksettings,
3133 	.set_coalesce = virtnet_set_coalesce,
3134 	.get_coalesce = virtnet_get_coalesce,
3135 	.get_rxfh_key_size = virtnet_get_rxfh_key_size,
3136 	.get_rxfh_indir_size = virtnet_get_rxfh_indir_size,
3137 	.get_rxfh = virtnet_get_rxfh,
3138 	.set_rxfh = virtnet_set_rxfh,
3139 	.get_rxnfc = virtnet_get_rxnfc,
3140 	.set_rxnfc = virtnet_set_rxnfc,
3141 };
3142 
3143 static void virtnet_freeze_down(struct virtio_device *vdev)
3144 {
3145 	struct virtnet_info *vi = vdev->priv;
3146 
3147 	/* Make sure no work handler is accessing the device */
3148 	flush_work(&vi->config_work);
3149 
3150 	netif_tx_lock_bh(vi->dev);
3151 	netif_device_detach(vi->dev);
3152 	netif_tx_unlock_bh(vi->dev);
3153 	if (netif_running(vi->dev))
3154 		virtnet_close(vi->dev);
3155 }
3156 
3157 static int init_vqs(struct virtnet_info *vi);
3158 
3159 static int virtnet_restore_up(struct virtio_device *vdev)
3160 {
3161 	struct virtnet_info *vi = vdev->priv;
3162 	int err;
3163 
3164 	err = init_vqs(vi);
3165 	if (err)
3166 		return err;
3167 
3168 	virtio_device_ready(vdev);
3169 
3170 	enable_delayed_refill(vi);
3171 
3172 	if (netif_running(vi->dev)) {
3173 		err = virtnet_open(vi->dev);
3174 		if (err)
3175 			return err;
3176 	}
3177 
3178 	netif_tx_lock_bh(vi->dev);
3179 	netif_device_attach(vi->dev);
3180 	netif_tx_unlock_bh(vi->dev);
3181 	return err;
3182 }
3183 
3184 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
3185 {
3186 	struct scatterlist sg;
3187 	vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
3188 
3189 	sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
3190 
3191 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
3192 				  VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
3193 		dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
3194 		return -EINVAL;
3195 	}
3196 
3197 	return 0;
3198 }
3199 
3200 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
3201 {
3202 	u64 offloads = 0;
3203 
3204 	if (!vi->guest_offloads)
3205 		return 0;
3206 
3207 	return virtnet_set_guest_offloads(vi, offloads);
3208 }
3209 
3210 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
3211 {
3212 	u64 offloads = vi->guest_offloads;
3213 
3214 	if (!vi->guest_offloads)
3215 		return 0;
3216 
3217 	return virtnet_set_guest_offloads(vi, offloads);
3218 }
3219 
3220 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
3221 			   struct netlink_ext_ack *extack)
3222 {
3223 	unsigned int room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
3224 					   sizeof(struct skb_shared_info));
3225 	unsigned int max_sz = PAGE_SIZE - room - ETH_HLEN;
3226 	struct virtnet_info *vi = netdev_priv(dev);
3227 	struct bpf_prog *old_prog;
3228 	u16 xdp_qp = 0, curr_qp;
3229 	int i, err;
3230 
3231 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
3232 	    && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3233 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3234 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3235 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3236 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM) ||
3237 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) ||
3238 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6))) {
3239 		NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
3240 		return -EOPNOTSUPP;
3241 	}
3242 
3243 	if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
3244 		NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
3245 		return -EINVAL;
3246 	}
3247 
3248 	if (prog && !prog->aux->xdp_has_frags && dev->mtu > max_sz) {
3249 		NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP without frags");
3250 		netdev_warn(dev, "single-buffer XDP requires MTU less than %u\n", max_sz);
3251 		return -EINVAL;
3252 	}
3253 
3254 	curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
3255 	if (prog)
3256 		xdp_qp = nr_cpu_ids;
3257 
3258 	/* XDP requires extra queues for XDP_TX */
3259 	if (curr_qp + xdp_qp > vi->max_queue_pairs) {
3260 		netdev_warn_once(dev, "XDP request %i queues but max is %i. XDP_TX and XDP_REDIRECT will operate in a slower locked tx mode.\n",
3261 				 curr_qp + xdp_qp, vi->max_queue_pairs);
3262 		xdp_qp = 0;
3263 	}
3264 
3265 	old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
3266 	if (!prog && !old_prog)
3267 		return 0;
3268 
3269 	if (prog)
3270 		bpf_prog_add(prog, vi->max_queue_pairs - 1);
3271 
3272 	/* Make sure NAPI is not using any XDP TX queues for RX. */
3273 	if (netif_running(dev)) {
3274 		for (i = 0; i < vi->max_queue_pairs; i++) {
3275 			napi_disable(&vi->rq[i].napi);
3276 			virtnet_napi_tx_disable(&vi->sq[i].napi);
3277 		}
3278 	}
3279 
3280 	if (!prog) {
3281 		for (i = 0; i < vi->max_queue_pairs; i++) {
3282 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3283 			if (i == 0)
3284 				virtnet_restore_guest_offloads(vi);
3285 		}
3286 		synchronize_net();
3287 	}
3288 
3289 	err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
3290 	if (err)
3291 		goto err;
3292 	netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
3293 	vi->xdp_queue_pairs = xdp_qp;
3294 
3295 	if (prog) {
3296 		vi->xdp_enabled = true;
3297 		for (i = 0; i < vi->max_queue_pairs; i++) {
3298 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3299 			if (i == 0 && !old_prog)
3300 				virtnet_clear_guest_offloads(vi);
3301 		}
3302 		if (!old_prog)
3303 			xdp_features_set_redirect_target(dev, true);
3304 	} else {
3305 		xdp_features_clear_redirect_target(dev);
3306 		vi->xdp_enabled = false;
3307 	}
3308 
3309 	for (i = 0; i < vi->max_queue_pairs; i++) {
3310 		if (old_prog)
3311 			bpf_prog_put(old_prog);
3312 		if (netif_running(dev)) {
3313 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3314 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3315 					       &vi->sq[i].napi);
3316 		}
3317 	}
3318 
3319 	return 0;
3320 
3321 err:
3322 	if (!prog) {
3323 		virtnet_clear_guest_offloads(vi);
3324 		for (i = 0; i < vi->max_queue_pairs; i++)
3325 			rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
3326 	}
3327 
3328 	if (netif_running(dev)) {
3329 		for (i = 0; i < vi->max_queue_pairs; i++) {
3330 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3331 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3332 					       &vi->sq[i].napi);
3333 		}
3334 	}
3335 	if (prog)
3336 		bpf_prog_sub(prog, vi->max_queue_pairs - 1);
3337 	return err;
3338 }
3339 
3340 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
3341 {
3342 	switch (xdp->command) {
3343 	case XDP_SETUP_PROG:
3344 		return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
3345 	default:
3346 		return -EINVAL;
3347 	}
3348 }
3349 
3350 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
3351 				      size_t len)
3352 {
3353 	struct virtnet_info *vi = netdev_priv(dev);
3354 	int ret;
3355 
3356 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
3357 		return -EOPNOTSUPP;
3358 
3359 	ret = snprintf(buf, len, "sby");
3360 	if (ret >= len)
3361 		return -EOPNOTSUPP;
3362 
3363 	return 0;
3364 }
3365 
3366 static int virtnet_set_features(struct net_device *dev,
3367 				netdev_features_t features)
3368 {
3369 	struct virtnet_info *vi = netdev_priv(dev);
3370 	u64 offloads;
3371 	int err;
3372 
3373 	if ((dev->features ^ features) & NETIF_F_GRO_HW) {
3374 		if (vi->xdp_enabled)
3375 			return -EBUSY;
3376 
3377 		if (features & NETIF_F_GRO_HW)
3378 			offloads = vi->guest_offloads_capable;
3379 		else
3380 			offloads = vi->guest_offloads_capable &
3381 				   ~GUEST_OFFLOAD_GRO_HW_MASK;
3382 
3383 		err = virtnet_set_guest_offloads(vi, offloads);
3384 		if (err)
3385 			return err;
3386 		vi->guest_offloads = offloads;
3387 	}
3388 
3389 	if ((dev->features ^ features) & NETIF_F_RXHASH) {
3390 		if (features & NETIF_F_RXHASH)
3391 			vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
3392 		else
3393 			vi->ctrl->rss.hash_types = VIRTIO_NET_HASH_REPORT_NONE;
3394 
3395 		if (!virtnet_commit_rss_command(vi))
3396 			return -EINVAL;
3397 	}
3398 
3399 	return 0;
3400 }
3401 
3402 static void virtnet_tx_timeout(struct net_device *dev, unsigned int txqueue)
3403 {
3404 	struct virtnet_info *priv = netdev_priv(dev);
3405 	struct send_queue *sq = &priv->sq[txqueue];
3406 	struct netdev_queue *txq = netdev_get_tx_queue(dev, txqueue);
3407 
3408 	u64_stats_update_begin(&sq->stats.syncp);
3409 	sq->stats.tx_timeouts++;
3410 	u64_stats_update_end(&sq->stats.syncp);
3411 
3412 	netdev_err(dev, "TX timeout on queue: %u, sq: %s, vq: 0x%x, name: %s, %u usecs ago\n",
3413 		   txqueue, sq->name, sq->vq->index, sq->vq->name,
3414 		   jiffies_to_usecs(jiffies - READ_ONCE(txq->trans_start)));
3415 }
3416 
3417 static const struct net_device_ops virtnet_netdev = {
3418 	.ndo_open            = virtnet_open,
3419 	.ndo_stop   	     = virtnet_close,
3420 	.ndo_start_xmit      = start_xmit,
3421 	.ndo_validate_addr   = eth_validate_addr,
3422 	.ndo_set_mac_address = virtnet_set_mac_address,
3423 	.ndo_set_rx_mode     = virtnet_set_rx_mode,
3424 	.ndo_get_stats64     = virtnet_stats,
3425 	.ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
3426 	.ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
3427 	.ndo_bpf		= virtnet_xdp,
3428 	.ndo_xdp_xmit		= virtnet_xdp_xmit,
3429 	.ndo_features_check	= passthru_features_check,
3430 	.ndo_get_phys_port_name	= virtnet_get_phys_port_name,
3431 	.ndo_set_features	= virtnet_set_features,
3432 	.ndo_tx_timeout		= virtnet_tx_timeout,
3433 };
3434 
3435 static void virtnet_config_changed_work(struct work_struct *work)
3436 {
3437 	struct virtnet_info *vi =
3438 		container_of(work, struct virtnet_info, config_work);
3439 	u16 v;
3440 
3441 	if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
3442 				 struct virtio_net_config, status, &v) < 0)
3443 		return;
3444 
3445 	if (v & VIRTIO_NET_S_ANNOUNCE) {
3446 		netdev_notify_peers(vi->dev);
3447 		virtnet_ack_link_announce(vi);
3448 	}
3449 
3450 	/* Ignore unknown (future) status bits */
3451 	v &= VIRTIO_NET_S_LINK_UP;
3452 
3453 	if (vi->status == v)
3454 		return;
3455 
3456 	vi->status = v;
3457 
3458 	if (vi->status & VIRTIO_NET_S_LINK_UP) {
3459 		virtnet_update_settings(vi);
3460 		netif_carrier_on(vi->dev);
3461 		netif_tx_wake_all_queues(vi->dev);
3462 	} else {
3463 		netif_carrier_off(vi->dev);
3464 		netif_tx_stop_all_queues(vi->dev);
3465 	}
3466 }
3467 
3468 static void virtnet_config_changed(struct virtio_device *vdev)
3469 {
3470 	struct virtnet_info *vi = vdev->priv;
3471 
3472 	schedule_work(&vi->config_work);
3473 }
3474 
3475 static void virtnet_free_queues(struct virtnet_info *vi)
3476 {
3477 	int i;
3478 
3479 	for (i = 0; i < vi->max_queue_pairs; i++) {
3480 		__netif_napi_del(&vi->rq[i].napi);
3481 		__netif_napi_del(&vi->sq[i].napi);
3482 	}
3483 
3484 	/* We called __netif_napi_del(),
3485 	 * we need to respect an RCU grace period before freeing vi->rq
3486 	 */
3487 	synchronize_net();
3488 
3489 	kfree(vi->rq);
3490 	kfree(vi->sq);
3491 	kfree(vi->ctrl);
3492 }
3493 
3494 static void _free_receive_bufs(struct virtnet_info *vi)
3495 {
3496 	struct bpf_prog *old_prog;
3497 	int i;
3498 
3499 	for (i = 0; i < vi->max_queue_pairs; i++) {
3500 		while (vi->rq[i].pages)
3501 			__free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
3502 
3503 		old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
3504 		RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
3505 		if (old_prog)
3506 			bpf_prog_put(old_prog);
3507 	}
3508 }
3509 
3510 static void free_receive_bufs(struct virtnet_info *vi)
3511 {
3512 	rtnl_lock();
3513 	_free_receive_bufs(vi);
3514 	rtnl_unlock();
3515 }
3516 
3517 static void free_receive_page_frags(struct virtnet_info *vi)
3518 {
3519 	int i;
3520 	for (i = 0; i < vi->max_queue_pairs; i++)
3521 		if (vi->rq[i].alloc_frag.page)
3522 			put_page(vi->rq[i].alloc_frag.page);
3523 }
3524 
3525 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf)
3526 {
3527 	if (!is_xdp_frame(buf))
3528 		dev_kfree_skb(buf);
3529 	else
3530 		xdp_return_frame(ptr_to_xdp(buf));
3531 }
3532 
3533 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf)
3534 {
3535 	struct virtnet_info *vi = vq->vdev->priv;
3536 	int i = vq2rxq(vq);
3537 
3538 	if (vi->mergeable_rx_bufs)
3539 		put_page(virt_to_head_page(buf));
3540 	else if (vi->big_packets)
3541 		give_pages(&vi->rq[i], buf);
3542 	else
3543 		put_page(virt_to_head_page(buf));
3544 }
3545 
3546 static void free_unused_bufs(struct virtnet_info *vi)
3547 {
3548 	void *buf;
3549 	int i;
3550 
3551 	for (i = 0; i < vi->max_queue_pairs; i++) {
3552 		struct virtqueue *vq = vi->sq[i].vq;
3553 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3554 			virtnet_sq_free_unused_buf(vq, buf);
3555 	}
3556 
3557 	for (i = 0; i < vi->max_queue_pairs; i++) {
3558 		struct virtqueue *vq = vi->rq[i].vq;
3559 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3560 			virtnet_rq_free_unused_buf(vq, buf);
3561 	}
3562 }
3563 
3564 static void virtnet_del_vqs(struct virtnet_info *vi)
3565 {
3566 	struct virtio_device *vdev = vi->vdev;
3567 
3568 	virtnet_clean_affinity(vi);
3569 
3570 	vdev->config->del_vqs(vdev);
3571 
3572 	virtnet_free_queues(vi);
3573 }
3574 
3575 /* How large should a single buffer be so a queue full of these can fit at
3576  * least one full packet?
3577  * Logic below assumes the mergeable buffer header is used.
3578  */
3579 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
3580 {
3581 	const unsigned int hdr_len = vi->hdr_len;
3582 	unsigned int rq_size = virtqueue_get_vring_size(vq);
3583 	unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
3584 	unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
3585 	unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
3586 
3587 	return max(max(min_buf_len, hdr_len) - hdr_len,
3588 		   (unsigned int)GOOD_PACKET_LEN);
3589 }
3590 
3591 static int virtnet_find_vqs(struct virtnet_info *vi)
3592 {
3593 	vq_callback_t **callbacks;
3594 	struct virtqueue **vqs;
3595 	int ret = -ENOMEM;
3596 	int i, total_vqs;
3597 	const char **names;
3598 	bool *ctx;
3599 
3600 	/* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
3601 	 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
3602 	 * possible control vq.
3603 	 */
3604 	total_vqs = vi->max_queue_pairs * 2 +
3605 		    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
3606 
3607 	/* Allocate space for find_vqs parameters */
3608 	vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
3609 	if (!vqs)
3610 		goto err_vq;
3611 	callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
3612 	if (!callbacks)
3613 		goto err_callback;
3614 	names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
3615 	if (!names)
3616 		goto err_names;
3617 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
3618 		ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
3619 		if (!ctx)
3620 			goto err_ctx;
3621 	} else {
3622 		ctx = NULL;
3623 	}
3624 
3625 	/* Parameters for control virtqueue, if any */
3626 	if (vi->has_cvq) {
3627 		callbacks[total_vqs - 1] = NULL;
3628 		names[total_vqs - 1] = "control";
3629 	}
3630 
3631 	/* Allocate/initialize parameters for send/receive virtqueues */
3632 	for (i = 0; i < vi->max_queue_pairs; i++) {
3633 		callbacks[rxq2vq(i)] = skb_recv_done;
3634 		callbacks[txq2vq(i)] = skb_xmit_done;
3635 		sprintf(vi->rq[i].name, "input.%d", i);
3636 		sprintf(vi->sq[i].name, "output.%d", i);
3637 		names[rxq2vq(i)] = vi->rq[i].name;
3638 		names[txq2vq(i)] = vi->sq[i].name;
3639 		if (ctx)
3640 			ctx[rxq2vq(i)] = true;
3641 	}
3642 
3643 	ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
3644 				  names, ctx, NULL);
3645 	if (ret)
3646 		goto err_find;
3647 
3648 	if (vi->has_cvq) {
3649 		vi->cvq = vqs[total_vqs - 1];
3650 		if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
3651 			vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
3652 	}
3653 
3654 	for (i = 0; i < vi->max_queue_pairs; i++) {
3655 		vi->rq[i].vq = vqs[rxq2vq(i)];
3656 		vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
3657 		vi->sq[i].vq = vqs[txq2vq(i)];
3658 	}
3659 
3660 	/* run here: ret == 0. */
3661 
3662 
3663 err_find:
3664 	kfree(ctx);
3665 err_ctx:
3666 	kfree(names);
3667 err_names:
3668 	kfree(callbacks);
3669 err_callback:
3670 	kfree(vqs);
3671 err_vq:
3672 	return ret;
3673 }
3674 
3675 static int virtnet_alloc_queues(struct virtnet_info *vi)
3676 {
3677 	int i;
3678 
3679 	if (vi->has_cvq) {
3680 		vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
3681 		if (!vi->ctrl)
3682 			goto err_ctrl;
3683 	} else {
3684 		vi->ctrl = NULL;
3685 	}
3686 	vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
3687 	if (!vi->sq)
3688 		goto err_sq;
3689 	vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
3690 	if (!vi->rq)
3691 		goto err_rq;
3692 
3693 	INIT_DELAYED_WORK(&vi->refill, refill_work);
3694 	for (i = 0; i < vi->max_queue_pairs; i++) {
3695 		vi->rq[i].pages = NULL;
3696 		netif_napi_add_weight(vi->dev, &vi->rq[i].napi, virtnet_poll,
3697 				      napi_weight);
3698 		netif_napi_add_tx_weight(vi->dev, &vi->sq[i].napi,
3699 					 virtnet_poll_tx,
3700 					 napi_tx ? napi_weight : 0);
3701 
3702 		sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
3703 		ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
3704 		sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
3705 
3706 		u64_stats_init(&vi->rq[i].stats.syncp);
3707 		u64_stats_init(&vi->sq[i].stats.syncp);
3708 	}
3709 
3710 	return 0;
3711 
3712 err_rq:
3713 	kfree(vi->sq);
3714 err_sq:
3715 	kfree(vi->ctrl);
3716 err_ctrl:
3717 	return -ENOMEM;
3718 }
3719 
3720 static int init_vqs(struct virtnet_info *vi)
3721 {
3722 	int ret;
3723 
3724 	/* Allocate send & receive queues */
3725 	ret = virtnet_alloc_queues(vi);
3726 	if (ret)
3727 		goto err;
3728 
3729 	ret = virtnet_find_vqs(vi);
3730 	if (ret)
3731 		goto err_free;
3732 
3733 	cpus_read_lock();
3734 	virtnet_set_affinity(vi);
3735 	cpus_read_unlock();
3736 
3737 	return 0;
3738 
3739 err_free:
3740 	virtnet_free_queues(vi);
3741 err:
3742 	return ret;
3743 }
3744 
3745 #ifdef CONFIG_SYSFS
3746 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
3747 		char *buf)
3748 {
3749 	struct virtnet_info *vi = netdev_priv(queue->dev);
3750 	unsigned int queue_index = get_netdev_rx_queue_index(queue);
3751 	unsigned int headroom = virtnet_get_headroom(vi);
3752 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
3753 	struct ewma_pkt_len *avg;
3754 
3755 	BUG_ON(queue_index >= vi->max_queue_pairs);
3756 	avg = &vi->rq[queue_index].mrg_avg_pkt_len;
3757 	return sprintf(buf, "%u\n",
3758 		       get_mergeable_buf_len(&vi->rq[queue_index], avg,
3759 				       SKB_DATA_ALIGN(headroom + tailroom)));
3760 }
3761 
3762 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
3763 	__ATTR_RO(mergeable_rx_buffer_size);
3764 
3765 static struct attribute *virtio_net_mrg_rx_attrs[] = {
3766 	&mergeable_rx_buffer_size_attribute.attr,
3767 	NULL
3768 };
3769 
3770 static const struct attribute_group virtio_net_mrg_rx_group = {
3771 	.name = "virtio_net",
3772 	.attrs = virtio_net_mrg_rx_attrs
3773 };
3774 #endif
3775 
3776 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
3777 				    unsigned int fbit,
3778 				    const char *fname, const char *dname)
3779 {
3780 	if (!virtio_has_feature(vdev, fbit))
3781 		return false;
3782 
3783 	dev_err(&vdev->dev, "device advertises feature %s but not %s",
3784 		fname, dname);
3785 
3786 	return true;
3787 }
3788 
3789 #define VIRTNET_FAIL_ON(vdev, fbit, dbit)			\
3790 	virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
3791 
3792 static bool virtnet_validate_features(struct virtio_device *vdev)
3793 {
3794 	if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
3795 	    (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
3796 			     "VIRTIO_NET_F_CTRL_VQ") ||
3797 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
3798 			     "VIRTIO_NET_F_CTRL_VQ") ||
3799 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
3800 			     "VIRTIO_NET_F_CTRL_VQ") ||
3801 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
3802 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
3803 			     "VIRTIO_NET_F_CTRL_VQ") ||
3804 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_RSS,
3805 			     "VIRTIO_NET_F_CTRL_VQ") ||
3806 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_HASH_REPORT,
3807 			     "VIRTIO_NET_F_CTRL_VQ") ||
3808 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_NOTF_COAL,
3809 			     "VIRTIO_NET_F_CTRL_VQ"))) {
3810 		return false;
3811 	}
3812 
3813 	return true;
3814 }
3815 
3816 #define MIN_MTU ETH_MIN_MTU
3817 #define MAX_MTU ETH_MAX_MTU
3818 
3819 static int virtnet_validate(struct virtio_device *vdev)
3820 {
3821 	if (!vdev->config->get) {
3822 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
3823 			__func__);
3824 		return -EINVAL;
3825 	}
3826 
3827 	if (!virtnet_validate_features(vdev))
3828 		return -EINVAL;
3829 
3830 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3831 		int mtu = virtio_cread16(vdev,
3832 					 offsetof(struct virtio_net_config,
3833 						  mtu));
3834 		if (mtu < MIN_MTU)
3835 			__virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3836 	}
3837 
3838 	if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY) &&
3839 	    !virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3840 		dev_warn(&vdev->dev, "device advertises feature VIRTIO_NET_F_STANDBY but not VIRTIO_NET_F_MAC, disabling standby");
3841 		__virtio_clear_bit(vdev, VIRTIO_NET_F_STANDBY);
3842 	}
3843 
3844 	return 0;
3845 }
3846 
3847 static bool virtnet_check_guest_gso(const struct virtnet_info *vi)
3848 {
3849 	return virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3850 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3851 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3852 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3853 		(virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) &&
3854 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6));
3855 }
3856 
3857 static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu)
3858 {
3859 	bool guest_gso = virtnet_check_guest_gso(vi);
3860 
3861 	/* If device can receive ANY guest GSO packets, regardless of mtu,
3862 	 * allocate packets of maximum size, otherwise limit it to only
3863 	 * mtu size worth only.
3864 	 */
3865 	if (mtu > ETH_DATA_LEN || guest_gso) {
3866 		vi->big_packets = true;
3867 		vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE);
3868 	}
3869 }
3870 
3871 static int virtnet_probe(struct virtio_device *vdev)
3872 {
3873 	int i, err = -ENOMEM;
3874 	struct net_device *dev;
3875 	struct virtnet_info *vi;
3876 	u16 max_queue_pairs;
3877 	int mtu = 0;
3878 
3879 	/* Find if host supports multiqueue/rss virtio_net device */
3880 	max_queue_pairs = 1;
3881 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MQ) || virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3882 		max_queue_pairs =
3883 		     virtio_cread16(vdev, offsetof(struct virtio_net_config, max_virtqueue_pairs));
3884 
3885 	/* We need at least 2 queue's */
3886 	if (max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
3887 	    max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
3888 	    !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3889 		max_queue_pairs = 1;
3890 
3891 	/* Allocate ourselves a network device with room for our info */
3892 	dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
3893 	if (!dev)
3894 		return -ENOMEM;
3895 
3896 	/* Set up network device as normal. */
3897 	dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
3898 			   IFF_TX_SKB_NO_LINEAR;
3899 	dev->netdev_ops = &virtnet_netdev;
3900 	dev->features = NETIF_F_HIGHDMA;
3901 
3902 	dev->ethtool_ops = &virtnet_ethtool_ops;
3903 	SET_NETDEV_DEV(dev, &vdev->dev);
3904 
3905 	/* Do we support "hardware" checksums? */
3906 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
3907 		/* This opens up the world of extra features. */
3908 		dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3909 		if (csum)
3910 			dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3911 
3912 		if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
3913 			dev->hw_features |= NETIF_F_TSO
3914 				| NETIF_F_TSO_ECN | NETIF_F_TSO6;
3915 		}
3916 		/* Individual feature bits: what can host handle? */
3917 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
3918 			dev->hw_features |= NETIF_F_TSO;
3919 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
3920 			dev->hw_features |= NETIF_F_TSO6;
3921 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
3922 			dev->hw_features |= NETIF_F_TSO_ECN;
3923 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_USO))
3924 			dev->hw_features |= NETIF_F_GSO_UDP_L4;
3925 
3926 		dev->features |= NETIF_F_GSO_ROBUST;
3927 
3928 		if (gso)
3929 			dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
3930 		/* (!csum && gso) case will be fixed by register_netdev() */
3931 	}
3932 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
3933 		dev->features |= NETIF_F_RXCSUM;
3934 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3935 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3936 		dev->features |= NETIF_F_GRO_HW;
3937 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3938 		dev->hw_features |= NETIF_F_GRO_HW;
3939 
3940 	dev->vlan_features = dev->features;
3941 	dev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT;
3942 
3943 	/* MTU range: 68 - 65535 */
3944 	dev->min_mtu = MIN_MTU;
3945 	dev->max_mtu = MAX_MTU;
3946 
3947 	/* Configuration may specify what MAC to use.  Otherwise random. */
3948 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3949 		u8 addr[ETH_ALEN];
3950 
3951 		virtio_cread_bytes(vdev,
3952 				   offsetof(struct virtio_net_config, mac),
3953 				   addr, ETH_ALEN);
3954 		eth_hw_addr_set(dev, addr);
3955 	} else {
3956 		eth_hw_addr_random(dev);
3957 		dev_info(&vdev->dev, "Assigned random MAC address %pM\n",
3958 			 dev->dev_addr);
3959 	}
3960 
3961 	/* Set up our device-specific information */
3962 	vi = netdev_priv(dev);
3963 	vi->dev = dev;
3964 	vi->vdev = vdev;
3965 	vdev->priv = vi;
3966 
3967 	INIT_WORK(&vi->config_work, virtnet_config_changed_work);
3968 	spin_lock_init(&vi->refill_lock);
3969 
3970 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) {
3971 		vi->mergeable_rx_bufs = true;
3972 		dev->xdp_features |= NETDEV_XDP_ACT_RX_SG;
3973 	}
3974 
3975 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
3976 		vi->rx_usecs = 0;
3977 		vi->tx_usecs = 0;
3978 		vi->tx_max_packets = 0;
3979 		vi->rx_max_packets = 0;
3980 	}
3981 
3982 	if (virtio_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT))
3983 		vi->has_rss_hash_report = true;
3984 
3985 	if (virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3986 		vi->has_rss = true;
3987 
3988 	if (vi->has_rss || vi->has_rss_hash_report) {
3989 		vi->rss_indir_table_size =
3990 			virtio_cread16(vdev, offsetof(struct virtio_net_config,
3991 				rss_max_indirection_table_length));
3992 		vi->rss_key_size =
3993 			virtio_cread8(vdev, offsetof(struct virtio_net_config, rss_max_key_size));
3994 
3995 		vi->rss_hash_types_supported =
3996 		    virtio_cread32(vdev, offsetof(struct virtio_net_config, supported_hash_types));
3997 		vi->rss_hash_types_supported &=
3998 				~(VIRTIO_NET_RSS_HASH_TYPE_IP_EX |
3999 				  VIRTIO_NET_RSS_HASH_TYPE_TCP_EX |
4000 				  VIRTIO_NET_RSS_HASH_TYPE_UDP_EX);
4001 
4002 		dev->hw_features |= NETIF_F_RXHASH;
4003 	}
4004 
4005 	if (vi->has_rss_hash_report)
4006 		vi->hdr_len = sizeof(struct virtio_net_hdr_v1_hash);
4007 	else if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
4008 		 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4009 		vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
4010 	else
4011 		vi->hdr_len = sizeof(struct virtio_net_hdr);
4012 
4013 	if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
4014 	    virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4015 		vi->any_header_sg = true;
4016 
4017 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
4018 		vi->has_cvq = true;
4019 
4020 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
4021 		mtu = virtio_cread16(vdev,
4022 				     offsetof(struct virtio_net_config,
4023 					      mtu));
4024 		if (mtu < dev->min_mtu) {
4025 			/* Should never trigger: MTU was previously validated
4026 			 * in virtnet_validate.
4027 			 */
4028 			dev_err(&vdev->dev,
4029 				"device MTU appears to have changed it is now %d < %d",
4030 				mtu, dev->min_mtu);
4031 			err = -EINVAL;
4032 			goto free;
4033 		}
4034 
4035 		dev->mtu = mtu;
4036 		dev->max_mtu = mtu;
4037 	}
4038 
4039 	virtnet_set_big_packets(vi, mtu);
4040 
4041 	if (vi->any_header_sg)
4042 		dev->needed_headroom = vi->hdr_len;
4043 
4044 	/* Enable multiqueue by default */
4045 	if (num_online_cpus() >= max_queue_pairs)
4046 		vi->curr_queue_pairs = max_queue_pairs;
4047 	else
4048 		vi->curr_queue_pairs = num_online_cpus();
4049 	vi->max_queue_pairs = max_queue_pairs;
4050 
4051 	/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
4052 	err = init_vqs(vi);
4053 	if (err)
4054 		goto free;
4055 
4056 #ifdef CONFIG_SYSFS
4057 	if (vi->mergeable_rx_bufs)
4058 		dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
4059 #endif
4060 	netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
4061 	netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
4062 
4063 	virtnet_init_settings(dev);
4064 
4065 	if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
4066 		vi->failover = net_failover_create(vi->dev);
4067 		if (IS_ERR(vi->failover)) {
4068 			err = PTR_ERR(vi->failover);
4069 			goto free_vqs;
4070 		}
4071 	}
4072 
4073 	if (vi->has_rss || vi->has_rss_hash_report)
4074 		virtnet_init_default_rss(vi);
4075 
4076 	/* serialize netdev register + virtio_device_ready() with ndo_open() */
4077 	rtnl_lock();
4078 
4079 	err = register_netdevice(dev);
4080 	if (err) {
4081 		pr_debug("virtio_net: registering device failed\n");
4082 		rtnl_unlock();
4083 		goto free_failover;
4084 	}
4085 
4086 	virtio_device_ready(vdev);
4087 
4088 	/* a random MAC address has been assigned, notify the device.
4089 	 * We don't fail probe if VIRTIO_NET_F_CTRL_MAC_ADDR is not there
4090 	 * because many devices work fine without getting MAC explicitly
4091 	 */
4092 	if (!virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
4093 	    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
4094 		struct scatterlist sg;
4095 
4096 		sg_init_one(&sg, dev->dev_addr, dev->addr_len);
4097 		if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
4098 					  VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
4099 			pr_debug("virtio_net: setting MAC address failed\n");
4100 			rtnl_unlock();
4101 			err = -EINVAL;
4102 			goto free_unregister_netdev;
4103 		}
4104 	}
4105 
4106 	rtnl_unlock();
4107 
4108 	err = virtnet_cpu_notif_add(vi);
4109 	if (err) {
4110 		pr_debug("virtio_net: registering cpu notifier failed\n");
4111 		goto free_unregister_netdev;
4112 	}
4113 
4114 	virtnet_set_queues(vi, vi->curr_queue_pairs);
4115 
4116 	/* Assume link up if device can't report link status,
4117 	   otherwise get link status from config. */
4118 	netif_carrier_off(dev);
4119 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
4120 		schedule_work(&vi->config_work);
4121 	} else {
4122 		vi->status = VIRTIO_NET_S_LINK_UP;
4123 		virtnet_update_settings(vi);
4124 		netif_carrier_on(dev);
4125 	}
4126 
4127 	for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
4128 		if (virtio_has_feature(vi->vdev, guest_offloads[i]))
4129 			set_bit(guest_offloads[i], &vi->guest_offloads);
4130 	vi->guest_offloads_capable = vi->guest_offloads;
4131 
4132 	pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
4133 		 dev->name, max_queue_pairs);
4134 
4135 	return 0;
4136 
4137 free_unregister_netdev:
4138 	unregister_netdev(dev);
4139 free_failover:
4140 	net_failover_destroy(vi->failover);
4141 free_vqs:
4142 	virtio_reset_device(vdev);
4143 	cancel_delayed_work_sync(&vi->refill);
4144 	free_receive_page_frags(vi);
4145 	virtnet_del_vqs(vi);
4146 free:
4147 	free_netdev(dev);
4148 	return err;
4149 }
4150 
4151 static void remove_vq_common(struct virtnet_info *vi)
4152 {
4153 	virtio_reset_device(vi->vdev);
4154 
4155 	/* Free unused buffers in both send and recv, if any. */
4156 	free_unused_bufs(vi);
4157 
4158 	free_receive_bufs(vi);
4159 
4160 	free_receive_page_frags(vi);
4161 
4162 	virtnet_del_vqs(vi);
4163 }
4164 
4165 static void virtnet_remove(struct virtio_device *vdev)
4166 {
4167 	struct virtnet_info *vi = vdev->priv;
4168 
4169 	virtnet_cpu_notif_remove(vi);
4170 
4171 	/* Make sure no work handler is accessing the device. */
4172 	flush_work(&vi->config_work);
4173 
4174 	unregister_netdev(vi->dev);
4175 
4176 	net_failover_destroy(vi->failover);
4177 
4178 	remove_vq_common(vi);
4179 
4180 	free_netdev(vi->dev);
4181 }
4182 
4183 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
4184 {
4185 	struct virtnet_info *vi = vdev->priv;
4186 
4187 	virtnet_cpu_notif_remove(vi);
4188 	virtnet_freeze_down(vdev);
4189 	remove_vq_common(vi);
4190 
4191 	return 0;
4192 }
4193 
4194 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
4195 {
4196 	struct virtnet_info *vi = vdev->priv;
4197 	int err;
4198 
4199 	err = virtnet_restore_up(vdev);
4200 	if (err)
4201 		return err;
4202 	virtnet_set_queues(vi, vi->curr_queue_pairs);
4203 
4204 	err = virtnet_cpu_notif_add(vi);
4205 	if (err) {
4206 		virtnet_freeze_down(vdev);
4207 		remove_vq_common(vi);
4208 		return err;
4209 	}
4210 
4211 	return 0;
4212 }
4213 
4214 static struct virtio_device_id id_table[] = {
4215 	{ VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
4216 	{ 0 },
4217 };
4218 
4219 #define VIRTNET_FEATURES \
4220 	VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
4221 	VIRTIO_NET_F_MAC, \
4222 	VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
4223 	VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
4224 	VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
4225 	VIRTIO_NET_F_HOST_USO, VIRTIO_NET_F_GUEST_USO4, VIRTIO_NET_F_GUEST_USO6, \
4226 	VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
4227 	VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
4228 	VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
4229 	VIRTIO_NET_F_CTRL_MAC_ADDR, \
4230 	VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
4231 	VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY, \
4232 	VIRTIO_NET_F_RSS, VIRTIO_NET_F_HASH_REPORT, VIRTIO_NET_F_NOTF_COAL
4233 
4234 static unsigned int features[] = {
4235 	VIRTNET_FEATURES,
4236 };
4237 
4238 static unsigned int features_legacy[] = {
4239 	VIRTNET_FEATURES,
4240 	VIRTIO_NET_F_GSO,
4241 	VIRTIO_F_ANY_LAYOUT,
4242 };
4243 
4244 static struct virtio_driver virtio_net_driver = {
4245 	.feature_table = features,
4246 	.feature_table_size = ARRAY_SIZE(features),
4247 	.feature_table_legacy = features_legacy,
4248 	.feature_table_size_legacy = ARRAY_SIZE(features_legacy),
4249 	.driver.name =	KBUILD_MODNAME,
4250 	.driver.owner =	THIS_MODULE,
4251 	.id_table =	id_table,
4252 	.validate =	virtnet_validate,
4253 	.probe =	virtnet_probe,
4254 	.remove =	virtnet_remove,
4255 	.config_changed = virtnet_config_changed,
4256 #ifdef CONFIG_PM_SLEEP
4257 	.freeze =	virtnet_freeze,
4258 	.restore =	virtnet_restore,
4259 #endif
4260 };
4261 
4262 static __init int virtio_net_driver_init(void)
4263 {
4264 	int ret;
4265 
4266 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
4267 				      virtnet_cpu_online,
4268 				      virtnet_cpu_down_prep);
4269 	if (ret < 0)
4270 		goto out;
4271 	virtionet_online = ret;
4272 	ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
4273 				      NULL, virtnet_cpu_dead);
4274 	if (ret)
4275 		goto err_dead;
4276 	ret = register_virtio_driver(&virtio_net_driver);
4277 	if (ret)
4278 		goto err_virtio;
4279 	return 0;
4280 err_virtio:
4281 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4282 err_dead:
4283 	cpuhp_remove_multi_state(virtionet_online);
4284 out:
4285 	return ret;
4286 }
4287 module_init(virtio_net_driver_init);
4288 
4289 static __exit void virtio_net_driver_exit(void)
4290 {
4291 	unregister_virtio_driver(&virtio_net_driver);
4292 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4293 	cpuhp_remove_multi_state(virtionet_online);
4294 }
4295 module_exit(virtio_net_driver_exit);
4296 
4297 MODULE_DEVICE_TABLE(virtio, id_table);
4298 MODULE_DESCRIPTION("Virtio network driver");
4299 MODULE_LICENSE("GPL");
4300