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