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