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