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