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