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