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