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