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