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