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