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