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