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