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