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