xref: /linux/drivers/net/virtio_net.c (revision 1ce8460496c05379c66edc178c3c55ca4e953044)
1 /* A network driver using virtio.
2  *
3  * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, see <http://www.gnu.org/licenses/>.
17  */
18 //#define DEBUG
19 #include <linux/netdevice.h>
20 #include <linux/etherdevice.h>
21 #include <linux/ethtool.h>
22 #include <linux/module.h>
23 #include <linux/virtio.h>
24 #include <linux/virtio_net.h>
25 #include <linux/bpf.h>
26 #include <linux/bpf_trace.h>
27 #include <linux/scatterlist.h>
28 #include <linux/if_vlan.h>
29 #include <linux/slab.h>
30 #include <linux/cpu.h>
31 #include <linux/average.h>
32 
33 static int napi_weight = NAPI_POLL_WEIGHT;
34 module_param(napi_weight, int, 0444);
35 
36 static bool csum = true, gso = true;
37 module_param(csum, bool, 0444);
38 module_param(gso, bool, 0444);
39 
40 /* FIXME: MTU in config. */
41 #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
42 #define GOOD_COPY_LEN	128
43 
44 /* RX packet size EWMA. The average packet size is used to determine the packet
45  * buffer size when refilling RX rings. As the entire RX ring may be refilled
46  * at once, the weight is chosen so that the EWMA will be insensitive to short-
47  * term, transient changes in packet size.
48  */
49 DECLARE_EWMA(pkt_len, 1, 64)
50 
51 /* With mergeable buffers we align buffer address and use the low bits to
52  * encode its true size. Buffer size is up to 1 page so we need to align to
53  * square root of page size to ensure we reserve enough bits to encode the true
54  * size.
55  */
56 #define MERGEABLE_BUFFER_MIN_ALIGN_SHIFT ((PAGE_SHIFT + 1) / 2)
57 
58 /* Minimum alignment for mergeable packet buffers. */
59 #define MERGEABLE_BUFFER_ALIGN max(L1_CACHE_BYTES, \
60 				   1 << MERGEABLE_BUFFER_MIN_ALIGN_SHIFT)
61 
62 #define VIRTNET_DRIVER_VERSION "1.0.0"
63 
64 struct virtnet_stats {
65 	struct u64_stats_sync tx_syncp;
66 	struct u64_stats_sync rx_syncp;
67 	u64 tx_bytes;
68 	u64 tx_packets;
69 
70 	u64 rx_bytes;
71 	u64 rx_packets;
72 };
73 
74 /* Internal representation of a send virtqueue */
75 struct send_queue {
76 	/* Virtqueue associated with this send _queue */
77 	struct virtqueue *vq;
78 
79 	/* TX: fragments + linear part + virtio header */
80 	struct scatterlist sg[MAX_SKB_FRAGS + 2];
81 
82 	/* Name of the send queue: output.$index */
83 	char name[40];
84 };
85 
86 /* Internal representation of a receive virtqueue */
87 struct receive_queue {
88 	/* Virtqueue associated with this receive_queue */
89 	struct virtqueue *vq;
90 
91 	struct napi_struct napi;
92 
93 	struct bpf_prog __rcu *xdp_prog;
94 
95 	/* Chain pages by the private ptr. */
96 	struct page *pages;
97 
98 	/* Average packet length for mergeable receive buffers. */
99 	struct ewma_pkt_len mrg_avg_pkt_len;
100 
101 	/* Page frag for packet buffer allocation. */
102 	struct page_frag alloc_frag;
103 
104 	/* RX: fragments + linear part + virtio header */
105 	struct scatterlist sg[MAX_SKB_FRAGS + 2];
106 
107 	/* Name of this receive queue: input.$index */
108 	char name[40];
109 };
110 
111 struct virtnet_info {
112 	struct virtio_device *vdev;
113 	struct virtqueue *cvq;
114 	struct net_device *dev;
115 	struct send_queue *sq;
116 	struct receive_queue *rq;
117 	unsigned int status;
118 
119 	/* Max # of queue pairs supported by the device */
120 	u16 max_queue_pairs;
121 
122 	/* # of queue pairs currently used by the driver */
123 	u16 curr_queue_pairs;
124 
125 	/* # of XDP queue pairs currently used by the driver */
126 	u16 xdp_queue_pairs;
127 
128 	/* I like... big packets and I cannot lie! */
129 	bool big_packets;
130 
131 	/* Host will merge rx buffers for big packets (shake it! shake it!) */
132 	bool mergeable_rx_bufs;
133 
134 	/* Has control virtqueue */
135 	bool has_cvq;
136 
137 	/* Host can handle any s/g split between our header and packet data */
138 	bool any_header_sg;
139 
140 	/* Packet virtio header size */
141 	u8 hdr_len;
142 
143 	/* Active statistics */
144 	struct virtnet_stats __percpu *stats;
145 
146 	/* Work struct for refilling if we run low on memory. */
147 	struct delayed_work refill;
148 
149 	/* Work struct for config space updates */
150 	struct work_struct config_work;
151 
152 	/* Does the affinity hint is set for virtqueues? */
153 	bool affinity_hint_set;
154 
155 	/* CPU hotplug instances for online & dead */
156 	struct hlist_node node;
157 	struct hlist_node node_dead;
158 
159 	/* Control VQ buffers: protected by the rtnl lock */
160 	struct virtio_net_ctrl_hdr ctrl_hdr;
161 	virtio_net_ctrl_ack ctrl_status;
162 	struct virtio_net_ctrl_mq ctrl_mq;
163 	u8 ctrl_promisc;
164 	u8 ctrl_allmulti;
165 	u16 ctrl_vid;
166 
167 	/* Ethtool settings */
168 	u8 duplex;
169 	u32 speed;
170 };
171 
172 struct padded_vnet_hdr {
173 	struct virtio_net_hdr_mrg_rxbuf hdr;
174 	/*
175 	 * hdr is in a separate sg buffer, and data sg buffer shares same page
176 	 * with this header sg. This padding makes next sg 16 byte aligned
177 	 * after the header.
178 	 */
179 	char padding[4];
180 };
181 
182 /* Converting between virtqueue no. and kernel tx/rx queue no.
183  * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
184  */
185 static int vq2txq(struct virtqueue *vq)
186 {
187 	return (vq->index - 1) / 2;
188 }
189 
190 static int txq2vq(int txq)
191 {
192 	return txq * 2 + 1;
193 }
194 
195 static int vq2rxq(struct virtqueue *vq)
196 {
197 	return vq->index / 2;
198 }
199 
200 static int rxq2vq(int rxq)
201 {
202 	return rxq * 2;
203 }
204 
205 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
206 {
207 	return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
208 }
209 
210 /*
211  * private is used to chain pages for big packets, put the whole
212  * most recent used list in the beginning for reuse
213  */
214 static void give_pages(struct receive_queue *rq, struct page *page)
215 {
216 	struct page *end;
217 
218 	/* Find end of list, sew whole thing into vi->rq.pages. */
219 	for (end = page; end->private; end = (struct page *)end->private);
220 	end->private = (unsigned long)rq->pages;
221 	rq->pages = page;
222 }
223 
224 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
225 {
226 	struct page *p = rq->pages;
227 
228 	if (p) {
229 		rq->pages = (struct page *)p->private;
230 		/* clear private here, it is used to chain pages */
231 		p->private = 0;
232 	} else
233 		p = alloc_page(gfp_mask);
234 	return p;
235 }
236 
237 static void skb_xmit_done(struct virtqueue *vq)
238 {
239 	struct virtnet_info *vi = vq->vdev->priv;
240 
241 	/* Suppress further interrupts. */
242 	virtqueue_disable_cb(vq);
243 
244 	/* We were probably waiting for more output buffers. */
245 	netif_wake_subqueue(vi->dev, vq2txq(vq));
246 }
247 
248 static unsigned int mergeable_ctx_to_buf_truesize(unsigned long mrg_ctx)
249 {
250 	unsigned int truesize = mrg_ctx & (MERGEABLE_BUFFER_ALIGN - 1);
251 	return (truesize + 1) * MERGEABLE_BUFFER_ALIGN;
252 }
253 
254 static void *mergeable_ctx_to_buf_address(unsigned long mrg_ctx)
255 {
256 	return (void *)(mrg_ctx & -MERGEABLE_BUFFER_ALIGN);
257 
258 }
259 
260 static unsigned long mergeable_buf_to_ctx(void *buf, unsigned int truesize)
261 {
262 	unsigned int size = truesize / MERGEABLE_BUFFER_ALIGN;
263 	return (unsigned long)buf | (size - 1);
264 }
265 
266 /* Called from bottom half context */
267 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
268 				   struct receive_queue *rq,
269 				   struct page *page, unsigned int offset,
270 				   unsigned int len, unsigned int truesize)
271 {
272 	struct sk_buff *skb;
273 	struct virtio_net_hdr_mrg_rxbuf *hdr;
274 	unsigned int copy, hdr_len, hdr_padded_len;
275 	char *p;
276 
277 	p = page_address(page) + offset;
278 
279 	/* copy small packet so we can reuse these pages for small data */
280 	skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
281 	if (unlikely(!skb))
282 		return NULL;
283 
284 	hdr = skb_vnet_hdr(skb);
285 
286 	hdr_len = vi->hdr_len;
287 	if (vi->mergeable_rx_bufs)
288 		hdr_padded_len = sizeof *hdr;
289 	else
290 		hdr_padded_len = sizeof(struct padded_vnet_hdr);
291 
292 	memcpy(hdr, p, hdr_len);
293 
294 	len -= hdr_len;
295 	offset += hdr_padded_len;
296 	p += hdr_padded_len;
297 
298 	copy = len;
299 	if (copy > skb_tailroom(skb))
300 		copy = skb_tailroom(skb);
301 	memcpy(skb_put(skb, copy), p, copy);
302 
303 	len -= copy;
304 	offset += copy;
305 
306 	if (vi->mergeable_rx_bufs) {
307 		if (len)
308 			skb_add_rx_frag(skb, 0, page, offset, len, truesize);
309 		else
310 			put_page(page);
311 		return skb;
312 	}
313 
314 	/*
315 	 * Verify that we can indeed put this data into a skb.
316 	 * This is here to handle cases when the device erroneously
317 	 * tries to receive more than is possible. This is usually
318 	 * the case of a broken device.
319 	 */
320 	if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
321 		net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
322 		dev_kfree_skb(skb);
323 		return NULL;
324 	}
325 	BUG_ON(offset >= PAGE_SIZE);
326 	while (len) {
327 		unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
328 		skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
329 				frag_size, truesize);
330 		len -= frag_size;
331 		page = (struct page *)page->private;
332 		offset = 0;
333 	}
334 
335 	if (page)
336 		give_pages(rq, page);
337 
338 	return skb;
339 }
340 
341 static bool virtnet_xdp_xmit(struct virtnet_info *vi,
342 			     struct receive_queue *rq,
343 			     struct send_queue *sq,
344 			     struct xdp_buff *xdp,
345 			     void *data)
346 {
347 	struct virtio_net_hdr_mrg_rxbuf *hdr;
348 	unsigned int num_sg, len;
349 	void *xdp_sent;
350 	int err;
351 
352 	/* Free up any pending old buffers before queueing new ones. */
353 	while ((xdp_sent = virtqueue_get_buf(sq->vq, &len)) != NULL) {
354 		if (vi->mergeable_rx_bufs) {
355 			struct page *sent_page = virt_to_head_page(xdp_sent);
356 
357 			put_page(sent_page);
358 		} else { /* small buffer */
359 			struct sk_buff *skb = xdp_sent;
360 
361 			kfree_skb(skb);
362 		}
363 	}
364 
365 	if (vi->mergeable_rx_bufs) {
366 		/* Zero header and leave csum up to XDP layers */
367 		hdr = xdp->data;
368 		memset(hdr, 0, vi->hdr_len);
369 
370 		num_sg = 1;
371 		sg_init_one(sq->sg, xdp->data, xdp->data_end - xdp->data);
372 	} else { /* small buffer */
373 		struct sk_buff *skb = data;
374 
375 		/* Zero header and leave csum up to XDP layers */
376 		hdr = skb_vnet_hdr(skb);
377 		memset(hdr, 0, vi->hdr_len);
378 
379 		num_sg = 2;
380 		sg_init_table(sq->sg, 2);
381 		sg_set_buf(sq->sg, hdr, vi->hdr_len);
382 		skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
383 	}
384 	err = virtqueue_add_outbuf(sq->vq, sq->sg, num_sg,
385 				   data, GFP_ATOMIC);
386 	if (unlikely(err)) {
387 		if (vi->mergeable_rx_bufs) {
388 			struct page *page = virt_to_head_page(xdp->data);
389 
390 			put_page(page);
391 		} else /* small buffer */
392 			kfree_skb(data);
393 		/* On error abort to avoid unnecessary kick */
394 		return false;
395 	}
396 
397 	virtqueue_kick(sq->vq);
398 	return true;
399 }
400 
401 static u32 do_xdp_prog(struct virtnet_info *vi,
402 		       struct receive_queue *rq,
403 		       struct bpf_prog *xdp_prog,
404 		       void *data, int len)
405 {
406 	int hdr_padded_len;
407 	struct xdp_buff xdp;
408 	void *buf;
409 	unsigned int qp;
410 	u32 act;
411 
412 	if (vi->mergeable_rx_bufs) {
413 		hdr_padded_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
414 		xdp.data = data + hdr_padded_len;
415 		xdp.data_end = xdp.data + (len - vi->hdr_len);
416 		buf = data;
417 	} else { /* small buffers */
418 		struct sk_buff *skb = data;
419 
420 		xdp.data = skb->data;
421 		xdp.data_end = xdp.data + len;
422 		buf = skb->data;
423 	}
424 
425 	act = bpf_prog_run_xdp(xdp_prog, &xdp);
426 	switch (act) {
427 	case XDP_PASS:
428 		return XDP_PASS;
429 	case XDP_TX:
430 		qp = vi->curr_queue_pairs -
431 			vi->xdp_queue_pairs +
432 			smp_processor_id();
433 		xdp.data = buf;
434 		if (unlikely(!virtnet_xdp_xmit(vi, rq, &vi->sq[qp], &xdp,
435 					       data)))
436 			trace_xdp_exception(vi->dev, xdp_prog, act);
437 		return XDP_TX;
438 	default:
439 		bpf_warn_invalid_xdp_action(act);
440 	case XDP_ABORTED:
441 		trace_xdp_exception(vi->dev, xdp_prog, act);
442 	case XDP_DROP:
443 		return XDP_DROP;
444 	}
445 }
446 
447 static struct sk_buff *receive_small(struct net_device *dev,
448 				     struct virtnet_info *vi,
449 				     struct receive_queue *rq,
450 				     void *buf, unsigned int len)
451 {
452 	struct sk_buff * skb = buf;
453 	struct bpf_prog *xdp_prog;
454 
455 	len -= vi->hdr_len;
456 	skb_trim(skb, len);
457 
458 	rcu_read_lock();
459 	xdp_prog = rcu_dereference(rq->xdp_prog);
460 	if (xdp_prog) {
461 		struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
462 		u32 act;
463 
464 		if (unlikely(hdr->hdr.gso_type || hdr->hdr.flags))
465 			goto err_xdp;
466 		act = do_xdp_prog(vi, rq, xdp_prog, skb, len);
467 		switch (act) {
468 		case XDP_PASS:
469 			break;
470 		case XDP_TX:
471 			rcu_read_unlock();
472 			goto xdp_xmit;
473 		case XDP_DROP:
474 		default:
475 			goto err_xdp;
476 		}
477 	}
478 	rcu_read_unlock();
479 
480 	return skb;
481 
482 err_xdp:
483 	rcu_read_unlock();
484 	dev->stats.rx_dropped++;
485 	kfree_skb(skb);
486 xdp_xmit:
487 	return NULL;
488 }
489 
490 static struct sk_buff *receive_big(struct net_device *dev,
491 				   struct virtnet_info *vi,
492 				   struct receive_queue *rq,
493 				   void *buf,
494 				   unsigned int len)
495 {
496 	struct page *page = buf;
497 	struct sk_buff *skb = page_to_skb(vi, rq, page, 0, len, PAGE_SIZE);
498 
499 	if (unlikely(!skb))
500 		goto err;
501 
502 	return skb;
503 
504 err:
505 	dev->stats.rx_dropped++;
506 	give_pages(rq, page);
507 	return NULL;
508 }
509 
510 /* The conditions to enable XDP should preclude the underlying device from
511  * sending packets across multiple buffers (num_buf > 1). However per spec
512  * it does not appear to be illegal to do so but rather just against convention.
513  * So in order to avoid making a system unresponsive the packets are pushed
514  * into a page and the XDP program is run. This will be extremely slow and we
515  * push a warning to the user to fix this as soon as possible. Fixing this may
516  * require resolving the underlying hardware to determine why multiple buffers
517  * are being received or simply loading the XDP program in the ingress stack
518  * after the skb is built because there is no advantage to running it here
519  * anymore.
520  */
521 static struct page *xdp_linearize_page(struct receive_queue *rq,
522 				       u16 *num_buf,
523 				       struct page *p,
524 				       int offset,
525 				       unsigned int *len)
526 {
527 	struct page *page = alloc_page(GFP_ATOMIC);
528 	unsigned int page_off = 0;
529 
530 	if (!page)
531 		return NULL;
532 
533 	memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
534 	page_off += *len;
535 
536 	while (--*num_buf) {
537 		unsigned int buflen;
538 		unsigned long ctx;
539 		void *buf;
540 		int off;
541 
542 		ctx = (unsigned long)virtqueue_get_buf(rq->vq, &buflen);
543 		if (unlikely(!ctx))
544 			goto err_buf;
545 
546 		buf = mergeable_ctx_to_buf_address(ctx);
547 		p = virt_to_head_page(buf);
548 		off = buf - page_address(p);
549 
550 		/* guard against a misconfigured or uncooperative backend that
551 		 * is sending packet larger than the MTU.
552 		 */
553 		if ((page_off + buflen) > PAGE_SIZE) {
554 			put_page(p);
555 			goto err_buf;
556 		}
557 
558 		memcpy(page_address(page) + page_off,
559 		       page_address(p) + off, buflen);
560 		page_off += buflen;
561 		put_page(p);
562 	}
563 
564 	*len = page_off;
565 	return page;
566 err_buf:
567 	__free_pages(page, 0);
568 	return NULL;
569 }
570 
571 static struct sk_buff *receive_mergeable(struct net_device *dev,
572 					 struct virtnet_info *vi,
573 					 struct receive_queue *rq,
574 					 unsigned long ctx,
575 					 unsigned int len)
576 {
577 	void *buf = mergeable_ctx_to_buf_address(ctx);
578 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
579 	u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
580 	struct page *page = virt_to_head_page(buf);
581 	int offset = buf - page_address(page);
582 	struct sk_buff *head_skb, *curr_skb;
583 	struct bpf_prog *xdp_prog;
584 	unsigned int truesize;
585 
586 	head_skb = NULL;
587 
588 	rcu_read_lock();
589 	xdp_prog = rcu_dereference(rq->xdp_prog);
590 	if (xdp_prog) {
591 		struct page *xdp_page;
592 		u32 act;
593 
594 		/* This happens when rx buffer size is underestimated */
595 		if (unlikely(num_buf > 1)) {
596 			/* linearize data for XDP */
597 			xdp_page = xdp_linearize_page(rq, &num_buf,
598 						      page, offset, &len);
599 			if (!xdp_page)
600 				goto err_xdp;
601 			offset = 0;
602 		} else {
603 			xdp_page = page;
604 		}
605 
606 		/* Transient failure which in theory could occur if
607 		 * in-flight packets from before XDP was enabled reach
608 		 * the receive path after XDP is loaded. In practice I
609 		 * was not able to create this condition.
610 		 */
611 		if (unlikely(hdr->hdr.gso_type))
612 			goto err_xdp;
613 
614 		act = do_xdp_prog(vi, rq, xdp_prog,
615 				  page_address(xdp_page) + offset, len);
616 		switch (act) {
617 		case XDP_PASS:
618 			/* We can only create skb based on xdp_page. */
619 			if (unlikely(xdp_page != page)) {
620 				rcu_read_unlock();
621 				put_page(page);
622 				head_skb = page_to_skb(vi, rq, xdp_page,
623 						       0, len, PAGE_SIZE);
624 				ewma_pkt_len_add(&rq->mrg_avg_pkt_len, len);
625 				return head_skb;
626 			}
627 			break;
628 		case XDP_TX:
629 			ewma_pkt_len_add(&rq->mrg_avg_pkt_len, len);
630 			if (unlikely(xdp_page != page))
631 				goto err_xdp;
632 			rcu_read_unlock();
633 			goto xdp_xmit;
634 		case XDP_DROP:
635 		default:
636 			if (unlikely(xdp_page != page))
637 				__free_pages(xdp_page, 0);
638 			ewma_pkt_len_add(&rq->mrg_avg_pkt_len, len);
639 			goto err_xdp;
640 		}
641 	}
642 	rcu_read_unlock();
643 
644 	truesize = max(len, mergeable_ctx_to_buf_truesize(ctx));
645 	head_skb = page_to_skb(vi, rq, page, offset, len, truesize);
646 	curr_skb = head_skb;
647 
648 	if (unlikely(!curr_skb))
649 		goto err_skb;
650 	while (--num_buf) {
651 		int num_skb_frags;
652 
653 		ctx = (unsigned long)virtqueue_get_buf(rq->vq, &len);
654 		if (unlikely(!ctx)) {
655 			pr_debug("%s: rx error: %d buffers out of %d missing\n",
656 				 dev->name, num_buf,
657 				 virtio16_to_cpu(vi->vdev,
658 						 hdr->num_buffers));
659 			dev->stats.rx_length_errors++;
660 			goto err_buf;
661 		}
662 
663 		buf = mergeable_ctx_to_buf_address(ctx);
664 		page = virt_to_head_page(buf);
665 
666 		num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
667 		if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
668 			struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
669 
670 			if (unlikely(!nskb))
671 				goto err_skb;
672 			if (curr_skb == head_skb)
673 				skb_shinfo(curr_skb)->frag_list = nskb;
674 			else
675 				curr_skb->next = nskb;
676 			curr_skb = nskb;
677 			head_skb->truesize += nskb->truesize;
678 			num_skb_frags = 0;
679 		}
680 		truesize = max(len, mergeable_ctx_to_buf_truesize(ctx));
681 		if (curr_skb != head_skb) {
682 			head_skb->data_len += len;
683 			head_skb->len += len;
684 			head_skb->truesize += truesize;
685 		}
686 		offset = buf - page_address(page);
687 		if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
688 			put_page(page);
689 			skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
690 					     len, truesize);
691 		} else {
692 			skb_add_rx_frag(curr_skb, num_skb_frags, page,
693 					offset, len, truesize);
694 		}
695 	}
696 
697 	ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
698 	return head_skb;
699 
700 err_xdp:
701 	rcu_read_unlock();
702 err_skb:
703 	put_page(page);
704 	while (--num_buf) {
705 		ctx = (unsigned long)virtqueue_get_buf(rq->vq, &len);
706 		if (unlikely(!ctx)) {
707 			pr_debug("%s: rx error: %d buffers missing\n",
708 				 dev->name, num_buf);
709 			dev->stats.rx_length_errors++;
710 			break;
711 		}
712 		page = virt_to_head_page(mergeable_ctx_to_buf_address(ctx));
713 		put_page(page);
714 	}
715 err_buf:
716 	dev->stats.rx_dropped++;
717 	dev_kfree_skb(head_skb);
718 xdp_xmit:
719 	return NULL;
720 }
721 
722 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
723 			void *buf, unsigned int len)
724 {
725 	struct net_device *dev = vi->dev;
726 	struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
727 	struct sk_buff *skb;
728 	struct virtio_net_hdr_mrg_rxbuf *hdr;
729 
730 	if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
731 		pr_debug("%s: short packet %i\n", dev->name, len);
732 		dev->stats.rx_length_errors++;
733 		if (vi->mergeable_rx_bufs) {
734 			unsigned long ctx = (unsigned long)buf;
735 			void *base = mergeable_ctx_to_buf_address(ctx);
736 			put_page(virt_to_head_page(base));
737 		} else if (vi->big_packets) {
738 			give_pages(rq, buf);
739 		} else {
740 			dev_kfree_skb(buf);
741 		}
742 		return;
743 	}
744 
745 	if (vi->mergeable_rx_bufs)
746 		skb = receive_mergeable(dev, vi, rq, (unsigned long)buf, len);
747 	else if (vi->big_packets)
748 		skb = receive_big(dev, vi, rq, buf, len);
749 	else
750 		skb = receive_small(dev, vi, rq, buf, len);
751 
752 	if (unlikely(!skb))
753 		return;
754 
755 	hdr = skb_vnet_hdr(skb);
756 
757 	u64_stats_update_begin(&stats->rx_syncp);
758 	stats->rx_bytes += skb->len;
759 	stats->rx_packets++;
760 	u64_stats_update_end(&stats->rx_syncp);
761 
762 	if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
763 		skb->ip_summed = CHECKSUM_UNNECESSARY;
764 
765 	if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
766 				  virtio_is_little_endian(vi->vdev))) {
767 		net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
768 				     dev->name, hdr->hdr.gso_type,
769 				     hdr->hdr.gso_size);
770 		goto frame_err;
771 	}
772 
773 	skb->protocol = eth_type_trans(skb, dev);
774 	pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
775 		 ntohs(skb->protocol), skb->len, skb->pkt_type);
776 
777 	napi_gro_receive(&rq->napi, skb);
778 	return;
779 
780 frame_err:
781 	dev->stats.rx_frame_errors++;
782 	dev_kfree_skb(skb);
783 }
784 
785 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
786 			     gfp_t gfp)
787 {
788 	struct sk_buff *skb;
789 	struct virtio_net_hdr_mrg_rxbuf *hdr;
790 	int err;
791 
792 	skb = __netdev_alloc_skb_ip_align(vi->dev, GOOD_PACKET_LEN, gfp);
793 	if (unlikely(!skb))
794 		return -ENOMEM;
795 
796 	skb_put(skb, GOOD_PACKET_LEN);
797 
798 	hdr = skb_vnet_hdr(skb);
799 	sg_init_table(rq->sg, 2);
800 	sg_set_buf(rq->sg, hdr, vi->hdr_len);
801 	skb_to_sgvec(skb, rq->sg + 1, 0, skb->len);
802 
803 	err = virtqueue_add_inbuf(rq->vq, rq->sg, 2, skb, gfp);
804 	if (err < 0)
805 		dev_kfree_skb(skb);
806 
807 	return err;
808 }
809 
810 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
811 			   gfp_t gfp)
812 {
813 	struct page *first, *list = NULL;
814 	char *p;
815 	int i, err, offset;
816 
817 	sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
818 
819 	/* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
820 	for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
821 		first = get_a_page(rq, gfp);
822 		if (!first) {
823 			if (list)
824 				give_pages(rq, list);
825 			return -ENOMEM;
826 		}
827 		sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
828 
829 		/* chain new page in list head to match sg */
830 		first->private = (unsigned long)list;
831 		list = first;
832 	}
833 
834 	first = get_a_page(rq, gfp);
835 	if (!first) {
836 		give_pages(rq, list);
837 		return -ENOMEM;
838 	}
839 	p = page_address(first);
840 
841 	/* rq->sg[0], rq->sg[1] share the same page */
842 	/* a separated rq->sg[0] for header - required in case !any_header_sg */
843 	sg_set_buf(&rq->sg[0], p, vi->hdr_len);
844 
845 	/* rq->sg[1] for data packet, from offset */
846 	offset = sizeof(struct padded_vnet_hdr);
847 	sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
848 
849 	/* chain first in list head */
850 	first->private = (unsigned long)list;
851 	err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
852 				  first, gfp);
853 	if (err < 0)
854 		give_pages(rq, first);
855 
856 	return err;
857 }
858 
859 static unsigned int get_mergeable_buf_len(struct ewma_pkt_len *avg_pkt_len)
860 {
861 	const size_t hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
862 	unsigned int len;
863 
864 	len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
865 			GOOD_PACKET_LEN, PAGE_SIZE - hdr_len);
866 	return ALIGN(len, MERGEABLE_BUFFER_ALIGN);
867 }
868 
869 static int add_recvbuf_mergeable(struct receive_queue *rq, gfp_t gfp)
870 {
871 	struct page_frag *alloc_frag = &rq->alloc_frag;
872 	char *buf;
873 	unsigned long ctx;
874 	int err;
875 	unsigned int len, hole;
876 
877 	len = get_mergeable_buf_len(&rq->mrg_avg_pkt_len);
878 	if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
879 		return -ENOMEM;
880 
881 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
882 	ctx = mergeable_buf_to_ctx(buf, len);
883 	get_page(alloc_frag->page);
884 	alloc_frag->offset += len;
885 	hole = alloc_frag->size - alloc_frag->offset;
886 	if (hole < len) {
887 		/* To avoid internal fragmentation, if there is very likely not
888 		 * enough space for another buffer, add the remaining space to
889 		 * the current buffer. This extra space is not included in
890 		 * the truesize stored in ctx.
891 		 */
892 		len += hole;
893 		alloc_frag->offset += hole;
894 	}
895 
896 	sg_init_one(rq->sg, buf, len);
897 	err = virtqueue_add_inbuf(rq->vq, rq->sg, 1, (void *)ctx, gfp);
898 	if (err < 0)
899 		put_page(virt_to_head_page(buf));
900 
901 	return err;
902 }
903 
904 /*
905  * Returns false if we couldn't fill entirely (OOM).
906  *
907  * Normally run in the receive path, but can also be run from ndo_open
908  * before we're receiving packets, or from refill_work which is
909  * careful to disable receiving (using napi_disable).
910  */
911 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
912 			  gfp_t gfp)
913 {
914 	int err;
915 	bool oom;
916 
917 	gfp |= __GFP_COLD;
918 	do {
919 		if (vi->mergeable_rx_bufs)
920 			err = add_recvbuf_mergeable(rq, gfp);
921 		else if (vi->big_packets)
922 			err = add_recvbuf_big(vi, rq, gfp);
923 		else
924 			err = add_recvbuf_small(vi, rq, gfp);
925 
926 		oom = err == -ENOMEM;
927 		if (err)
928 			break;
929 	} while (rq->vq->num_free);
930 	virtqueue_kick(rq->vq);
931 	return !oom;
932 }
933 
934 static void skb_recv_done(struct virtqueue *rvq)
935 {
936 	struct virtnet_info *vi = rvq->vdev->priv;
937 	struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
938 
939 	/* Schedule NAPI, Suppress further interrupts if successful. */
940 	if (napi_schedule_prep(&rq->napi)) {
941 		virtqueue_disable_cb(rvq);
942 		__napi_schedule(&rq->napi);
943 	}
944 }
945 
946 static void virtnet_napi_enable(struct receive_queue *rq)
947 {
948 	napi_enable(&rq->napi);
949 
950 	/* If all buffers were filled by other side before we napi_enabled, we
951 	 * won't get another interrupt, so process any outstanding packets
952 	 * now.  virtnet_poll wants re-enable the queue, so we disable here.
953 	 * We synchronize against interrupts via NAPI_STATE_SCHED */
954 	if (napi_schedule_prep(&rq->napi)) {
955 		virtqueue_disable_cb(rq->vq);
956 		local_bh_disable();
957 		__napi_schedule(&rq->napi);
958 		local_bh_enable();
959 	}
960 }
961 
962 static void refill_work(struct work_struct *work)
963 {
964 	struct virtnet_info *vi =
965 		container_of(work, struct virtnet_info, refill.work);
966 	bool still_empty;
967 	int i;
968 
969 	for (i = 0; i < vi->curr_queue_pairs; i++) {
970 		struct receive_queue *rq = &vi->rq[i];
971 
972 		napi_disable(&rq->napi);
973 		still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
974 		virtnet_napi_enable(rq);
975 
976 		/* In theory, this can happen: if we don't get any buffers in
977 		 * we will *never* try to fill again.
978 		 */
979 		if (still_empty)
980 			schedule_delayed_work(&vi->refill, HZ/2);
981 	}
982 }
983 
984 static int virtnet_receive(struct receive_queue *rq, int budget)
985 {
986 	struct virtnet_info *vi = rq->vq->vdev->priv;
987 	unsigned int len, received = 0;
988 	void *buf;
989 
990 	while (received < budget &&
991 	       (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
992 		receive_buf(vi, rq, buf, len);
993 		received++;
994 	}
995 
996 	if (rq->vq->num_free > virtqueue_get_vring_size(rq->vq) / 2) {
997 		if (!try_fill_recv(vi, rq, GFP_ATOMIC))
998 			schedule_delayed_work(&vi->refill, 0);
999 	}
1000 
1001 	return received;
1002 }
1003 
1004 static int virtnet_poll(struct napi_struct *napi, int budget)
1005 {
1006 	struct receive_queue *rq =
1007 		container_of(napi, struct receive_queue, napi);
1008 	unsigned int r, received;
1009 
1010 	received = virtnet_receive(rq, budget);
1011 
1012 	/* Out of packets? */
1013 	if (received < budget) {
1014 		r = virtqueue_enable_cb_prepare(rq->vq);
1015 		napi_complete_done(napi, received);
1016 		if (unlikely(virtqueue_poll(rq->vq, r)) &&
1017 		    napi_schedule_prep(napi)) {
1018 			virtqueue_disable_cb(rq->vq);
1019 			__napi_schedule(napi);
1020 		}
1021 	}
1022 
1023 	return received;
1024 }
1025 
1026 static int virtnet_open(struct net_device *dev)
1027 {
1028 	struct virtnet_info *vi = netdev_priv(dev);
1029 	int i;
1030 
1031 	for (i = 0; i < vi->max_queue_pairs; i++) {
1032 		if (i < vi->curr_queue_pairs)
1033 			/* Make sure we have some buffers: if oom use wq. */
1034 			if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1035 				schedule_delayed_work(&vi->refill, 0);
1036 		virtnet_napi_enable(&vi->rq[i]);
1037 	}
1038 
1039 	return 0;
1040 }
1041 
1042 static void free_old_xmit_skbs(struct send_queue *sq)
1043 {
1044 	struct sk_buff *skb;
1045 	unsigned int len;
1046 	struct virtnet_info *vi = sq->vq->vdev->priv;
1047 	struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
1048 
1049 	while ((skb = virtqueue_get_buf(sq->vq, &len)) != NULL) {
1050 		pr_debug("Sent skb %p\n", skb);
1051 
1052 		u64_stats_update_begin(&stats->tx_syncp);
1053 		stats->tx_bytes += skb->len;
1054 		stats->tx_packets++;
1055 		u64_stats_update_end(&stats->tx_syncp);
1056 
1057 		dev_kfree_skb_any(skb);
1058 	}
1059 }
1060 
1061 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1062 {
1063 	struct virtio_net_hdr_mrg_rxbuf *hdr;
1064 	const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1065 	struct virtnet_info *vi = sq->vq->vdev->priv;
1066 	unsigned num_sg;
1067 	unsigned hdr_len = vi->hdr_len;
1068 	bool can_push;
1069 
1070 	pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1071 
1072 	can_push = vi->any_header_sg &&
1073 		!((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1074 		!skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1075 	/* Even if we can, don't push here yet as this would skew
1076 	 * csum_start offset below. */
1077 	if (can_push)
1078 		hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1079 	else
1080 		hdr = skb_vnet_hdr(skb);
1081 
1082 	if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1083 				    virtio_is_little_endian(vi->vdev), false))
1084 		BUG();
1085 
1086 	if (vi->mergeable_rx_bufs)
1087 		hdr->num_buffers = 0;
1088 
1089 	sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1090 	if (can_push) {
1091 		__skb_push(skb, hdr_len);
1092 		num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1093 		/* Pull header back to avoid skew in tx bytes calculations. */
1094 		__skb_pull(skb, hdr_len);
1095 	} else {
1096 		sg_set_buf(sq->sg, hdr, hdr_len);
1097 		num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len) + 1;
1098 	}
1099 	return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1100 }
1101 
1102 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1103 {
1104 	struct virtnet_info *vi = netdev_priv(dev);
1105 	int qnum = skb_get_queue_mapping(skb);
1106 	struct send_queue *sq = &vi->sq[qnum];
1107 	int err;
1108 	struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1109 	bool kick = !skb->xmit_more;
1110 
1111 	/* Free up any pending old buffers before queueing new ones. */
1112 	free_old_xmit_skbs(sq);
1113 
1114 	/* timestamp packet in software */
1115 	skb_tx_timestamp(skb);
1116 
1117 	/* Try to transmit */
1118 	err = xmit_skb(sq, skb);
1119 
1120 	/* This should not happen! */
1121 	if (unlikely(err)) {
1122 		dev->stats.tx_fifo_errors++;
1123 		if (net_ratelimit())
1124 			dev_warn(&dev->dev,
1125 				 "Unexpected TXQ (%d) queue failure: %d\n", qnum, err);
1126 		dev->stats.tx_dropped++;
1127 		dev_kfree_skb_any(skb);
1128 		return NETDEV_TX_OK;
1129 	}
1130 
1131 	/* Don't wait up for transmitted skbs to be freed. */
1132 	skb_orphan(skb);
1133 	nf_reset(skb);
1134 
1135 	/* If running out of space, stop queue to avoid getting packets that we
1136 	 * are then unable to transmit.
1137 	 * An alternative would be to force queuing layer to requeue the skb by
1138 	 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
1139 	 * returned in a normal path of operation: it means that driver is not
1140 	 * maintaining the TX queue stop/start state properly, and causes
1141 	 * the stack to do a non-trivial amount of useless work.
1142 	 * Since most packets only take 1 or 2 ring slots, stopping the queue
1143 	 * early means 16 slots are typically wasted.
1144 	 */
1145 	if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1146 		netif_stop_subqueue(dev, qnum);
1147 		if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1148 			/* More just got used, free them then recheck. */
1149 			free_old_xmit_skbs(sq);
1150 			if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1151 				netif_start_subqueue(dev, qnum);
1152 				virtqueue_disable_cb(sq->vq);
1153 			}
1154 		}
1155 	}
1156 
1157 	if (kick || netif_xmit_stopped(txq))
1158 		virtqueue_kick(sq->vq);
1159 
1160 	return NETDEV_TX_OK;
1161 }
1162 
1163 /*
1164  * Send command via the control virtqueue and check status.  Commands
1165  * supported by the hypervisor, as indicated by feature bits, should
1166  * never fail unless improperly formatted.
1167  */
1168 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1169 				 struct scatterlist *out)
1170 {
1171 	struct scatterlist *sgs[4], hdr, stat;
1172 	unsigned out_num = 0, tmp;
1173 
1174 	/* Caller should know better */
1175 	BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1176 
1177 	vi->ctrl_status = ~0;
1178 	vi->ctrl_hdr.class = class;
1179 	vi->ctrl_hdr.cmd = cmd;
1180 	/* Add header */
1181 	sg_init_one(&hdr, &vi->ctrl_hdr, sizeof(vi->ctrl_hdr));
1182 	sgs[out_num++] = &hdr;
1183 
1184 	if (out)
1185 		sgs[out_num++] = out;
1186 
1187 	/* Add return status. */
1188 	sg_init_one(&stat, &vi->ctrl_status, sizeof(vi->ctrl_status));
1189 	sgs[out_num] = &stat;
1190 
1191 	BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1192 	virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1193 
1194 	if (unlikely(!virtqueue_kick(vi->cvq)))
1195 		return vi->ctrl_status == VIRTIO_NET_OK;
1196 
1197 	/* Spin for a response, the kick causes an ioport write, trapping
1198 	 * into the hypervisor, so the request should be handled immediately.
1199 	 */
1200 	while (!virtqueue_get_buf(vi->cvq, &tmp) &&
1201 	       !virtqueue_is_broken(vi->cvq))
1202 		cpu_relax();
1203 
1204 	return vi->ctrl_status == VIRTIO_NET_OK;
1205 }
1206 
1207 static int virtnet_set_mac_address(struct net_device *dev, void *p)
1208 {
1209 	struct virtnet_info *vi = netdev_priv(dev);
1210 	struct virtio_device *vdev = vi->vdev;
1211 	int ret;
1212 	struct sockaddr *addr;
1213 	struct scatterlist sg;
1214 
1215 	addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
1216 	if (!addr)
1217 		return -ENOMEM;
1218 
1219 	ret = eth_prepare_mac_addr_change(dev, addr);
1220 	if (ret)
1221 		goto out;
1222 
1223 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1224 		sg_init_one(&sg, addr->sa_data, dev->addr_len);
1225 		if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1226 					  VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
1227 			dev_warn(&vdev->dev,
1228 				 "Failed to set mac address by vq command.\n");
1229 			ret = -EINVAL;
1230 			goto out;
1231 		}
1232 	} else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
1233 		   !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1234 		unsigned int i;
1235 
1236 		/* Naturally, this has an atomicity problem. */
1237 		for (i = 0; i < dev->addr_len; i++)
1238 			virtio_cwrite8(vdev,
1239 				       offsetof(struct virtio_net_config, mac) +
1240 				       i, addr->sa_data[i]);
1241 	}
1242 
1243 	eth_commit_mac_addr_change(dev, p);
1244 	ret = 0;
1245 
1246 out:
1247 	kfree(addr);
1248 	return ret;
1249 }
1250 
1251 static void virtnet_stats(struct net_device *dev,
1252 			  struct rtnl_link_stats64 *tot)
1253 {
1254 	struct virtnet_info *vi = netdev_priv(dev);
1255 	int cpu;
1256 	unsigned int start;
1257 
1258 	for_each_possible_cpu(cpu) {
1259 		struct virtnet_stats *stats = per_cpu_ptr(vi->stats, cpu);
1260 		u64 tpackets, tbytes, rpackets, rbytes;
1261 
1262 		do {
1263 			start = u64_stats_fetch_begin_irq(&stats->tx_syncp);
1264 			tpackets = stats->tx_packets;
1265 			tbytes   = stats->tx_bytes;
1266 		} while (u64_stats_fetch_retry_irq(&stats->tx_syncp, start));
1267 
1268 		do {
1269 			start = u64_stats_fetch_begin_irq(&stats->rx_syncp);
1270 			rpackets = stats->rx_packets;
1271 			rbytes   = stats->rx_bytes;
1272 		} while (u64_stats_fetch_retry_irq(&stats->rx_syncp, start));
1273 
1274 		tot->rx_packets += rpackets;
1275 		tot->tx_packets += tpackets;
1276 		tot->rx_bytes   += rbytes;
1277 		tot->tx_bytes   += tbytes;
1278 	}
1279 
1280 	tot->tx_dropped = dev->stats.tx_dropped;
1281 	tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
1282 	tot->rx_dropped = dev->stats.rx_dropped;
1283 	tot->rx_length_errors = dev->stats.rx_length_errors;
1284 	tot->rx_frame_errors = dev->stats.rx_frame_errors;
1285 }
1286 
1287 #ifdef CONFIG_NET_POLL_CONTROLLER
1288 static void virtnet_netpoll(struct net_device *dev)
1289 {
1290 	struct virtnet_info *vi = netdev_priv(dev);
1291 	int i;
1292 
1293 	for (i = 0; i < vi->curr_queue_pairs; i++)
1294 		napi_schedule(&vi->rq[i].napi);
1295 }
1296 #endif
1297 
1298 static void virtnet_ack_link_announce(struct virtnet_info *vi)
1299 {
1300 	rtnl_lock();
1301 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
1302 				  VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
1303 		dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
1304 	rtnl_unlock();
1305 }
1306 
1307 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1308 {
1309 	struct scatterlist sg;
1310 	struct net_device *dev = vi->dev;
1311 
1312 	if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
1313 		return 0;
1314 
1315 	vi->ctrl_mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
1316 	sg_init_one(&sg, &vi->ctrl_mq, sizeof(vi->ctrl_mq));
1317 
1318 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
1319 				  VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
1320 		dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
1321 			 queue_pairs);
1322 		return -EINVAL;
1323 	} else {
1324 		vi->curr_queue_pairs = queue_pairs;
1325 		/* virtnet_open() will refill when device is going to up. */
1326 		if (dev->flags & IFF_UP)
1327 			schedule_delayed_work(&vi->refill, 0);
1328 	}
1329 
1330 	return 0;
1331 }
1332 
1333 static int virtnet_close(struct net_device *dev)
1334 {
1335 	struct virtnet_info *vi = netdev_priv(dev);
1336 	int i;
1337 
1338 	/* Make sure refill_work doesn't re-enable napi! */
1339 	cancel_delayed_work_sync(&vi->refill);
1340 
1341 	for (i = 0; i < vi->max_queue_pairs; i++)
1342 		napi_disable(&vi->rq[i].napi);
1343 
1344 	return 0;
1345 }
1346 
1347 static void virtnet_set_rx_mode(struct net_device *dev)
1348 {
1349 	struct virtnet_info *vi = netdev_priv(dev);
1350 	struct scatterlist sg[2];
1351 	struct virtio_net_ctrl_mac *mac_data;
1352 	struct netdev_hw_addr *ha;
1353 	int uc_count;
1354 	int mc_count;
1355 	void *buf;
1356 	int i;
1357 
1358 	/* We can't dynamically set ndo_set_rx_mode, so return gracefully */
1359 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
1360 		return;
1361 
1362 	vi->ctrl_promisc = ((dev->flags & IFF_PROMISC) != 0);
1363 	vi->ctrl_allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
1364 
1365 	sg_init_one(sg, &vi->ctrl_promisc, sizeof(vi->ctrl_promisc));
1366 
1367 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1368 				  VIRTIO_NET_CTRL_RX_PROMISC, sg))
1369 		dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
1370 			 vi->ctrl_promisc ? "en" : "dis");
1371 
1372 	sg_init_one(sg, &vi->ctrl_allmulti, sizeof(vi->ctrl_allmulti));
1373 
1374 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1375 				  VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
1376 		dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
1377 			 vi->ctrl_allmulti ? "en" : "dis");
1378 
1379 	uc_count = netdev_uc_count(dev);
1380 	mc_count = netdev_mc_count(dev);
1381 	/* MAC filter - use one buffer for both lists */
1382 	buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
1383 		      (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
1384 	mac_data = buf;
1385 	if (!buf)
1386 		return;
1387 
1388 	sg_init_table(sg, 2);
1389 
1390 	/* Store the unicast list and count in the front of the buffer */
1391 	mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
1392 	i = 0;
1393 	netdev_for_each_uc_addr(ha, dev)
1394 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1395 
1396 	sg_set_buf(&sg[0], mac_data,
1397 		   sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
1398 
1399 	/* multicast list and count fill the end */
1400 	mac_data = (void *)&mac_data->macs[uc_count][0];
1401 
1402 	mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
1403 	i = 0;
1404 	netdev_for_each_mc_addr(ha, dev)
1405 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1406 
1407 	sg_set_buf(&sg[1], mac_data,
1408 		   sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
1409 
1410 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1411 				  VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
1412 		dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
1413 
1414 	kfree(buf);
1415 }
1416 
1417 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
1418 				   __be16 proto, u16 vid)
1419 {
1420 	struct virtnet_info *vi = netdev_priv(dev);
1421 	struct scatterlist sg;
1422 
1423 	vi->ctrl_vid = vid;
1424 	sg_init_one(&sg, &vi->ctrl_vid, sizeof(vi->ctrl_vid));
1425 
1426 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1427 				  VIRTIO_NET_CTRL_VLAN_ADD, &sg))
1428 		dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
1429 	return 0;
1430 }
1431 
1432 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
1433 				    __be16 proto, u16 vid)
1434 {
1435 	struct virtnet_info *vi = netdev_priv(dev);
1436 	struct scatterlist sg;
1437 
1438 	vi->ctrl_vid = vid;
1439 	sg_init_one(&sg, &vi->ctrl_vid, sizeof(vi->ctrl_vid));
1440 
1441 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1442 				  VIRTIO_NET_CTRL_VLAN_DEL, &sg))
1443 		dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
1444 	return 0;
1445 }
1446 
1447 static void virtnet_clean_affinity(struct virtnet_info *vi, long hcpu)
1448 {
1449 	int i;
1450 
1451 	if (vi->affinity_hint_set) {
1452 		for (i = 0; i < vi->max_queue_pairs; i++) {
1453 			virtqueue_set_affinity(vi->rq[i].vq, -1);
1454 			virtqueue_set_affinity(vi->sq[i].vq, -1);
1455 		}
1456 
1457 		vi->affinity_hint_set = false;
1458 	}
1459 }
1460 
1461 static void virtnet_set_affinity(struct virtnet_info *vi)
1462 {
1463 	int i;
1464 	int cpu;
1465 
1466 	/* In multiqueue mode, when the number of cpu is equal to the number of
1467 	 * queue pairs, we let the queue pairs to be private to one cpu by
1468 	 * setting the affinity hint to eliminate the contention.
1469 	 */
1470 	if (vi->curr_queue_pairs == 1 ||
1471 	    vi->max_queue_pairs != num_online_cpus()) {
1472 		virtnet_clean_affinity(vi, -1);
1473 		return;
1474 	}
1475 
1476 	i = 0;
1477 	for_each_online_cpu(cpu) {
1478 		virtqueue_set_affinity(vi->rq[i].vq, cpu);
1479 		virtqueue_set_affinity(vi->sq[i].vq, cpu);
1480 		netif_set_xps_queue(vi->dev, cpumask_of(cpu), i);
1481 		i++;
1482 	}
1483 
1484 	vi->affinity_hint_set = true;
1485 }
1486 
1487 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
1488 {
1489 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1490 						   node);
1491 	virtnet_set_affinity(vi);
1492 	return 0;
1493 }
1494 
1495 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
1496 {
1497 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1498 						   node_dead);
1499 	virtnet_set_affinity(vi);
1500 	return 0;
1501 }
1502 
1503 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
1504 {
1505 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1506 						   node);
1507 
1508 	virtnet_clean_affinity(vi, cpu);
1509 	return 0;
1510 }
1511 
1512 static enum cpuhp_state virtionet_online;
1513 
1514 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
1515 {
1516 	int ret;
1517 
1518 	ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
1519 	if (ret)
1520 		return ret;
1521 	ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
1522 					       &vi->node_dead);
1523 	if (!ret)
1524 		return ret;
1525 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
1526 	return ret;
1527 }
1528 
1529 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
1530 {
1531 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
1532 	cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
1533 					    &vi->node_dead);
1534 }
1535 
1536 static void virtnet_get_ringparam(struct net_device *dev,
1537 				struct ethtool_ringparam *ring)
1538 {
1539 	struct virtnet_info *vi = netdev_priv(dev);
1540 
1541 	ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
1542 	ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
1543 	ring->rx_pending = ring->rx_max_pending;
1544 	ring->tx_pending = ring->tx_max_pending;
1545 }
1546 
1547 
1548 static void virtnet_get_drvinfo(struct net_device *dev,
1549 				struct ethtool_drvinfo *info)
1550 {
1551 	struct virtnet_info *vi = netdev_priv(dev);
1552 	struct virtio_device *vdev = vi->vdev;
1553 
1554 	strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
1555 	strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
1556 	strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
1557 
1558 }
1559 
1560 /* TODO: Eliminate OOO packets during switching */
1561 static int virtnet_set_channels(struct net_device *dev,
1562 				struct ethtool_channels *channels)
1563 {
1564 	struct virtnet_info *vi = netdev_priv(dev);
1565 	u16 queue_pairs = channels->combined_count;
1566 	int err;
1567 
1568 	/* We don't support separate rx/tx channels.
1569 	 * We don't allow setting 'other' channels.
1570 	 */
1571 	if (channels->rx_count || channels->tx_count || channels->other_count)
1572 		return -EINVAL;
1573 
1574 	if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
1575 		return -EINVAL;
1576 
1577 	/* For now we don't support modifying channels while XDP is loaded
1578 	 * also when XDP is loaded all RX queues have XDP programs so we only
1579 	 * need to check a single RX queue.
1580 	 */
1581 	if (vi->rq[0].xdp_prog)
1582 		return -EINVAL;
1583 
1584 	get_online_cpus();
1585 	err = virtnet_set_queues(vi, queue_pairs);
1586 	if (!err) {
1587 		netif_set_real_num_tx_queues(dev, queue_pairs);
1588 		netif_set_real_num_rx_queues(dev, queue_pairs);
1589 
1590 		virtnet_set_affinity(vi);
1591 	}
1592 	put_online_cpus();
1593 
1594 	return err;
1595 }
1596 
1597 static void virtnet_get_channels(struct net_device *dev,
1598 				 struct ethtool_channels *channels)
1599 {
1600 	struct virtnet_info *vi = netdev_priv(dev);
1601 
1602 	channels->combined_count = vi->curr_queue_pairs;
1603 	channels->max_combined = vi->max_queue_pairs;
1604 	channels->max_other = 0;
1605 	channels->rx_count = 0;
1606 	channels->tx_count = 0;
1607 	channels->other_count = 0;
1608 }
1609 
1610 /* Check if the user is trying to change anything besides speed/duplex */
1611 static bool virtnet_validate_ethtool_cmd(const struct ethtool_cmd *cmd)
1612 {
1613 	struct ethtool_cmd diff1 = *cmd;
1614 	struct ethtool_cmd diff2 = {};
1615 
1616 	/* cmd is always set so we need to clear it, validate the port type
1617 	 * and also without autonegotiation we can ignore advertising
1618 	 */
1619 	ethtool_cmd_speed_set(&diff1, 0);
1620 	diff2.port = PORT_OTHER;
1621 	diff1.advertising = 0;
1622 	diff1.duplex = 0;
1623 	diff1.cmd = 0;
1624 
1625 	return !memcmp(&diff1, &diff2, sizeof(diff1));
1626 }
1627 
1628 static int virtnet_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1629 {
1630 	struct virtnet_info *vi = netdev_priv(dev);
1631 	u32 speed;
1632 
1633 	speed = ethtool_cmd_speed(cmd);
1634 	/* don't allow custom speed and duplex */
1635 	if (!ethtool_validate_speed(speed) ||
1636 	    !ethtool_validate_duplex(cmd->duplex) ||
1637 	    !virtnet_validate_ethtool_cmd(cmd))
1638 		return -EINVAL;
1639 	vi->speed = speed;
1640 	vi->duplex = cmd->duplex;
1641 
1642 	return 0;
1643 }
1644 
1645 static int virtnet_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1646 {
1647 	struct virtnet_info *vi = netdev_priv(dev);
1648 
1649 	ethtool_cmd_speed_set(cmd, vi->speed);
1650 	cmd->duplex = vi->duplex;
1651 	cmd->port = PORT_OTHER;
1652 
1653 	return 0;
1654 }
1655 
1656 static void virtnet_init_settings(struct net_device *dev)
1657 {
1658 	struct virtnet_info *vi = netdev_priv(dev);
1659 
1660 	vi->speed = SPEED_UNKNOWN;
1661 	vi->duplex = DUPLEX_UNKNOWN;
1662 }
1663 
1664 static const struct ethtool_ops virtnet_ethtool_ops = {
1665 	.get_drvinfo = virtnet_get_drvinfo,
1666 	.get_link = ethtool_op_get_link,
1667 	.get_ringparam = virtnet_get_ringparam,
1668 	.set_channels = virtnet_set_channels,
1669 	.get_channels = virtnet_get_channels,
1670 	.get_ts_info = ethtool_op_get_ts_info,
1671 	.get_settings = virtnet_get_settings,
1672 	.set_settings = virtnet_set_settings,
1673 };
1674 
1675 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog)
1676 {
1677 	unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
1678 	struct virtnet_info *vi = netdev_priv(dev);
1679 	struct bpf_prog *old_prog;
1680 	u16 xdp_qp = 0, curr_qp;
1681 	int i, err;
1682 
1683 	if (prog && prog->xdp_adjust_head) {
1684 		netdev_warn(dev, "Does not support bpf_xdp_adjust_head()\n");
1685 		return -EOPNOTSUPP;
1686 	}
1687 
1688 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
1689 	    virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
1690 	    virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
1691 	    virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO)) {
1692 		netdev_warn(dev, "can't set XDP while host is implementing LRO, disable LRO first\n");
1693 		return -EOPNOTSUPP;
1694 	}
1695 
1696 	if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
1697 		netdev_warn(dev, "XDP expects header/data in single page, any_header_sg required\n");
1698 		return -EINVAL;
1699 	}
1700 
1701 	if (dev->mtu > max_sz) {
1702 		netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
1703 		return -EINVAL;
1704 	}
1705 
1706 	curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
1707 	if (prog)
1708 		xdp_qp = nr_cpu_ids;
1709 
1710 	/* XDP requires extra queues for XDP_TX */
1711 	if (curr_qp + xdp_qp > vi->max_queue_pairs) {
1712 		netdev_warn(dev, "request %i queues but max is %i\n",
1713 			    curr_qp + xdp_qp, vi->max_queue_pairs);
1714 		return -ENOMEM;
1715 	}
1716 
1717 	err = virtnet_set_queues(vi, curr_qp + xdp_qp);
1718 	if (err) {
1719 		dev_warn(&dev->dev, "XDP Device queue allocation failure.\n");
1720 		return err;
1721 	}
1722 
1723 	if (prog) {
1724 		prog = bpf_prog_add(prog, vi->max_queue_pairs - 1);
1725 		if (IS_ERR(prog)) {
1726 			virtnet_set_queues(vi, curr_qp);
1727 			return PTR_ERR(prog);
1728 		}
1729 	}
1730 
1731 	vi->xdp_queue_pairs = xdp_qp;
1732 	netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
1733 
1734 	for (i = 0; i < vi->max_queue_pairs; i++) {
1735 		old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
1736 		rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
1737 		if (old_prog)
1738 			bpf_prog_put(old_prog);
1739 	}
1740 
1741 	return 0;
1742 }
1743 
1744 static bool virtnet_xdp_query(struct net_device *dev)
1745 {
1746 	struct virtnet_info *vi = netdev_priv(dev);
1747 	int i;
1748 
1749 	for (i = 0; i < vi->max_queue_pairs; i++) {
1750 		if (vi->rq[i].xdp_prog)
1751 			return true;
1752 	}
1753 	return false;
1754 }
1755 
1756 static int virtnet_xdp(struct net_device *dev, struct netdev_xdp *xdp)
1757 {
1758 	switch (xdp->command) {
1759 	case XDP_SETUP_PROG:
1760 		return virtnet_xdp_set(dev, xdp->prog);
1761 	case XDP_QUERY_PROG:
1762 		xdp->prog_attached = virtnet_xdp_query(dev);
1763 		return 0;
1764 	default:
1765 		return -EINVAL;
1766 	}
1767 }
1768 
1769 static const struct net_device_ops virtnet_netdev = {
1770 	.ndo_open            = virtnet_open,
1771 	.ndo_stop   	     = virtnet_close,
1772 	.ndo_start_xmit      = start_xmit,
1773 	.ndo_validate_addr   = eth_validate_addr,
1774 	.ndo_set_mac_address = virtnet_set_mac_address,
1775 	.ndo_set_rx_mode     = virtnet_set_rx_mode,
1776 	.ndo_get_stats64     = virtnet_stats,
1777 	.ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
1778 	.ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
1779 #ifdef CONFIG_NET_POLL_CONTROLLER
1780 	.ndo_poll_controller = virtnet_netpoll,
1781 #endif
1782 	.ndo_xdp		= virtnet_xdp,
1783 };
1784 
1785 static void virtnet_config_changed_work(struct work_struct *work)
1786 {
1787 	struct virtnet_info *vi =
1788 		container_of(work, struct virtnet_info, config_work);
1789 	u16 v;
1790 
1791 	if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
1792 				 struct virtio_net_config, status, &v) < 0)
1793 		return;
1794 
1795 	if (v & VIRTIO_NET_S_ANNOUNCE) {
1796 		netdev_notify_peers(vi->dev);
1797 		virtnet_ack_link_announce(vi);
1798 	}
1799 
1800 	/* Ignore unknown (future) status bits */
1801 	v &= VIRTIO_NET_S_LINK_UP;
1802 
1803 	if (vi->status == v)
1804 		return;
1805 
1806 	vi->status = v;
1807 
1808 	if (vi->status & VIRTIO_NET_S_LINK_UP) {
1809 		netif_carrier_on(vi->dev);
1810 		netif_tx_wake_all_queues(vi->dev);
1811 	} else {
1812 		netif_carrier_off(vi->dev);
1813 		netif_tx_stop_all_queues(vi->dev);
1814 	}
1815 }
1816 
1817 static void virtnet_config_changed(struct virtio_device *vdev)
1818 {
1819 	struct virtnet_info *vi = vdev->priv;
1820 
1821 	schedule_work(&vi->config_work);
1822 }
1823 
1824 static void virtnet_free_queues(struct virtnet_info *vi)
1825 {
1826 	int i;
1827 
1828 	for (i = 0; i < vi->max_queue_pairs; i++) {
1829 		napi_hash_del(&vi->rq[i].napi);
1830 		netif_napi_del(&vi->rq[i].napi);
1831 	}
1832 
1833 	/* We called napi_hash_del() before netif_napi_del(),
1834 	 * we need to respect an RCU grace period before freeing vi->rq
1835 	 */
1836 	synchronize_net();
1837 
1838 	kfree(vi->rq);
1839 	kfree(vi->sq);
1840 }
1841 
1842 static void free_receive_bufs(struct virtnet_info *vi)
1843 {
1844 	struct bpf_prog *old_prog;
1845 	int i;
1846 
1847 	rtnl_lock();
1848 	for (i = 0; i < vi->max_queue_pairs; i++) {
1849 		while (vi->rq[i].pages)
1850 			__free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
1851 
1852 		old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
1853 		RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
1854 		if (old_prog)
1855 			bpf_prog_put(old_prog);
1856 	}
1857 	rtnl_unlock();
1858 }
1859 
1860 static void free_receive_page_frags(struct virtnet_info *vi)
1861 {
1862 	int i;
1863 	for (i = 0; i < vi->max_queue_pairs; i++)
1864 		if (vi->rq[i].alloc_frag.page)
1865 			put_page(vi->rq[i].alloc_frag.page);
1866 }
1867 
1868 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
1869 {
1870 	/* For small receive mode always use kfree_skb variants */
1871 	if (!vi->mergeable_rx_bufs)
1872 		return false;
1873 
1874 	if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
1875 		return false;
1876 	else if (q < vi->curr_queue_pairs)
1877 		return true;
1878 	else
1879 		return false;
1880 }
1881 
1882 static void free_unused_bufs(struct virtnet_info *vi)
1883 {
1884 	void *buf;
1885 	int i;
1886 
1887 	for (i = 0; i < vi->max_queue_pairs; i++) {
1888 		struct virtqueue *vq = vi->sq[i].vq;
1889 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
1890 			if (!is_xdp_raw_buffer_queue(vi, i))
1891 				dev_kfree_skb(buf);
1892 			else
1893 				put_page(virt_to_head_page(buf));
1894 		}
1895 	}
1896 
1897 	for (i = 0; i < vi->max_queue_pairs; i++) {
1898 		struct virtqueue *vq = vi->rq[i].vq;
1899 
1900 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
1901 			if (vi->mergeable_rx_bufs) {
1902 				unsigned long ctx = (unsigned long)buf;
1903 				void *base = mergeable_ctx_to_buf_address(ctx);
1904 				put_page(virt_to_head_page(base));
1905 			} else if (vi->big_packets) {
1906 				give_pages(&vi->rq[i], buf);
1907 			} else {
1908 				dev_kfree_skb(buf);
1909 			}
1910 		}
1911 	}
1912 }
1913 
1914 static void virtnet_del_vqs(struct virtnet_info *vi)
1915 {
1916 	struct virtio_device *vdev = vi->vdev;
1917 
1918 	virtnet_clean_affinity(vi, -1);
1919 
1920 	vdev->config->del_vqs(vdev);
1921 
1922 	virtnet_free_queues(vi);
1923 }
1924 
1925 static int virtnet_find_vqs(struct virtnet_info *vi)
1926 {
1927 	vq_callback_t **callbacks;
1928 	struct virtqueue **vqs;
1929 	int ret = -ENOMEM;
1930 	int i, total_vqs;
1931 	const char **names;
1932 
1933 	/* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
1934 	 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
1935 	 * possible control vq.
1936 	 */
1937 	total_vqs = vi->max_queue_pairs * 2 +
1938 		    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
1939 
1940 	/* Allocate space for find_vqs parameters */
1941 	vqs = kzalloc(total_vqs * sizeof(*vqs), GFP_KERNEL);
1942 	if (!vqs)
1943 		goto err_vq;
1944 	callbacks = kmalloc(total_vqs * sizeof(*callbacks), GFP_KERNEL);
1945 	if (!callbacks)
1946 		goto err_callback;
1947 	names = kmalloc(total_vqs * sizeof(*names), GFP_KERNEL);
1948 	if (!names)
1949 		goto err_names;
1950 
1951 	/* Parameters for control virtqueue, if any */
1952 	if (vi->has_cvq) {
1953 		callbacks[total_vqs - 1] = NULL;
1954 		names[total_vqs - 1] = "control";
1955 	}
1956 
1957 	/* Allocate/initialize parameters for send/receive virtqueues */
1958 	for (i = 0; i < vi->max_queue_pairs; i++) {
1959 		callbacks[rxq2vq(i)] = skb_recv_done;
1960 		callbacks[txq2vq(i)] = skb_xmit_done;
1961 		sprintf(vi->rq[i].name, "input.%d", i);
1962 		sprintf(vi->sq[i].name, "output.%d", i);
1963 		names[rxq2vq(i)] = vi->rq[i].name;
1964 		names[txq2vq(i)] = vi->sq[i].name;
1965 	}
1966 
1967 	ret = vi->vdev->config->find_vqs(vi->vdev, total_vqs, vqs, callbacks,
1968 					 names);
1969 	if (ret)
1970 		goto err_find;
1971 
1972 	if (vi->has_cvq) {
1973 		vi->cvq = vqs[total_vqs - 1];
1974 		if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
1975 			vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
1976 	}
1977 
1978 	for (i = 0; i < vi->max_queue_pairs; i++) {
1979 		vi->rq[i].vq = vqs[rxq2vq(i)];
1980 		vi->sq[i].vq = vqs[txq2vq(i)];
1981 	}
1982 
1983 	kfree(names);
1984 	kfree(callbacks);
1985 	kfree(vqs);
1986 
1987 	return 0;
1988 
1989 err_find:
1990 	kfree(names);
1991 err_names:
1992 	kfree(callbacks);
1993 err_callback:
1994 	kfree(vqs);
1995 err_vq:
1996 	return ret;
1997 }
1998 
1999 static int virtnet_alloc_queues(struct virtnet_info *vi)
2000 {
2001 	int i;
2002 
2003 	vi->sq = kzalloc(sizeof(*vi->sq) * vi->max_queue_pairs, GFP_KERNEL);
2004 	if (!vi->sq)
2005 		goto err_sq;
2006 	vi->rq = kzalloc(sizeof(*vi->rq) * vi->max_queue_pairs, GFP_KERNEL);
2007 	if (!vi->rq)
2008 		goto err_rq;
2009 
2010 	INIT_DELAYED_WORK(&vi->refill, refill_work);
2011 	for (i = 0; i < vi->max_queue_pairs; i++) {
2012 		vi->rq[i].pages = NULL;
2013 		netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
2014 			       napi_weight);
2015 
2016 		sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
2017 		ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
2018 		sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
2019 	}
2020 
2021 	return 0;
2022 
2023 err_rq:
2024 	kfree(vi->sq);
2025 err_sq:
2026 	return -ENOMEM;
2027 }
2028 
2029 static int init_vqs(struct virtnet_info *vi)
2030 {
2031 	int ret;
2032 
2033 	/* Allocate send & receive queues */
2034 	ret = virtnet_alloc_queues(vi);
2035 	if (ret)
2036 		goto err;
2037 
2038 	ret = virtnet_find_vqs(vi);
2039 	if (ret)
2040 		goto err_free;
2041 
2042 	get_online_cpus();
2043 	virtnet_set_affinity(vi);
2044 	put_online_cpus();
2045 
2046 	return 0;
2047 
2048 err_free:
2049 	virtnet_free_queues(vi);
2050 err:
2051 	return ret;
2052 }
2053 
2054 #ifdef CONFIG_SYSFS
2055 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
2056 		struct rx_queue_attribute *attribute, char *buf)
2057 {
2058 	struct virtnet_info *vi = netdev_priv(queue->dev);
2059 	unsigned int queue_index = get_netdev_rx_queue_index(queue);
2060 	struct ewma_pkt_len *avg;
2061 
2062 	BUG_ON(queue_index >= vi->max_queue_pairs);
2063 	avg = &vi->rq[queue_index].mrg_avg_pkt_len;
2064 	return sprintf(buf, "%u\n", get_mergeable_buf_len(avg));
2065 }
2066 
2067 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
2068 	__ATTR_RO(mergeable_rx_buffer_size);
2069 
2070 static struct attribute *virtio_net_mrg_rx_attrs[] = {
2071 	&mergeable_rx_buffer_size_attribute.attr,
2072 	NULL
2073 };
2074 
2075 static const struct attribute_group virtio_net_mrg_rx_group = {
2076 	.name = "virtio_net",
2077 	.attrs = virtio_net_mrg_rx_attrs
2078 };
2079 #endif
2080 
2081 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
2082 				    unsigned int fbit,
2083 				    const char *fname, const char *dname)
2084 {
2085 	if (!virtio_has_feature(vdev, fbit))
2086 		return false;
2087 
2088 	dev_err(&vdev->dev, "device advertises feature %s but not %s",
2089 		fname, dname);
2090 
2091 	return true;
2092 }
2093 
2094 #define VIRTNET_FAIL_ON(vdev, fbit, dbit)			\
2095 	virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
2096 
2097 static bool virtnet_validate_features(struct virtio_device *vdev)
2098 {
2099 	if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
2100 	    (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
2101 			     "VIRTIO_NET_F_CTRL_VQ") ||
2102 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
2103 			     "VIRTIO_NET_F_CTRL_VQ") ||
2104 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
2105 			     "VIRTIO_NET_F_CTRL_VQ") ||
2106 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
2107 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
2108 			     "VIRTIO_NET_F_CTRL_VQ"))) {
2109 		return false;
2110 	}
2111 
2112 	return true;
2113 }
2114 
2115 #define MIN_MTU ETH_MIN_MTU
2116 #define MAX_MTU ETH_MAX_MTU
2117 
2118 static int virtnet_probe(struct virtio_device *vdev)
2119 {
2120 	int i, err;
2121 	struct net_device *dev;
2122 	struct virtnet_info *vi;
2123 	u16 max_queue_pairs;
2124 	int mtu;
2125 
2126 	if (!vdev->config->get) {
2127 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
2128 			__func__);
2129 		return -EINVAL;
2130 	}
2131 
2132 	if (!virtnet_validate_features(vdev))
2133 		return -EINVAL;
2134 
2135 	/* Find if host supports multiqueue virtio_net device */
2136 	err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
2137 				   struct virtio_net_config,
2138 				   max_virtqueue_pairs, &max_queue_pairs);
2139 
2140 	/* We need at least 2 queue's */
2141 	if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
2142 	    max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
2143 	    !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
2144 		max_queue_pairs = 1;
2145 
2146 	/* Allocate ourselves a network device with room for our info */
2147 	dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
2148 	if (!dev)
2149 		return -ENOMEM;
2150 
2151 	/* Set up network device as normal. */
2152 	dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
2153 	dev->netdev_ops = &virtnet_netdev;
2154 	dev->features = NETIF_F_HIGHDMA;
2155 
2156 	dev->ethtool_ops = &virtnet_ethtool_ops;
2157 	SET_NETDEV_DEV(dev, &vdev->dev);
2158 
2159 	/* Do we support "hardware" checksums? */
2160 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
2161 		/* This opens up the world of extra features. */
2162 		dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
2163 		if (csum)
2164 			dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
2165 
2166 		if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
2167 			dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
2168 				| NETIF_F_TSO_ECN | NETIF_F_TSO6;
2169 		}
2170 		/* Individual feature bits: what can host handle? */
2171 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
2172 			dev->hw_features |= NETIF_F_TSO;
2173 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
2174 			dev->hw_features |= NETIF_F_TSO6;
2175 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
2176 			dev->hw_features |= NETIF_F_TSO_ECN;
2177 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
2178 			dev->hw_features |= NETIF_F_UFO;
2179 
2180 		dev->features |= NETIF_F_GSO_ROBUST;
2181 
2182 		if (gso)
2183 			dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
2184 		/* (!csum && gso) case will be fixed by register_netdev() */
2185 	}
2186 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
2187 		dev->features |= NETIF_F_RXCSUM;
2188 
2189 	dev->vlan_features = dev->features;
2190 
2191 	/* MTU range: 68 - 65535 */
2192 	dev->min_mtu = MIN_MTU;
2193 	dev->max_mtu = MAX_MTU;
2194 
2195 	/* Configuration may specify what MAC to use.  Otherwise random. */
2196 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
2197 		virtio_cread_bytes(vdev,
2198 				   offsetof(struct virtio_net_config, mac),
2199 				   dev->dev_addr, dev->addr_len);
2200 	else
2201 		eth_hw_addr_random(dev);
2202 
2203 	/* Set up our device-specific information */
2204 	vi = netdev_priv(dev);
2205 	vi->dev = dev;
2206 	vi->vdev = vdev;
2207 	vdev->priv = vi;
2208 	vi->stats = alloc_percpu(struct virtnet_stats);
2209 	err = -ENOMEM;
2210 	if (vi->stats == NULL)
2211 		goto free;
2212 
2213 	for_each_possible_cpu(i) {
2214 		struct virtnet_stats *virtnet_stats;
2215 		virtnet_stats = per_cpu_ptr(vi->stats, i);
2216 		u64_stats_init(&virtnet_stats->tx_syncp);
2217 		u64_stats_init(&virtnet_stats->rx_syncp);
2218 	}
2219 
2220 	INIT_WORK(&vi->config_work, virtnet_config_changed_work);
2221 
2222 	/* If we can receive ANY GSO packets, we must allocate large ones. */
2223 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
2224 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
2225 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
2226 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
2227 		vi->big_packets = true;
2228 
2229 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
2230 		vi->mergeable_rx_bufs = true;
2231 
2232 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
2233 	    virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
2234 		vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2235 	else
2236 		vi->hdr_len = sizeof(struct virtio_net_hdr);
2237 
2238 	if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
2239 	    virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
2240 		vi->any_header_sg = true;
2241 
2242 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
2243 		vi->has_cvq = true;
2244 
2245 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
2246 		mtu = virtio_cread16(vdev,
2247 				     offsetof(struct virtio_net_config,
2248 					      mtu));
2249 		if (mtu < dev->min_mtu) {
2250 			__virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
2251 		} else {
2252 			dev->mtu = mtu;
2253 			dev->max_mtu = mtu;
2254 		}
2255 	}
2256 
2257 	if (vi->any_header_sg)
2258 		dev->needed_headroom = vi->hdr_len;
2259 
2260 	/* Enable multiqueue by default */
2261 	if (num_online_cpus() >= max_queue_pairs)
2262 		vi->curr_queue_pairs = max_queue_pairs;
2263 	else
2264 		vi->curr_queue_pairs = num_online_cpus();
2265 	vi->max_queue_pairs = max_queue_pairs;
2266 
2267 	/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
2268 	err = init_vqs(vi);
2269 	if (err)
2270 		goto free_stats;
2271 
2272 #ifdef CONFIG_SYSFS
2273 	if (vi->mergeable_rx_bufs)
2274 		dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
2275 #endif
2276 	netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
2277 	netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
2278 
2279 	virtnet_init_settings(dev);
2280 
2281 	err = register_netdev(dev);
2282 	if (err) {
2283 		pr_debug("virtio_net: registering device failed\n");
2284 		goto free_vqs;
2285 	}
2286 
2287 	virtio_device_ready(vdev);
2288 
2289 	err = virtnet_cpu_notif_add(vi);
2290 	if (err) {
2291 		pr_debug("virtio_net: registering cpu notifier failed\n");
2292 		goto free_unregister_netdev;
2293 	}
2294 
2295 	rtnl_lock();
2296 	virtnet_set_queues(vi, vi->curr_queue_pairs);
2297 	rtnl_unlock();
2298 
2299 	/* Assume link up if device can't report link status,
2300 	   otherwise get link status from config. */
2301 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
2302 		netif_carrier_off(dev);
2303 		schedule_work(&vi->config_work);
2304 	} else {
2305 		vi->status = VIRTIO_NET_S_LINK_UP;
2306 		netif_carrier_on(dev);
2307 	}
2308 
2309 	pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
2310 		 dev->name, max_queue_pairs);
2311 
2312 	return 0;
2313 
2314 free_unregister_netdev:
2315 	vi->vdev->config->reset(vdev);
2316 
2317 	unregister_netdev(dev);
2318 free_vqs:
2319 	cancel_delayed_work_sync(&vi->refill);
2320 	free_receive_page_frags(vi);
2321 	virtnet_del_vqs(vi);
2322 free_stats:
2323 	free_percpu(vi->stats);
2324 free:
2325 	free_netdev(dev);
2326 	return err;
2327 }
2328 
2329 static void remove_vq_common(struct virtnet_info *vi)
2330 {
2331 	vi->vdev->config->reset(vi->vdev);
2332 
2333 	/* Free unused buffers in both send and recv, if any. */
2334 	free_unused_bufs(vi);
2335 
2336 	free_receive_bufs(vi);
2337 
2338 	free_receive_page_frags(vi);
2339 
2340 	virtnet_del_vqs(vi);
2341 }
2342 
2343 static void virtnet_remove(struct virtio_device *vdev)
2344 {
2345 	struct virtnet_info *vi = vdev->priv;
2346 
2347 	virtnet_cpu_notif_remove(vi);
2348 
2349 	/* Make sure no work handler is accessing the device. */
2350 	flush_work(&vi->config_work);
2351 
2352 	unregister_netdev(vi->dev);
2353 
2354 	remove_vq_common(vi);
2355 
2356 	free_percpu(vi->stats);
2357 	free_netdev(vi->dev);
2358 }
2359 
2360 #ifdef CONFIG_PM_SLEEP
2361 static int virtnet_freeze(struct virtio_device *vdev)
2362 {
2363 	struct virtnet_info *vi = vdev->priv;
2364 	int i;
2365 
2366 	virtnet_cpu_notif_remove(vi);
2367 
2368 	/* Make sure no work handler is accessing the device */
2369 	flush_work(&vi->config_work);
2370 
2371 	netif_device_detach(vi->dev);
2372 	cancel_delayed_work_sync(&vi->refill);
2373 
2374 	if (netif_running(vi->dev)) {
2375 		for (i = 0; i < vi->max_queue_pairs; i++)
2376 			napi_disable(&vi->rq[i].napi);
2377 	}
2378 
2379 	remove_vq_common(vi);
2380 
2381 	return 0;
2382 }
2383 
2384 static int virtnet_restore(struct virtio_device *vdev)
2385 {
2386 	struct virtnet_info *vi = vdev->priv;
2387 	int err, i;
2388 
2389 	err = init_vqs(vi);
2390 	if (err)
2391 		return err;
2392 
2393 	virtio_device_ready(vdev);
2394 
2395 	if (netif_running(vi->dev)) {
2396 		for (i = 0; i < vi->curr_queue_pairs; i++)
2397 			if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
2398 				schedule_delayed_work(&vi->refill, 0);
2399 
2400 		for (i = 0; i < vi->max_queue_pairs; i++)
2401 			virtnet_napi_enable(&vi->rq[i]);
2402 	}
2403 
2404 	netif_device_attach(vi->dev);
2405 
2406 	rtnl_lock();
2407 	virtnet_set_queues(vi, vi->curr_queue_pairs);
2408 	rtnl_unlock();
2409 
2410 	err = virtnet_cpu_notif_add(vi);
2411 	if (err)
2412 		return err;
2413 
2414 	return 0;
2415 }
2416 #endif
2417 
2418 static struct virtio_device_id id_table[] = {
2419 	{ VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
2420 	{ 0 },
2421 };
2422 
2423 #define VIRTNET_FEATURES \
2424 	VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
2425 	VIRTIO_NET_F_MAC, \
2426 	VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
2427 	VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
2428 	VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
2429 	VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
2430 	VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
2431 	VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
2432 	VIRTIO_NET_F_CTRL_MAC_ADDR, \
2433 	VIRTIO_NET_F_MTU
2434 
2435 static unsigned int features[] = {
2436 	VIRTNET_FEATURES,
2437 };
2438 
2439 static unsigned int features_legacy[] = {
2440 	VIRTNET_FEATURES,
2441 	VIRTIO_NET_F_GSO,
2442 	VIRTIO_F_ANY_LAYOUT,
2443 };
2444 
2445 static struct virtio_driver virtio_net_driver = {
2446 	.feature_table = features,
2447 	.feature_table_size = ARRAY_SIZE(features),
2448 	.feature_table_legacy = features_legacy,
2449 	.feature_table_size_legacy = ARRAY_SIZE(features_legacy),
2450 	.driver.name =	KBUILD_MODNAME,
2451 	.driver.owner =	THIS_MODULE,
2452 	.id_table =	id_table,
2453 	.probe =	virtnet_probe,
2454 	.remove =	virtnet_remove,
2455 	.config_changed = virtnet_config_changed,
2456 #ifdef CONFIG_PM_SLEEP
2457 	.freeze =	virtnet_freeze,
2458 	.restore =	virtnet_restore,
2459 #endif
2460 };
2461 
2462 static __init int virtio_net_driver_init(void)
2463 {
2464 	int ret;
2465 
2466 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
2467 				      virtnet_cpu_online,
2468 				      virtnet_cpu_down_prep);
2469 	if (ret < 0)
2470 		goto out;
2471 	virtionet_online = ret;
2472 	ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
2473 				      NULL, virtnet_cpu_dead);
2474 	if (ret)
2475 		goto err_dead;
2476 
2477         ret = register_virtio_driver(&virtio_net_driver);
2478 	if (ret)
2479 		goto err_virtio;
2480 	return 0;
2481 err_virtio:
2482 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
2483 err_dead:
2484 	cpuhp_remove_multi_state(virtionet_online);
2485 out:
2486 	return ret;
2487 }
2488 module_init(virtio_net_driver_init);
2489 
2490 static __exit void virtio_net_driver_exit(void)
2491 {
2492 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
2493 	cpuhp_remove_multi_state(virtionet_online);
2494 	unregister_virtio_driver(&virtio_net_driver);
2495 }
2496 module_exit(virtio_net_driver_exit);
2497 
2498 MODULE_DEVICE_TABLE(virtio, id_table);
2499 MODULE_DESCRIPTION("Virtio network driver");
2500 MODULE_LICENSE("GPL");
2501