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