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