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