xref: /linux/drivers/net/virtio_net.c (revision 906fd46a65383cd639e5eec72a047efc33045d86)
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 <linux/dim.h>
23 #include <net/route.h>
24 #include <net/xdp.h>
25 #include <net/net_failover.h>
26 #include <net/netdev_rx_queue.h>
27 #include <net/netdev_queues.h>
28 
29 static int napi_weight = NAPI_POLL_WEIGHT;
30 module_param(napi_weight, int, 0444);
31 
32 static bool csum = true, gso = true, napi_tx = true;
33 module_param(csum, bool, 0444);
34 module_param(gso, bool, 0444);
35 module_param(napi_tx, bool, 0644);
36 
37 /* FIXME: MTU in config. */
38 #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
39 #define GOOD_COPY_LEN	128
40 
41 #define VIRTNET_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
42 
43 /* Amount of XDP headroom to prepend to packets for use by xdp_adjust_head */
44 #define VIRTIO_XDP_HEADROOM 256
45 
46 /* Separating two types of XDP xmit */
47 #define VIRTIO_XDP_TX		BIT(0)
48 #define VIRTIO_XDP_REDIR	BIT(1)
49 
50 #define VIRTIO_XDP_FLAG	BIT(0)
51 
52 /* RX packet size EWMA. The average packet size is used to determine the packet
53  * buffer size when refilling RX rings. As the entire RX ring may be refilled
54  * at once, the weight is chosen so that the EWMA will be insensitive to short-
55  * term, transient changes in packet size.
56  */
57 DECLARE_EWMA(pkt_len, 0, 64)
58 
59 #define VIRTNET_DRIVER_VERSION "1.0.0"
60 
61 static const unsigned long guest_offloads[] = {
62 	VIRTIO_NET_F_GUEST_TSO4,
63 	VIRTIO_NET_F_GUEST_TSO6,
64 	VIRTIO_NET_F_GUEST_ECN,
65 	VIRTIO_NET_F_GUEST_UFO,
66 	VIRTIO_NET_F_GUEST_CSUM,
67 	VIRTIO_NET_F_GUEST_USO4,
68 	VIRTIO_NET_F_GUEST_USO6,
69 	VIRTIO_NET_F_GUEST_HDRLEN
70 };
71 
72 #define GUEST_OFFLOAD_GRO_HW_MASK ((1ULL << VIRTIO_NET_F_GUEST_TSO4) | \
73 				(1ULL << VIRTIO_NET_F_GUEST_TSO6) | \
74 				(1ULL << VIRTIO_NET_F_GUEST_ECN)  | \
75 				(1ULL << VIRTIO_NET_F_GUEST_UFO)  | \
76 				(1ULL << VIRTIO_NET_F_GUEST_USO4) | \
77 				(1ULL << VIRTIO_NET_F_GUEST_USO6))
78 
79 struct virtnet_stat_desc {
80 	char desc[ETH_GSTRING_LEN];
81 	size_t offset;
82 	size_t qstat_offset;
83 };
84 
85 struct virtnet_sq_free_stats {
86 	u64 packets;
87 	u64 bytes;
88 };
89 
90 struct virtnet_sq_stats {
91 	struct u64_stats_sync syncp;
92 	u64_stats_t packets;
93 	u64_stats_t bytes;
94 	u64_stats_t xdp_tx;
95 	u64_stats_t xdp_tx_drops;
96 	u64_stats_t kicks;
97 	u64_stats_t tx_timeouts;
98 	u64_stats_t stop;
99 	u64_stats_t wake;
100 };
101 
102 struct virtnet_rq_stats {
103 	struct u64_stats_sync syncp;
104 	u64_stats_t packets;
105 	u64_stats_t bytes;
106 	u64_stats_t drops;
107 	u64_stats_t xdp_packets;
108 	u64_stats_t xdp_tx;
109 	u64_stats_t xdp_redirects;
110 	u64_stats_t xdp_drops;
111 	u64_stats_t kicks;
112 };
113 
114 #define VIRTNET_SQ_STAT(name, m) {name, offsetof(struct virtnet_sq_stats, m), -1}
115 #define VIRTNET_RQ_STAT(name, m) {name, offsetof(struct virtnet_rq_stats, m), -1}
116 
117 #define VIRTNET_SQ_STAT_QSTAT(name, m)				\
118 	{							\
119 		name,						\
120 		offsetof(struct virtnet_sq_stats, m),		\
121 		offsetof(struct netdev_queue_stats_tx, m),	\
122 	}
123 
124 #define VIRTNET_RQ_STAT_QSTAT(name, m)				\
125 	{							\
126 		name,						\
127 		offsetof(struct virtnet_rq_stats, m),		\
128 		offsetof(struct netdev_queue_stats_rx, m),	\
129 	}
130 
131 static const struct virtnet_stat_desc virtnet_sq_stats_desc[] = {
132 	VIRTNET_SQ_STAT("xdp_tx",       xdp_tx),
133 	VIRTNET_SQ_STAT("xdp_tx_drops", xdp_tx_drops),
134 	VIRTNET_SQ_STAT("kicks",        kicks),
135 	VIRTNET_SQ_STAT("tx_timeouts",  tx_timeouts),
136 };
137 
138 static const struct virtnet_stat_desc virtnet_rq_stats_desc[] = {
139 	VIRTNET_RQ_STAT("drops",         drops),
140 	VIRTNET_RQ_STAT("xdp_packets",   xdp_packets),
141 	VIRTNET_RQ_STAT("xdp_tx",        xdp_tx),
142 	VIRTNET_RQ_STAT("xdp_redirects", xdp_redirects),
143 	VIRTNET_RQ_STAT("xdp_drops",     xdp_drops),
144 	VIRTNET_RQ_STAT("kicks",         kicks),
145 };
146 
147 static const struct virtnet_stat_desc virtnet_sq_stats_desc_qstat[] = {
148 	VIRTNET_SQ_STAT_QSTAT("packets", packets),
149 	VIRTNET_SQ_STAT_QSTAT("bytes",   bytes),
150 	VIRTNET_SQ_STAT_QSTAT("stop",	 stop),
151 	VIRTNET_SQ_STAT_QSTAT("wake",	 wake),
152 };
153 
154 static const struct virtnet_stat_desc virtnet_rq_stats_desc_qstat[] = {
155 	VIRTNET_RQ_STAT_QSTAT("packets", packets),
156 	VIRTNET_RQ_STAT_QSTAT("bytes",   bytes),
157 };
158 
159 #define VIRTNET_STATS_DESC_CQ(name) \
160 	{#name, offsetof(struct virtio_net_stats_cvq, name), -1}
161 
162 #define VIRTNET_STATS_DESC_RX(class, name) \
163 	{#name, offsetof(struct virtio_net_stats_rx_ ## class, rx_ ## name), -1}
164 
165 #define VIRTNET_STATS_DESC_TX(class, name) \
166 	{#name, offsetof(struct virtio_net_stats_tx_ ## class, tx_ ## name), -1}
167 
168 
169 static const struct virtnet_stat_desc virtnet_stats_cvq_desc[] = {
170 	VIRTNET_STATS_DESC_CQ(command_num),
171 	VIRTNET_STATS_DESC_CQ(ok_num),
172 };
173 
174 static const struct virtnet_stat_desc virtnet_stats_rx_basic_desc[] = {
175 	VIRTNET_STATS_DESC_RX(basic, packets),
176 	VIRTNET_STATS_DESC_RX(basic, bytes),
177 
178 	VIRTNET_STATS_DESC_RX(basic, notifications),
179 	VIRTNET_STATS_DESC_RX(basic, interrupts),
180 };
181 
182 static const struct virtnet_stat_desc virtnet_stats_tx_basic_desc[] = {
183 	VIRTNET_STATS_DESC_TX(basic, packets),
184 	VIRTNET_STATS_DESC_TX(basic, bytes),
185 
186 	VIRTNET_STATS_DESC_TX(basic, notifications),
187 	VIRTNET_STATS_DESC_TX(basic, interrupts),
188 };
189 
190 static const struct virtnet_stat_desc virtnet_stats_rx_csum_desc[] = {
191 	VIRTNET_STATS_DESC_RX(csum, needs_csum),
192 };
193 
194 static const struct virtnet_stat_desc virtnet_stats_tx_gso_desc[] = {
195 	VIRTNET_STATS_DESC_TX(gso, gso_packets_noseg),
196 	VIRTNET_STATS_DESC_TX(gso, gso_bytes_noseg),
197 };
198 
199 static const struct virtnet_stat_desc virtnet_stats_rx_speed_desc[] = {
200 	VIRTNET_STATS_DESC_RX(speed, ratelimit_bytes),
201 };
202 
203 static const struct virtnet_stat_desc virtnet_stats_tx_speed_desc[] = {
204 	VIRTNET_STATS_DESC_TX(speed, ratelimit_bytes),
205 };
206 
207 #define VIRTNET_STATS_DESC_RX_QSTAT(class, name, qstat_field)			\
208 	{									\
209 		#name,								\
210 		offsetof(struct virtio_net_stats_rx_ ## class, rx_ ## name),	\
211 		offsetof(struct netdev_queue_stats_rx, qstat_field),		\
212 	}
213 
214 #define VIRTNET_STATS_DESC_TX_QSTAT(class, name, qstat_field)			\
215 	{									\
216 		#name,								\
217 		offsetof(struct virtio_net_stats_tx_ ## class, tx_ ## name),	\
218 		offsetof(struct netdev_queue_stats_tx, qstat_field),		\
219 	}
220 
221 static const struct virtnet_stat_desc virtnet_stats_rx_basic_desc_qstat[] = {
222 	VIRTNET_STATS_DESC_RX_QSTAT(basic, drops,         hw_drops),
223 	VIRTNET_STATS_DESC_RX_QSTAT(basic, drop_overruns, hw_drop_overruns),
224 };
225 
226 static const struct virtnet_stat_desc virtnet_stats_tx_basic_desc_qstat[] = {
227 	VIRTNET_STATS_DESC_TX_QSTAT(basic, drops,          hw_drops),
228 	VIRTNET_STATS_DESC_TX_QSTAT(basic, drop_malformed, hw_drop_errors),
229 };
230 
231 static const struct virtnet_stat_desc virtnet_stats_rx_csum_desc_qstat[] = {
232 	VIRTNET_STATS_DESC_RX_QSTAT(csum, csum_valid, csum_unnecessary),
233 	VIRTNET_STATS_DESC_RX_QSTAT(csum, csum_none,  csum_none),
234 	VIRTNET_STATS_DESC_RX_QSTAT(csum, csum_bad,   csum_bad),
235 };
236 
237 static const struct virtnet_stat_desc virtnet_stats_tx_csum_desc_qstat[] = {
238 	VIRTNET_STATS_DESC_TX_QSTAT(csum, csum_none,  csum_none),
239 	VIRTNET_STATS_DESC_TX_QSTAT(csum, needs_csum, needs_csum),
240 };
241 
242 static const struct virtnet_stat_desc virtnet_stats_rx_gso_desc_qstat[] = {
243 	VIRTNET_STATS_DESC_RX_QSTAT(gso, gso_packets,           hw_gro_packets),
244 	VIRTNET_STATS_DESC_RX_QSTAT(gso, gso_bytes,             hw_gro_bytes),
245 	VIRTNET_STATS_DESC_RX_QSTAT(gso, gso_packets_coalesced, hw_gro_wire_packets),
246 	VIRTNET_STATS_DESC_RX_QSTAT(gso, gso_bytes_coalesced,   hw_gro_wire_bytes),
247 };
248 
249 static const struct virtnet_stat_desc virtnet_stats_tx_gso_desc_qstat[] = {
250 	VIRTNET_STATS_DESC_TX_QSTAT(gso, gso_packets,        hw_gso_packets),
251 	VIRTNET_STATS_DESC_TX_QSTAT(gso, gso_bytes,          hw_gso_bytes),
252 	VIRTNET_STATS_DESC_TX_QSTAT(gso, gso_segments,       hw_gso_wire_packets),
253 	VIRTNET_STATS_DESC_TX_QSTAT(gso, gso_segments_bytes, hw_gso_wire_bytes),
254 };
255 
256 static const struct virtnet_stat_desc virtnet_stats_rx_speed_desc_qstat[] = {
257 	VIRTNET_STATS_DESC_RX_QSTAT(speed, ratelimit_packets, hw_drop_ratelimits),
258 };
259 
260 static const struct virtnet_stat_desc virtnet_stats_tx_speed_desc_qstat[] = {
261 	VIRTNET_STATS_DESC_TX_QSTAT(speed, ratelimit_packets, hw_drop_ratelimits),
262 };
263 
264 #define VIRTNET_Q_TYPE_RX 0
265 #define VIRTNET_Q_TYPE_TX 1
266 #define VIRTNET_Q_TYPE_CQ 2
267 
268 struct virtnet_interrupt_coalesce {
269 	u32 max_packets;
270 	u32 max_usecs;
271 };
272 
273 /* The dma information of pages allocated at a time. */
274 struct virtnet_rq_dma {
275 	dma_addr_t addr;
276 	u32 ref;
277 	u16 len;
278 	u16 need_sync;
279 };
280 
281 /* Internal representation of a send virtqueue */
282 struct send_queue {
283 	/* Virtqueue associated with this send _queue */
284 	struct virtqueue *vq;
285 
286 	/* TX: fragments + linear part + virtio header */
287 	struct scatterlist sg[MAX_SKB_FRAGS + 2];
288 
289 	/* Name of the send queue: output.$index */
290 	char name[16];
291 
292 	struct virtnet_sq_stats stats;
293 
294 	struct virtnet_interrupt_coalesce intr_coal;
295 
296 	struct napi_struct napi;
297 
298 	/* Record whether sq is in reset state. */
299 	bool reset;
300 };
301 
302 /* Internal representation of a receive virtqueue */
303 struct receive_queue {
304 	/* Virtqueue associated with this receive_queue */
305 	struct virtqueue *vq;
306 
307 	struct napi_struct napi;
308 
309 	struct bpf_prog __rcu *xdp_prog;
310 
311 	struct virtnet_rq_stats stats;
312 
313 	/* The number of rx notifications */
314 	u16 calls;
315 
316 	/* Is dynamic interrupt moderation enabled? */
317 	bool dim_enabled;
318 
319 	/* Used to protect dim_enabled and inter_coal */
320 	struct mutex dim_lock;
321 
322 	/* Dynamic Interrupt Moderation */
323 	struct dim dim;
324 
325 	u32 packets_in_napi;
326 
327 	struct virtnet_interrupt_coalesce intr_coal;
328 
329 	/* Chain pages by the private ptr. */
330 	struct page *pages;
331 
332 	/* Average packet length for mergeable receive buffers. */
333 	struct ewma_pkt_len mrg_avg_pkt_len;
334 
335 	/* Page frag for packet buffer allocation. */
336 	struct page_frag alloc_frag;
337 
338 	/* RX: fragments + linear part + virtio header */
339 	struct scatterlist sg[MAX_SKB_FRAGS + 2];
340 
341 	/* Min single buffer size for mergeable buffers case. */
342 	unsigned int min_buf_len;
343 
344 	/* Name of this receive queue: input.$index */
345 	char name[16];
346 
347 	struct xdp_rxq_info xdp_rxq;
348 
349 	/* Record the last dma info to free after new pages is allocated. */
350 	struct virtnet_rq_dma *last_dma;
351 };
352 
353 /* This structure can contain rss message with maximum settings for indirection table and keysize
354  * Note, that default structure that describes RSS configuration virtio_net_rss_config
355  * contains same info but can't handle table values.
356  * In any case, structure would be passed to virtio hw through sg_buf split by parts
357  * because table sizes may be differ according to the device configuration.
358  */
359 #define VIRTIO_NET_RSS_MAX_KEY_SIZE     40
360 #define VIRTIO_NET_RSS_MAX_TABLE_LEN    128
361 struct virtio_net_ctrl_rss {
362 	u32 hash_types;
363 	u16 indirection_table_mask;
364 	u16 unclassified_queue;
365 	u16 indirection_table[VIRTIO_NET_RSS_MAX_TABLE_LEN];
366 	u16 max_tx_vq;
367 	u8 hash_key_length;
368 	u8 key[VIRTIO_NET_RSS_MAX_KEY_SIZE];
369 };
370 
371 /* Control VQ buffers: protected by the rtnl lock */
372 struct control_buf {
373 	struct virtio_net_ctrl_hdr hdr;
374 	virtio_net_ctrl_ack status;
375 };
376 
377 struct virtnet_info {
378 	struct virtio_device *vdev;
379 	struct virtqueue *cvq;
380 	struct net_device *dev;
381 	struct send_queue *sq;
382 	struct receive_queue *rq;
383 	unsigned int status;
384 
385 	/* Max # of queue pairs supported by the device */
386 	u16 max_queue_pairs;
387 
388 	/* # of queue pairs currently used by the driver */
389 	u16 curr_queue_pairs;
390 
391 	/* # of XDP queue pairs currently used by the driver */
392 	u16 xdp_queue_pairs;
393 
394 	/* xdp_queue_pairs may be 0, when xdp is already loaded. So add this. */
395 	bool xdp_enabled;
396 
397 	/* I like... big packets and I cannot lie! */
398 	bool big_packets;
399 
400 	/* number of sg entries allocated for big packets */
401 	unsigned int big_packets_num_skbfrags;
402 
403 	/* Host will merge rx buffers for big packets (shake it! shake it!) */
404 	bool mergeable_rx_bufs;
405 
406 	/* Host supports rss and/or hash report */
407 	bool has_rss;
408 	bool has_rss_hash_report;
409 	u8 rss_key_size;
410 	u16 rss_indir_table_size;
411 	u32 rss_hash_types_supported;
412 	u32 rss_hash_types_saved;
413 	struct virtio_net_ctrl_rss rss;
414 
415 	/* Has control virtqueue */
416 	bool has_cvq;
417 
418 	/* Lock to protect the control VQ */
419 	struct mutex cvq_lock;
420 
421 	/* Host can handle any s/g split between our header and packet data */
422 	bool any_header_sg;
423 
424 	/* Packet virtio header size */
425 	u8 hdr_len;
426 
427 	/* Work struct for delayed refilling if we run low on memory. */
428 	struct delayed_work refill;
429 
430 	/* Is delayed refill enabled? */
431 	bool refill_enabled;
432 
433 	/* The lock to synchronize the access to refill_enabled */
434 	spinlock_t refill_lock;
435 
436 	/* Work struct for config space updates */
437 	struct work_struct config_work;
438 
439 	/* Work struct for setting rx mode */
440 	struct work_struct rx_mode_work;
441 
442 	/* OK to queue work setting RX mode? */
443 	bool rx_mode_work_enabled;
444 
445 	/* Does the affinity hint is set for virtqueues? */
446 	bool affinity_hint_set;
447 
448 	/* CPU hotplug instances for online & dead */
449 	struct hlist_node node;
450 	struct hlist_node node_dead;
451 
452 	struct control_buf *ctrl;
453 
454 	/* Ethtool settings */
455 	u8 duplex;
456 	u32 speed;
457 
458 	/* Is rx dynamic interrupt moderation enabled? */
459 	bool rx_dim_enabled;
460 
461 	/* Interrupt coalescing settings */
462 	struct virtnet_interrupt_coalesce intr_coal_tx;
463 	struct virtnet_interrupt_coalesce intr_coal_rx;
464 
465 	unsigned long guest_offloads;
466 	unsigned long guest_offloads_capable;
467 
468 	/* failover when STANDBY feature enabled */
469 	struct failover *failover;
470 
471 	u64 device_stats_cap;
472 };
473 
474 struct padded_vnet_hdr {
475 	struct virtio_net_hdr_v1_hash hdr;
476 	/*
477 	 * hdr is in a separate sg buffer, and data sg buffer shares same page
478 	 * with this header sg. This padding makes next sg 16 byte aligned
479 	 * after the header.
480 	 */
481 	char padding[12];
482 };
483 
484 struct virtio_net_common_hdr {
485 	union {
486 		struct virtio_net_hdr hdr;
487 		struct virtio_net_hdr_mrg_rxbuf	mrg_hdr;
488 		struct virtio_net_hdr_v1_hash hash_v1_hdr;
489 	};
490 };
491 
492 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf);
493 
494 static bool is_xdp_frame(void *ptr)
495 {
496 	return (unsigned long)ptr & VIRTIO_XDP_FLAG;
497 }
498 
499 static void *xdp_to_ptr(struct xdp_frame *ptr)
500 {
501 	return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
502 }
503 
504 static struct xdp_frame *ptr_to_xdp(void *ptr)
505 {
506 	return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
507 }
508 
509 static void __free_old_xmit(struct send_queue *sq, bool in_napi,
510 			    struct virtnet_sq_free_stats *stats)
511 {
512 	unsigned int len;
513 	void *ptr;
514 
515 	while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
516 		++stats->packets;
517 
518 		if (!is_xdp_frame(ptr)) {
519 			struct sk_buff *skb = ptr;
520 
521 			pr_debug("Sent skb %p\n", skb);
522 
523 			stats->bytes += skb->len;
524 			napi_consume_skb(skb, in_napi);
525 		} else {
526 			struct xdp_frame *frame = ptr_to_xdp(ptr);
527 
528 			stats->bytes += xdp_get_frame_len(frame);
529 			xdp_return_frame(frame);
530 		}
531 	}
532 }
533 
534 /* Converting between virtqueue no. and kernel tx/rx queue no.
535  * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
536  */
537 static int vq2txq(struct virtqueue *vq)
538 {
539 	return (vq->index - 1) / 2;
540 }
541 
542 static int txq2vq(int txq)
543 {
544 	return txq * 2 + 1;
545 }
546 
547 static int vq2rxq(struct virtqueue *vq)
548 {
549 	return vq->index / 2;
550 }
551 
552 static int rxq2vq(int rxq)
553 {
554 	return rxq * 2;
555 }
556 
557 static int vq_type(struct virtnet_info *vi, int qid)
558 {
559 	if (qid == vi->max_queue_pairs * 2)
560 		return VIRTNET_Q_TYPE_CQ;
561 
562 	if (qid % 2)
563 		return VIRTNET_Q_TYPE_TX;
564 
565 	return VIRTNET_Q_TYPE_RX;
566 }
567 
568 static inline struct virtio_net_common_hdr *
569 skb_vnet_common_hdr(struct sk_buff *skb)
570 {
571 	return (struct virtio_net_common_hdr *)skb->cb;
572 }
573 
574 /*
575  * private is used to chain pages for big packets, put the whole
576  * most recent used list in the beginning for reuse
577  */
578 static void give_pages(struct receive_queue *rq, struct page *page)
579 {
580 	struct page *end;
581 
582 	/* Find end of list, sew whole thing into vi->rq.pages. */
583 	for (end = page; end->private; end = (struct page *)end->private);
584 	end->private = (unsigned long)rq->pages;
585 	rq->pages = page;
586 }
587 
588 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
589 {
590 	struct page *p = rq->pages;
591 
592 	if (p) {
593 		rq->pages = (struct page *)p->private;
594 		/* clear private here, it is used to chain pages */
595 		p->private = 0;
596 	} else
597 		p = alloc_page(gfp_mask);
598 	return p;
599 }
600 
601 static void virtnet_rq_free_buf(struct virtnet_info *vi,
602 				struct receive_queue *rq, void *buf)
603 {
604 	if (vi->mergeable_rx_bufs)
605 		put_page(virt_to_head_page(buf));
606 	else if (vi->big_packets)
607 		give_pages(rq, buf);
608 	else
609 		put_page(virt_to_head_page(buf));
610 }
611 
612 static void enable_delayed_refill(struct virtnet_info *vi)
613 {
614 	spin_lock_bh(&vi->refill_lock);
615 	vi->refill_enabled = true;
616 	spin_unlock_bh(&vi->refill_lock);
617 }
618 
619 static void disable_delayed_refill(struct virtnet_info *vi)
620 {
621 	spin_lock_bh(&vi->refill_lock);
622 	vi->refill_enabled = false;
623 	spin_unlock_bh(&vi->refill_lock);
624 }
625 
626 static void enable_rx_mode_work(struct virtnet_info *vi)
627 {
628 	rtnl_lock();
629 	vi->rx_mode_work_enabled = true;
630 	rtnl_unlock();
631 }
632 
633 static void disable_rx_mode_work(struct virtnet_info *vi)
634 {
635 	rtnl_lock();
636 	vi->rx_mode_work_enabled = false;
637 	rtnl_unlock();
638 }
639 
640 static void virtqueue_napi_schedule(struct napi_struct *napi,
641 				    struct virtqueue *vq)
642 {
643 	if (napi_schedule_prep(napi)) {
644 		virtqueue_disable_cb(vq);
645 		__napi_schedule(napi);
646 	}
647 }
648 
649 static bool virtqueue_napi_complete(struct napi_struct *napi,
650 				    struct virtqueue *vq, int processed)
651 {
652 	int opaque;
653 
654 	opaque = virtqueue_enable_cb_prepare(vq);
655 	if (napi_complete_done(napi, processed)) {
656 		if (unlikely(virtqueue_poll(vq, opaque)))
657 			virtqueue_napi_schedule(napi, vq);
658 		else
659 			return true;
660 	} else {
661 		virtqueue_disable_cb(vq);
662 	}
663 
664 	return false;
665 }
666 
667 static void skb_xmit_done(struct virtqueue *vq)
668 {
669 	struct virtnet_info *vi = vq->vdev->priv;
670 	struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
671 
672 	/* Suppress further interrupts. */
673 	virtqueue_disable_cb(vq);
674 
675 	if (napi->weight)
676 		virtqueue_napi_schedule(napi, vq);
677 	else
678 		/* We were probably waiting for more output buffers. */
679 		netif_wake_subqueue(vi->dev, vq2txq(vq));
680 }
681 
682 #define MRG_CTX_HEADER_SHIFT 22
683 static void *mergeable_len_to_ctx(unsigned int truesize,
684 				  unsigned int headroom)
685 {
686 	return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
687 }
688 
689 static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
690 {
691 	return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
692 }
693 
694 static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
695 {
696 	return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
697 }
698 
699 static struct sk_buff *virtnet_build_skb(void *buf, unsigned int buflen,
700 					 unsigned int headroom,
701 					 unsigned int len)
702 {
703 	struct sk_buff *skb;
704 
705 	skb = build_skb(buf, buflen);
706 	if (unlikely(!skb))
707 		return NULL;
708 
709 	skb_reserve(skb, headroom);
710 	skb_put(skb, len);
711 
712 	return skb;
713 }
714 
715 /* Called from bottom half context */
716 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
717 				   struct receive_queue *rq,
718 				   struct page *page, unsigned int offset,
719 				   unsigned int len, unsigned int truesize,
720 				   unsigned int headroom)
721 {
722 	struct sk_buff *skb;
723 	struct virtio_net_common_hdr *hdr;
724 	unsigned int copy, hdr_len, hdr_padded_len;
725 	struct page *page_to_free = NULL;
726 	int tailroom, shinfo_size;
727 	char *p, *hdr_p, *buf;
728 
729 	p = page_address(page) + offset;
730 	hdr_p = p;
731 
732 	hdr_len = vi->hdr_len;
733 	if (vi->mergeable_rx_bufs)
734 		hdr_padded_len = hdr_len;
735 	else
736 		hdr_padded_len = sizeof(struct padded_vnet_hdr);
737 
738 	buf = p - headroom;
739 	len -= hdr_len;
740 	offset += hdr_padded_len;
741 	p += hdr_padded_len;
742 	tailroom = truesize - headroom  - hdr_padded_len - len;
743 
744 	shinfo_size = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
745 
746 	if (!NET_IP_ALIGN && len > GOOD_COPY_LEN && tailroom >= shinfo_size) {
747 		skb = virtnet_build_skb(buf, truesize, p - buf, len);
748 		if (unlikely(!skb))
749 			return NULL;
750 
751 		page = (struct page *)page->private;
752 		if (page)
753 			give_pages(rq, page);
754 		goto ok;
755 	}
756 
757 	/* copy small packet so we can reuse these pages for small data */
758 	skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
759 	if (unlikely(!skb))
760 		return NULL;
761 
762 	/* Copy all frame if it fits skb->head, otherwise
763 	 * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
764 	 */
765 	if (len <= skb_tailroom(skb))
766 		copy = len;
767 	else
768 		copy = ETH_HLEN;
769 	skb_put_data(skb, p, copy);
770 
771 	len -= copy;
772 	offset += copy;
773 
774 	if (vi->mergeable_rx_bufs) {
775 		if (len)
776 			skb_add_rx_frag(skb, 0, page, offset, len, truesize);
777 		else
778 			page_to_free = page;
779 		goto ok;
780 	}
781 
782 	/*
783 	 * Verify that we can indeed put this data into a skb.
784 	 * This is here to handle cases when the device erroneously
785 	 * tries to receive more than is possible. This is usually
786 	 * the case of a broken device.
787 	 */
788 	if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
789 		net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
790 		dev_kfree_skb(skb);
791 		return NULL;
792 	}
793 	BUG_ON(offset >= PAGE_SIZE);
794 	while (len) {
795 		unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
796 		skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
797 				frag_size, truesize);
798 		len -= frag_size;
799 		page = (struct page *)page->private;
800 		offset = 0;
801 	}
802 
803 	if (page)
804 		give_pages(rq, page);
805 
806 ok:
807 	hdr = skb_vnet_common_hdr(skb);
808 	memcpy(hdr, hdr_p, hdr_len);
809 	if (page_to_free)
810 		put_page(page_to_free);
811 
812 	return skb;
813 }
814 
815 static void virtnet_rq_unmap(struct receive_queue *rq, void *buf, u32 len)
816 {
817 	struct page *page = virt_to_head_page(buf);
818 	struct virtnet_rq_dma *dma;
819 	void *head;
820 	int offset;
821 
822 	head = page_address(page);
823 
824 	dma = head;
825 
826 	--dma->ref;
827 
828 	if (dma->need_sync && len) {
829 		offset = buf - (head + sizeof(*dma));
830 
831 		virtqueue_dma_sync_single_range_for_cpu(rq->vq, dma->addr,
832 							offset, len,
833 							DMA_FROM_DEVICE);
834 	}
835 
836 	if (dma->ref)
837 		return;
838 
839 	virtqueue_dma_unmap_single_attrs(rq->vq, dma->addr, dma->len,
840 					 DMA_FROM_DEVICE, DMA_ATTR_SKIP_CPU_SYNC);
841 	put_page(page);
842 }
843 
844 static void *virtnet_rq_get_buf(struct receive_queue *rq, u32 *len, void **ctx)
845 {
846 	void *buf;
847 
848 	buf = virtqueue_get_buf_ctx(rq->vq, len, ctx);
849 	if (buf)
850 		virtnet_rq_unmap(rq, buf, *len);
851 
852 	return buf;
853 }
854 
855 static void virtnet_rq_init_one_sg(struct receive_queue *rq, void *buf, u32 len)
856 {
857 	struct virtnet_rq_dma *dma;
858 	dma_addr_t addr;
859 	u32 offset;
860 	void *head;
861 
862 	head = page_address(rq->alloc_frag.page);
863 
864 	offset = buf - head;
865 
866 	dma = head;
867 
868 	addr = dma->addr - sizeof(*dma) + offset;
869 
870 	sg_init_table(rq->sg, 1);
871 	rq->sg[0].dma_address = addr;
872 	rq->sg[0].length = len;
873 }
874 
875 static void *virtnet_rq_alloc(struct receive_queue *rq, u32 size, gfp_t gfp)
876 {
877 	struct page_frag *alloc_frag = &rq->alloc_frag;
878 	struct virtnet_rq_dma *dma;
879 	void *buf, *head;
880 	dma_addr_t addr;
881 
882 	if (unlikely(!skb_page_frag_refill(size, alloc_frag, gfp)))
883 		return NULL;
884 
885 	head = page_address(alloc_frag->page);
886 
887 	dma = head;
888 
889 	/* new pages */
890 	if (!alloc_frag->offset) {
891 		if (rq->last_dma) {
892 			/* Now, the new page is allocated, the last dma
893 			 * will not be used. So the dma can be unmapped
894 			 * if the ref is 0.
895 			 */
896 			virtnet_rq_unmap(rq, rq->last_dma, 0);
897 			rq->last_dma = NULL;
898 		}
899 
900 		dma->len = alloc_frag->size - sizeof(*dma);
901 
902 		addr = virtqueue_dma_map_single_attrs(rq->vq, dma + 1,
903 						      dma->len, DMA_FROM_DEVICE, 0);
904 		if (virtqueue_dma_mapping_error(rq->vq, addr))
905 			return NULL;
906 
907 		dma->addr = addr;
908 		dma->need_sync = virtqueue_dma_need_sync(rq->vq, addr);
909 
910 		/* Add a reference to dma to prevent the entire dma from
911 		 * being released during error handling. This reference
912 		 * will be freed after the pages are no longer used.
913 		 */
914 		get_page(alloc_frag->page);
915 		dma->ref = 1;
916 		alloc_frag->offset = sizeof(*dma);
917 
918 		rq->last_dma = dma;
919 	}
920 
921 	++dma->ref;
922 
923 	buf = head + alloc_frag->offset;
924 
925 	get_page(alloc_frag->page);
926 	alloc_frag->offset += size;
927 
928 	return buf;
929 }
930 
931 static void virtnet_rq_set_premapped(struct virtnet_info *vi)
932 {
933 	int i;
934 
935 	/* disable for big mode */
936 	if (!vi->mergeable_rx_bufs && vi->big_packets)
937 		return;
938 
939 	for (i = 0; i < vi->max_queue_pairs; i++)
940 		/* error should never happen */
941 		BUG_ON(virtqueue_set_dma_premapped(vi->rq[i].vq));
942 }
943 
944 static void virtnet_rq_unmap_free_buf(struct virtqueue *vq, void *buf)
945 {
946 	struct virtnet_info *vi = vq->vdev->priv;
947 	struct receive_queue *rq;
948 	int i = vq2rxq(vq);
949 
950 	rq = &vi->rq[i];
951 
952 	if (!vi->big_packets || vi->mergeable_rx_bufs)
953 		virtnet_rq_unmap(rq, buf, 0);
954 
955 	virtnet_rq_free_buf(vi, rq, buf);
956 }
957 
958 static void free_old_xmit(struct send_queue *sq, bool in_napi)
959 {
960 	struct virtnet_sq_free_stats stats = {0};
961 
962 	__free_old_xmit(sq, in_napi, &stats);
963 
964 	/* Avoid overhead when no packets have been processed
965 	 * happens when called speculatively from start_xmit.
966 	 */
967 	if (!stats.packets)
968 		return;
969 
970 	u64_stats_update_begin(&sq->stats.syncp);
971 	u64_stats_add(&sq->stats.bytes, stats.bytes);
972 	u64_stats_add(&sq->stats.packets, stats.packets);
973 	u64_stats_update_end(&sq->stats.syncp);
974 }
975 
976 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
977 {
978 	if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
979 		return false;
980 	else if (q < vi->curr_queue_pairs)
981 		return true;
982 	else
983 		return false;
984 }
985 
986 static void check_sq_full_and_disable(struct virtnet_info *vi,
987 				      struct net_device *dev,
988 				      struct send_queue *sq)
989 {
990 	bool use_napi = sq->napi.weight;
991 	int qnum;
992 
993 	qnum = sq - vi->sq;
994 
995 	/* If running out of space, stop queue to avoid getting packets that we
996 	 * are then unable to transmit.
997 	 * An alternative would be to force queuing layer to requeue the skb by
998 	 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
999 	 * returned in a normal path of operation: it means that driver is not
1000 	 * maintaining the TX queue stop/start state properly, and causes
1001 	 * the stack to do a non-trivial amount of useless work.
1002 	 * Since most packets only take 1 or 2 ring slots, stopping the queue
1003 	 * early means 16 slots are typically wasted.
1004 	 */
1005 	if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1006 		netif_stop_subqueue(dev, qnum);
1007 		u64_stats_update_begin(&sq->stats.syncp);
1008 		u64_stats_inc(&sq->stats.stop);
1009 		u64_stats_update_end(&sq->stats.syncp);
1010 		if (use_napi) {
1011 			if (unlikely(!virtqueue_enable_cb_delayed(sq->vq)))
1012 				virtqueue_napi_schedule(&sq->napi, sq->vq);
1013 		} else if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1014 			/* More just got used, free them then recheck. */
1015 			free_old_xmit(sq, false);
1016 			if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1017 				netif_start_subqueue(dev, qnum);
1018 				u64_stats_update_begin(&sq->stats.syncp);
1019 				u64_stats_inc(&sq->stats.wake);
1020 				u64_stats_update_end(&sq->stats.syncp);
1021 				virtqueue_disable_cb(sq->vq);
1022 			}
1023 		}
1024 	}
1025 }
1026 
1027 static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
1028 				   struct send_queue *sq,
1029 				   struct xdp_frame *xdpf)
1030 {
1031 	struct virtio_net_hdr_mrg_rxbuf *hdr;
1032 	struct skb_shared_info *shinfo;
1033 	u8 nr_frags = 0;
1034 	int err, i;
1035 
1036 	if (unlikely(xdpf->headroom < vi->hdr_len))
1037 		return -EOVERFLOW;
1038 
1039 	if (unlikely(xdp_frame_has_frags(xdpf))) {
1040 		shinfo = xdp_get_shared_info_from_frame(xdpf);
1041 		nr_frags = shinfo->nr_frags;
1042 	}
1043 
1044 	/* In wrapping function virtnet_xdp_xmit(), we need to free
1045 	 * up the pending old buffers, where we need to calculate the
1046 	 * position of skb_shared_info in xdp_get_frame_len() and
1047 	 * xdp_return_frame(), which will involve to xdpf->data and
1048 	 * xdpf->headroom. Therefore, we need to update the value of
1049 	 * headroom synchronously here.
1050 	 */
1051 	xdpf->headroom -= vi->hdr_len;
1052 	xdpf->data -= vi->hdr_len;
1053 	/* Zero header and leave csum up to XDP layers */
1054 	hdr = xdpf->data;
1055 	memset(hdr, 0, vi->hdr_len);
1056 	xdpf->len   += vi->hdr_len;
1057 
1058 	sg_init_table(sq->sg, nr_frags + 1);
1059 	sg_set_buf(sq->sg, xdpf->data, xdpf->len);
1060 	for (i = 0; i < nr_frags; i++) {
1061 		skb_frag_t *frag = &shinfo->frags[i];
1062 
1063 		sg_set_page(&sq->sg[i + 1], skb_frag_page(frag),
1064 			    skb_frag_size(frag), skb_frag_off(frag));
1065 	}
1066 
1067 	err = virtqueue_add_outbuf(sq->vq, sq->sg, nr_frags + 1,
1068 				   xdp_to_ptr(xdpf), GFP_ATOMIC);
1069 	if (unlikely(err))
1070 		return -ENOSPC; /* Caller handle free/refcnt */
1071 
1072 	return 0;
1073 }
1074 
1075 /* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
1076  * the current cpu, so it does not need to be locked.
1077  *
1078  * Here we use marco instead of inline functions because we have to deal with
1079  * three issues at the same time: 1. the choice of sq. 2. judge and execute the
1080  * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
1081  * functions to perfectly solve these three problems at the same time.
1082  */
1083 #define virtnet_xdp_get_sq(vi) ({                                       \
1084 	int cpu = smp_processor_id();                                   \
1085 	struct netdev_queue *txq;                                       \
1086 	typeof(vi) v = (vi);                                            \
1087 	unsigned int qp;                                                \
1088 									\
1089 	if (v->curr_queue_pairs > nr_cpu_ids) {                         \
1090 		qp = v->curr_queue_pairs - v->xdp_queue_pairs;          \
1091 		qp += cpu;                                              \
1092 		txq = netdev_get_tx_queue(v->dev, qp);                  \
1093 		__netif_tx_acquire(txq);                                \
1094 	} else {                                                        \
1095 		qp = cpu % v->curr_queue_pairs;                         \
1096 		txq = netdev_get_tx_queue(v->dev, qp);                  \
1097 		__netif_tx_lock(txq, cpu);                              \
1098 	}                                                               \
1099 	v->sq + qp;                                                     \
1100 })
1101 
1102 #define virtnet_xdp_put_sq(vi, q) {                                     \
1103 	struct netdev_queue *txq;                                       \
1104 	typeof(vi) v = (vi);                                            \
1105 									\
1106 	txq = netdev_get_tx_queue(v->dev, (q) - v->sq);                 \
1107 	if (v->curr_queue_pairs > nr_cpu_ids)                           \
1108 		__netif_tx_release(txq);                                \
1109 	else                                                            \
1110 		__netif_tx_unlock(txq);                                 \
1111 }
1112 
1113 static int virtnet_xdp_xmit(struct net_device *dev,
1114 			    int n, struct xdp_frame **frames, u32 flags)
1115 {
1116 	struct virtnet_info *vi = netdev_priv(dev);
1117 	struct virtnet_sq_free_stats stats = {0};
1118 	struct receive_queue *rq = vi->rq;
1119 	struct bpf_prog *xdp_prog;
1120 	struct send_queue *sq;
1121 	int nxmit = 0;
1122 	int kicks = 0;
1123 	int ret;
1124 	int i;
1125 
1126 	/* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
1127 	 * indicate XDP resources have been successfully allocated.
1128 	 */
1129 	xdp_prog = rcu_access_pointer(rq->xdp_prog);
1130 	if (!xdp_prog)
1131 		return -ENXIO;
1132 
1133 	sq = virtnet_xdp_get_sq(vi);
1134 
1135 	if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
1136 		ret = -EINVAL;
1137 		goto out;
1138 	}
1139 
1140 	/* Free up any pending old buffers before queueing new ones. */
1141 	__free_old_xmit(sq, false, &stats);
1142 
1143 	for (i = 0; i < n; i++) {
1144 		struct xdp_frame *xdpf = frames[i];
1145 
1146 		if (__virtnet_xdp_xmit_one(vi, sq, xdpf))
1147 			break;
1148 		nxmit++;
1149 	}
1150 	ret = nxmit;
1151 
1152 	if (!is_xdp_raw_buffer_queue(vi, sq - vi->sq))
1153 		check_sq_full_and_disable(vi, dev, sq);
1154 
1155 	if (flags & XDP_XMIT_FLUSH) {
1156 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
1157 			kicks = 1;
1158 	}
1159 out:
1160 	u64_stats_update_begin(&sq->stats.syncp);
1161 	u64_stats_add(&sq->stats.bytes, stats.bytes);
1162 	u64_stats_add(&sq->stats.packets, stats.packets);
1163 	u64_stats_add(&sq->stats.xdp_tx, n);
1164 	u64_stats_add(&sq->stats.xdp_tx_drops, n - nxmit);
1165 	u64_stats_add(&sq->stats.kicks, kicks);
1166 	u64_stats_update_end(&sq->stats.syncp);
1167 
1168 	virtnet_xdp_put_sq(vi, sq);
1169 	return ret;
1170 }
1171 
1172 static void put_xdp_frags(struct xdp_buff *xdp)
1173 {
1174 	struct skb_shared_info *shinfo;
1175 	struct page *xdp_page;
1176 	int i;
1177 
1178 	if (xdp_buff_has_frags(xdp)) {
1179 		shinfo = xdp_get_shared_info_from_buff(xdp);
1180 		for (i = 0; i < shinfo->nr_frags; i++) {
1181 			xdp_page = skb_frag_page(&shinfo->frags[i]);
1182 			put_page(xdp_page);
1183 		}
1184 	}
1185 }
1186 
1187 static int virtnet_xdp_handler(struct bpf_prog *xdp_prog, struct xdp_buff *xdp,
1188 			       struct net_device *dev,
1189 			       unsigned int *xdp_xmit,
1190 			       struct virtnet_rq_stats *stats)
1191 {
1192 	struct xdp_frame *xdpf;
1193 	int err;
1194 	u32 act;
1195 
1196 	act = bpf_prog_run_xdp(xdp_prog, xdp);
1197 	u64_stats_inc(&stats->xdp_packets);
1198 
1199 	switch (act) {
1200 	case XDP_PASS:
1201 		return act;
1202 
1203 	case XDP_TX:
1204 		u64_stats_inc(&stats->xdp_tx);
1205 		xdpf = xdp_convert_buff_to_frame(xdp);
1206 		if (unlikely(!xdpf)) {
1207 			netdev_dbg(dev, "convert buff to frame failed for xdp\n");
1208 			return XDP_DROP;
1209 		}
1210 
1211 		err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
1212 		if (unlikely(!err)) {
1213 			xdp_return_frame_rx_napi(xdpf);
1214 		} else if (unlikely(err < 0)) {
1215 			trace_xdp_exception(dev, xdp_prog, act);
1216 			return XDP_DROP;
1217 		}
1218 		*xdp_xmit |= VIRTIO_XDP_TX;
1219 		return act;
1220 
1221 	case XDP_REDIRECT:
1222 		u64_stats_inc(&stats->xdp_redirects);
1223 		err = xdp_do_redirect(dev, xdp, xdp_prog);
1224 		if (err)
1225 			return XDP_DROP;
1226 
1227 		*xdp_xmit |= VIRTIO_XDP_REDIR;
1228 		return act;
1229 
1230 	default:
1231 		bpf_warn_invalid_xdp_action(dev, xdp_prog, act);
1232 		fallthrough;
1233 	case XDP_ABORTED:
1234 		trace_xdp_exception(dev, xdp_prog, act);
1235 		fallthrough;
1236 	case XDP_DROP:
1237 		return XDP_DROP;
1238 	}
1239 }
1240 
1241 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
1242 {
1243 	return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
1244 }
1245 
1246 /* We copy the packet for XDP in the following cases:
1247  *
1248  * 1) Packet is scattered across multiple rx buffers.
1249  * 2) Headroom space is insufficient.
1250  *
1251  * This is inefficient but it's a temporary condition that
1252  * we hit right after XDP is enabled and until queue is refilled
1253  * with large buffers with sufficient headroom - so it should affect
1254  * at most queue size packets.
1255  * Afterwards, the conditions to enable
1256  * XDP should preclude the underlying device from sending packets
1257  * across multiple buffers (num_buf > 1), and we make sure buffers
1258  * have enough headroom.
1259  */
1260 static struct page *xdp_linearize_page(struct receive_queue *rq,
1261 				       int *num_buf,
1262 				       struct page *p,
1263 				       int offset,
1264 				       int page_off,
1265 				       unsigned int *len)
1266 {
1267 	int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1268 	struct page *page;
1269 
1270 	if (page_off + *len + tailroom > PAGE_SIZE)
1271 		return NULL;
1272 
1273 	page = alloc_page(GFP_ATOMIC);
1274 	if (!page)
1275 		return NULL;
1276 
1277 	memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
1278 	page_off += *len;
1279 
1280 	while (--*num_buf) {
1281 		unsigned int buflen;
1282 		void *buf;
1283 		int off;
1284 
1285 		buf = virtnet_rq_get_buf(rq, &buflen, NULL);
1286 		if (unlikely(!buf))
1287 			goto err_buf;
1288 
1289 		p = virt_to_head_page(buf);
1290 		off = buf - page_address(p);
1291 
1292 		/* guard against a misconfigured or uncooperative backend that
1293 		 * is sending packet larger than the MTU.
1294 		 */
1295 		if ((page_off + buflen + tailroom) > PAGE_SIZE) {
1296 			put_page(p);
1297 			goto err_buf;
1298 		}
1299 
1300 		memcpy(page_address(page) + page_off,
1301 		       page_address(p) + off, buflen);
1302 		page_off += buflen;
1303 		put_page(p);
1304 	}
1305 
1306 	/* Headroom does not contribute to packet length */
1307 	*len = page_off - VIRTIO_XDP_HEADROOM;
1308 	return page;
1309 err_buf:
1310 	__free_pages(page, 0);
1311 	return NULL;
1312 }
1313 
1314 static struct sk_buff *receive_small_build_skb(struct virtnet_info *vi,
1315 					       unsigned int xdp_headroom,
1316 					       void *buf,
1317 					       unsigned int len)
1318 {
1319 	unsigned int header_offset;
1320 	unsigned int headroom;
1321 	unsigned int buflen;
1322 	struct sk_buff *skb;
1323 
1324 	header_offset = VIRTNET_RX_PAD + xdp_headroom;
1325 	headroom = vi->hdr_len + header_offset;
1326 	buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
1327 		SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1328 
1329 	skb = virtnet_build_skb(buf, buflen, headroom, len);
1330 	if (unlikely(!skb))
1331 		return NULL;
1332 
1333 	buf += header_offset;
1334 	memcpy(skb_vnet_common_hdr(skb), buf, vi->hdr_len);
1335 
1336 	return skb;
1337 }
1338 
1339 static struct sk_buff *receive_small_xdp(struct net_device *dev,
1340 					 struct virtnet_info *vi,
1341 					 struct receive_queue *rq,
1342 					 struct bpf_prog *xdp_prog,
1343 					 void *buf,
1344 					 unsigned int xdp_headroom,
1345 					 unsigned int len,
1346 					 unsigned int *xdp_xmit,
1347 					 struct virtnet_rq_stats *stats)
1348 {
1349 	unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
1350 	unsigned int headroom = vi->hdr_len + header_offset;
1351 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
1352 	struct page *page = virt_to_head_page(buf);
1353 	struct page *xdp_page;
1354 	unsigned int buflen;
1355 	struct xdp_buff xdp;
1356 	struct sk_buff *skb;
1357 	unsigned int metasize = 0;
1358 	u32 act;
1359 
1360 	if (unlikely(hdr->hdr.gso_type))
1361 		goto err_xdp;
1362 
1363 	/* Partially checksummed packets must be dropped. */
1364 	if (unlikely(hdr->hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM))
1365 		goto err_xdp;
1366 
1367 	buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
1368 		SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1369 
1370 	if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
1371 		int offset = buf - page_address(page) + header_offset;
1372 		unsigned int tlen = len + vi->hdr_len;
1373 		int num_buf = 1;
1374 
1375 		xdp_headroom = virtnet_get_headroom(vi);
1376 		header_offset = VIRTNET_RX_PAD + xdp_headroom;
1377 		headroom = vi->hdr_len + header_offset;
1378 		buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
1379 			SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1380 		xdp_page = xdp_linearize_page(rq, &num_buf, page,
1381 					      offset, header_offset,
1382 					      &tlen);
1383 		if (!xdp_page)
1384 			goto err_xdp;
1385 
1386 		buf = page_address(xdp_page);
1387 		put_page(page);
1388 		page = xdp_page;
1389 	}
1390 
1391 	xdp_init_buff(&xdp, buflen, &rq->xdp_rxq);
1392 	xdp_prepare_buff(&xdp, buf + VIRTNET_RX_PAD + vi->hdr_len,
1393 			 xdp_headroom, len, true);
1394 
1395 	act = virtnet_xdp_handler(xdp_prog, &xdp, dev, xdp_xmit, stats);
1396 
1397 	switch (act) {
1398 	case XDP_PASS:
1399 		/* Recalculate length in case bpf program changed it */
1400 		len = xdp.data_end - xdp.data;
1401 		metasize = xdp.data - xdp.data_meta;
1402 		break;
1403 
1404 	case XDP_TX:
1405 	case XDP_REDIRECT:
1406 		goto xdp_xmit;
1407 
1408 	default:
1409 		goto err_xdp;
1410 	}
1411 
1412 	skb = virtnet_build_skb(buf, buflen, xdp.data - buf, len);
1413 	if (unlikely(!skb))
1414 		goto err;
1415 
1416 	if (metasize)
1417 		skb_metadata_set(skb, metasize);
1418 
1419 	return skb;
1420 
1421 err_xdp:
1422 	u64_stats_inc(&stats->xdp_drops);
1423 err:
1424 	u64_stats_inc(&stats->drops);
1425 	put_page(page);
1426 xdp_xmit:
1427 	return NULL;
1428 }
1429 
1430 static struct sk_buff *receive_small(struct net_device *dev,
1431 				     struct virtnet_info *vi,
1432 				     struct receive_queue *rq,
1433 				     void *buf, void *ctx,
1434 				     unsigned int len,
1435 				     unsigned int *xdp_xmit,
1436 				     struct virtnet_rq_stats *stats)
1437 {
1438 	unsigned int xdp_headroom = (unsigned long)ctx;
1439 	struct page *page = virt_to_head_page(buf);
1440 	struct sk_buff *skb;
1441 
1442 	len -= vi->hdr_len;
1443 	u64_stats_add(&stats->bytes, len);
1444 
1445 	if (unlikely(len > GOOD_PACKET_LEN)) {
1446 		pr_debug("%s: rx error: len %u exceeds max size %d\n",
1447 			 dev->name, len, GOOD_PACKET_LEN);
1448 		DEV_STATS_INC(dev, rx_length_errors);
1449 		goto err;
1450 	}
1451 
1452 	if (unlikely(vi->xdp_enabled)) {
1453 		struct bpf_prog *xdp_prog;
1454 
1455 		rcu_read_lock();
1456 		xdp_prog = rcu_dereference(rq->xdp_prog);
1457 		if (xdp_prog) {
1458 			skb = receive_small_xdp(dev, vi, rq, xdp_prog, buf,
1459 						xdp_headroom, len, xdp_xmit,
1460 						stats);
1461 			rcu_read_unlock();
1462 			return skb;
1463 		}
1464 		rcu_read_unlock();
1465 	}
1466 
1467 	skb = receive_small_build_skb(vi, xdp_headroom, buf, len);
1468 	if (likely(skb))
1469 		return skb;
1470 
1471 err:
1472 	u64_stats_inc(&stats->drops);
1473 	put_page(page);
1474 	return NULL;
1475 }
1476 
1477 static struct sk_buff *receive_big(struct net_device *dev,
1478 				   struct virtnet_info *vi,
1479 				   struct receive_queue *rq,
1480 				   void *buf,
1481 				   unsigned int len,
1482 				   struct virtnet_rq_stats *stats)
1483 {
1484 	struct page *page = buf;
1485 	struct sk_buff *skb =
1486 		page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, 0);
1487 
1488 	u64_stats_add(&stats->bytes, len - vi->hdr_len);
1489 	if (unlikely(!skb))
1490 		goto err;
1491 
1492 	return skb;
1493 
1494 err:
1495 	u64_stats_inc(&stats->drops);
1496 	give_pages(rq, page);
1497 	return NULL;
1498 }
1499 
1500 static void mergeable_buf_free(struct receive_queue *rq, int num_buf,
1501 			       struct net_device *dev,
1502 			       struct virtnet_rq_stats *stats)
1503 {
1504 	struct page *page;
1505 	void *buf;
1506 	int len;
1507 
1508 	while (num_buf-- > 1) {
1509 		buf = virtnet_rq_get_buf(rq, &len, NULL);
1510 		if (unlikely(!buf)) {
1511 			pr_debug("%s: rx error: %d buffers missing\n",
1512 				 dev->name, num_buf);
1513 			DEV_STATS_INC(dev, rx_length_errors);
1514 			break;
1515 		}
1516 		u64_stats_add(&stats->bytes, len);
1517 		page = virt_to_head_page(buf);
1518 		put_page(page);
1519 	}
1520 }
1521 
1522 /* Why not use xdp_build_skb_from_frame() ?
1523  * XDP core assumes that xdp frags are PAGE_SIZE in length, while in
1524  * virtio-net there are 2 points that do not match its requirements:
1525  *  1. The size of the prefilled buffer is not fixed before xdp is set.
1526  *  2. xdp_build_skb_from_frame() does more checks that we don't need,
1527  *     like eth_type_trans() (which virtio-net does in receive_buf()).
1528  */
1529 static struct sk_buff *build_skb_from_xdp_buff(struct net_device *dev,
1530 					       struct virtnet_info *vi,
1531 					       struct xdp_buff *xdp,
1532 					       unsigned int xdp_frags_truesz)
1533 {
1534 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
1535 	unsigned int headroom, data_len;
1536 	struct sk_buff *skb;
1537 	int metasize;
1538 	u8 nr_frags;
1539 
1540 	if (unlikely(xdp->data_end > xdp_data_hard_end(xdp))) {
1541 		pr_debug("Error building skb as missing reserved tailroom for xdp");
1542 		return NULL;
1543 	}
1544 
1545 	if (unlikely(xdp_buff_has_frags(xdp)))
1546 		nr_frags = sinfo->nr_frags;
1547 
1548 	skb = build_skb(xdp->data_hard_start, xdp->frame_sz);
1549 	if (unlikely(!skb))
1550 		return NULL;
1551 
1552 	headroom = xdp->data - xdp->data_hard_start;
1553 	data_len = xdp->data_end - xdp->data;
1554 	skb_reserve(skb, headroom);
1555 	__skb_put(skb, data_len);
1556 
1557 	metasize = xdp->data - xdp->data_meta;
1558 	metasize = metasize > 0 ? metasize : 0;
1559 	if (metasize)
1560 		skb_metadata_set(skb, metasize);
1561 
1562 	if (unlikely(xdp_buff_has_frags(xdp)))
1563 		xdp_update_skb_shared_info(skb, nr_frags,
1564 					   sinfo->xdp_frags_size,
1565 					   xdp_frags_truesz,
1566 					   xdp_buff_is_frag_pfmemalloc(xdp));
1567 
1568 	return skb;
1569 }
1570 
1571 /* TODO: build xdp in big mode */
1572 static int virtnet_build_xdp_buff_mrg(struct net_device *dev,
1573 				      struct virtnet_info *vi,
1574 				      struct receive_queue *rq,
1575 				      struct xdp_buff *xdp,
1576 				      void *buf,
1577 				      unsigned int len,
1578 				      unsigned int frame_sz,
1579 				      int *num_buf,
1580 				      unsigned int *xdp_frags_truesize,
1581 				      struct virtnet_rq_stats *stats)
1582 {
1583 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1584 	unsigned int headroom, tailroom, room;
1585 	unsigned int truesize, cur_frag_size;
1586 	struct skb_shared_info *shinfo;
1587 	unsigned int xdp_frags_truesz = 0;
1588 	struct page *page;
1589 	skb_frag_t *frag;
1590 	int offset;
1591 	void *ctx;
1592 
1593 	xdp_init_buff(xdp, frame_sz, &rq->xdp_rxq);
1594 	xdp_prepare_buff(xdp, buf - VIRTIO_XDP_HEADROOM,
1595 			 VIRTIO_XDP_HEADROOM + vi->hdr_len, len - vi->hdr_len, true);
1596 
1597 	if (!*num_buf)
1598 		return 0;
1599 
1600 	if (*num_buf > 1) {
1601 		/* If we want to build multi-buffer xdp, we need
1602 		 * to specify that the flags of xdp_buff have the
1603 		 * XDP_FLAGS_HAS_FRAG bit.
1604 		 */
1605 		if (!xdp_buff_has_frags(xdp))
1606 			xdp_buff_set_frags_flag(xdp);
1607 
1608 		shinfo = xdp_get_shared_info_from_buff(xdp);
1609 		shinfo->nr_frags = 0;
1610 		shinfo->xdp_frags_size = 0;
1611 	}
1612 
1613 	if (*num_buf > MAX_SKB_FRAGS + 1)
1614 		return -EINVAL;
1615 
1616 	while (--*num_buf > 0) {
1617 		buf = virtnet_rq_get_buf(rq, &len, &ctx);
1618 		if (unlikely(!buf)) {
1619 			pr_debug("%s: rx error: %d buffers out of %d missing\n",
1620 				 dev->name, *num_buf,
1621 				 virtio16_to_cpu(vi->vdev, hdr->num_buffers));
1622 			DEV_STATS_INC(dev, rx_length_errors);
1623 			goto err;
1624 		}
1625 
1626 		u64_stats_add(&stats->bytes, len);
1627 		page = virt_to_head_page(buf);
1628 		offset = buf - page_address(page);
1629 
1630 		truesize = mergeable_ctx_to_truesize(ctx);
1631 		headroom = mergeable_ctx_to_headroom(ctx);
1632 		tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1633 		room = SKB_DATA_ALIGN(headroom + tailroom);
1634 
1635 		cur_frag_size = truesize;
1636 		xdp_frags_truesz += cur_frag_size;
1637 		if (unlikely(len > truesize - room || cur_frag_size > PAGE_SIZE)) {
1638 			put_page(page);
1639 			pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1640 				 dev->name, len, (unsigned long)(truesize - room));
1641 			DEV_STATS_INC(dev, rx_length_errors);
1642 			goto err;
1643 		}
1644 
1645 		frag = &shinfo->frags[shinfo->nr_frags++];
1646 		skb_frag_fill_page_desc(frag, page, offset, len);
1647 		if (page_is_pfmemalloc(page))
1648 			xdp_buff_set_frag_pfmemalloc(xdp);
1649 
1650 		shinfo->xdp_frags_size += len;
1651 	}
1652 
1653 	*xdp_frags_truesize = xdp_frags_truesz;
1654 	return 0;
1655 
1656 err:
1657 	put_xdp_frags(xdp);
1658 	return -EINVAL;
1659 }
1660 
1661 static void *mergeable_xdp_get_buf(struct virtnet_info *vi,
1662 				   struct receive_queue *rq,
1663 				   struct bpf_prog *xdp_prog,
1664 				   void *ctx,
1665 				   unsigned int *frame_sz,
1666 				   int *num_buf,
1667 				   struct page **page,
1668 				   int offset,
1669 				   unsigned int *len,
1670 				   struct virtio_net_hdr_mrg_rxbuf *hdr)
1671 {
1672 	unsigned int truesize = mergeable_ctx_to_truesize(ctx);
1673 	unsigned int headroom = mergeable_ctx_to_headroom(ctx);
1674 	struct page *xdp_page;
1675 	unsigned int xdp_room;
1676 
1677 	/* Transient failure which in theory could occur if
1678 	 * in-flight packets from before XDP was enabled reach
1679 	 * the receive path after XDP is loaded.
1680 	 */
1681 	if (unlikely(hdr->hdr.gso_type))
1682 		return NULL;
1683 
1684 	/* Partially checksummed packets must be dropped. */
1685 	if (unlikely(hdr->hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM))
1686 		return NULL;
1687 
1688 	/* Now XDP core assumes frag size is PAGE_SIZE, but buffers
1689 	 * with headroom may add hole in truesize, which
1690 	 * make their length exceed PAGE_SIZE. So we disabled the
1691 	 * hole mechanism for xdp. See add_recvbuf_mergeable().
1692 	 */
1693 	*frame_sz = truesize;
1694 
1695 	if (likely(headroom >= virtnet_get_headroom(vi) &&
1696 		   (*num_buf == 1 || xdp_prog->aux->xdp_has_frags))) {
1697 		return page_address(*page) + offset;
1698 	}
1699 
1700 	/* This happens when headroom is not enough because
1701 	 * of the buffer was prefilled before XDP is set.
1702 	 * This should only happen for the first several packets.
1703 	 * In fact, vq reset can be used here to help us clean up
1704 	 * the prefilled buffers, but many existing devices do not
1705 	 * support it, and we don't want to bother users who are
1706 	 * using xdp normally.
1707 	 */
1708 	if (!xdp_prog->aux->xdp_has_frags) {
1709 		/* linearize data for XDP */
1710 		xdp_page = xdp_linearize_page(rq, num_buf,
1711 					      *page, offset,
1712 					      VIRTIO_XDP_HEADROOM,
1713 					      len);
1714 		if (!xdp_page)
1715 			return NULL;
1716 	} else {
1717 		xdp_room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
1718 					  sizeof(struct skb_shared_info));
1719 		if (*len + xdp_room > PAGE_SIZE)
1720 			return NULL;
1721 
1722 		xdp_page = alloc_page(GFP_ATOMIC);
1723 		if (!xdp_page)
1724 			return NULL;
1725 
1726 		memcpy(page_address(xdp_page) + VIRTIO_XDP_HEADROOM,
1727 		       page_address(*page) + offset, *len);
1728 	}
1729 
1730 	*frame_sz = PAGE_SIZE;
1731 
1732 	put_page(*page);
1733 
1734 	*page = xdp_page;
1735 
1736 	return page_address(*page) + VIRTIO_XDP_HEADROOM;
1737 }
1738 
1739 static struct sk_buff *receive_mergeable_xdp(struct net_device *dev,
1740 					     struct virtnet_info *vi,
1741 					     struct receive_queue *rq,
1742 					     struct bpf_prog *xdp_prog,
1743 					     void *buf,
1744 					     void *ctx,
1745 					     unsigned int len,
1746 					     unsigned int *xdp_xmit,
1747 					     struct virtnet_rq_stats *stats)
1748 {
1749 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1750 	int num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
1751 	struct page *page = virt_to_head_page(buf);
1752 	int offset = buf - page_address(page);
1753 	unsigned int xdp_frags_truesz = 0;
1754 	struct sk_buff *head_skb;
1755 	unsigned int frame_sz;
1756 	struct xdp_buff xdp;
1757 	void *data;
1758 	u32 act;
1759 	int err;
1760 
1761 	data = mergeable_xdp_get_buf(vi, rq, xdp_prog, ctx, &frame_sz, &num_buf, &page,
1762 				     offset, &len, hdr);
1763 	if (unlikely(!data))
1764 		goto err_xdp;
1765 
1766 	err = virtnet_build_xdp_buff_mrg(dev, vi, rq, &xdp, data, len, frame_sz,
1767 					 &num_buf, &xdp_frags_truesz, stats);
1768 	if (unlikely(err))
1769 		goto err_xdp;
1770 
1771 	act = virtnet_xdp_handler(xdp_prog, &xdp, dev, xdp_xmit, stats);
1772 
1773 	switch (act) {
1774 	case XDP_PASS:
1775 		head_skb = build_skb_from_xdp_buff(dev, vi, &xdp, xdp_frags_truesz);
1776 		if (unlikely(!head_skb))
1777 			break;
1778 		return head_skb;
1779 
1780 	case XDP_TX:
1781 	case XDP_REDIRECT:
1782 		return NULL;
1783 
1784 	default:
1785 		break;
1786 	}
1787 
1788 	put_xdp_frags(&xdp);
1789 
1790 err_xdp:
1791 	put_page(page);
1792 	mergeable_buf_free(rq, num_buf, dev, stats);
1793 
1794 	u64_stats_inc(&stats->xdp_drops);
1795 	u64_stats_inc(&stats->drops);
1796 	return NULL;
1797 }
1798 
1799 static struct sk_buff *receive_mergeable(struct net_device *dev,
1800 					 struct virtnet_info *vi,
1801 					 struct receive_queue *rq,
1802 					 void *buf,
1803 					 void *ctx,
1804 					 unsigned int len,
1805 					 unsigned int *xdp_xmit,
1806 					 struct virtnet_rq_stats *stats)
1807 {
1808 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1809 	int num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
1810 	struct page *page = virt_to_head_page(buf);
1811 	int offset = buf - page_address(page);
1812 	struct sk_buff *head_skb, *curr_skb;
1813 	unsigned int truesize = mergeable_ctx_to_truesize(ctx);
1814 	unsigned int headroom = mergeable_ctx_to_headroom(ctx);
1815 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1816 	unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1817 
1818 	head_skb = NULL;
1819 	u64_stats_add(&stats->bytes, len - vi->hdr_len);
1820 
1821 	if (unlikely(len > truesize - room)) {
1822 		pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1823 			 dev->name, len, (unsigned long)(truesize - room));
1824 		DEV_STATS_INC(dev, rx_length_errors);
1825 		goto err_skb;
1826 	}
1827 
1828 	if (unlikely(vi->xdp_enabled)) {
1829 		struct bpf_prog *xdp_prog;
1830 
1831 		rcu_read_lock();
1832 		xdp_prog = rcu_dereference(rq->xdp_prog);
1833 		if (xdp_prog) {
1834 			head_skb = receive_mergeable_xdp(dev, vi, rq, xdp_prog, buf, ctx,
1835 							 len, xdp_xmit, stats);
1836 			rcu_read_unlock();
1837 			return head_skb;
1838 		}
1839 		rcu_read_unlock();
1840 	}
1841 
1842 	head_skb = page_to_skb(vi, rq, page, offset, len, truesize, headroom);
1843 	curr_skb = head_skb;
1844 
1845 	if (unlikely(!curr_skb))
1846 		goto err_skb;
1847 	while (--num_buf) {
1848 		int num_skb_frags;
1849 
1850 		buf = virtnet_rq_get_buf(rq, &len, &ctx);
1851 		if (unlikely(!buf)) {
1852 			pr_debug("%s: rx error: %d buffers out of %d missing\n",
1853 				 dev->name, num_buf,
1854 				 virtio16_to_cpu(vi->vdev,
1855 						 hdr->num_buffers));
1856 			DEV_STATS_INC(dev, rx_length_errors);
1857 			goto err_buf;
1858 		}
1859 
1860 		u64_stats_add(&stats->bytes, len);
1861 		page = virt_to_head_page(buf);
1862 
1863 		truesize = mergeable_ctx_to_truesize(ctx);
1864 		headroom = mergeable_ctx_to_headroom(ctx);
1865 		tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1866 		room = SKB_DATA_ALIGN(headroom + tailroom);
1867 		if (unlikely(len > truesize - room)) {
1868 			pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1869 				 dev->name, len, (unsigned long)(truesize - room));
1870 			DEV_STATS_INC(dev, rx_length_errors);
1871 			goto err_skb;
1872 		}
1873 
1874 		num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1875 		if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1876 			struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1877 
1878 			if (unlikely(!nskb))
1879 				goto err_skb;
1880 			if (curr_skb == head_skb)
1881 				skb_shinfo(curr_skb)->frag_list = nskb;
1882 			else
1883 				curr_skb->next = nskb;
1884 			curr_skb = nskb;
1885 			head_skb->truesize += nskb->truesize;
1886 			num_skb_frags = 0;
1887 		}
1888 		if (curr_skb != head_skb) {
1889 			head_skb->data_len += len;
1890 			head_skb->len += len;
1891 			head_skb->truesize += truesize;
1892 		}
1893 		offset = buf - page_address(page);
1894 		if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1895 			put_page(page);
1896 			skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1897 					     len, truesize);
1898 		} else {
1899 			skb_add_rx_frag(curr_skb, num_skb_frags, page,
1900 					offset, len, truesize);
1901 		}
1902 	}
1903 
1904 	ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1905 	return head_skb;
1906 
1907 err_skb:
1908 	put_page(page);
1909 	mergeable_buf_free(rq, num_buf, dev, stats);
1910 
1911 err_buf:
1912 	u64_stats_inc(&stats->drops);
1913 	dev_kfree_skb(head_skb);
1914 	return NULL;
1915 }
1916 
1917 static void virtio_skb_set_hash(const struct virtio_net_hdr_v1_hash *hdr_hash,
1918 				struct sk_buff *skb)
1919 {
1920 	enum pkt_hash_types rss_hash_type;
1921 
1922 	if (!hdr_hash || !skb)
1923 		return;
1924 
1925 	switch (__le16_to_cpu(hdr_hash->hash_report)) {
1926 	case VIRTIO_NET_HASH_REPORT_TCPv4:
1927 	case VIRTIO_NET_HASH_REPORT_UDPv4:
1928 	case VIRTIO_NET_HASH_REPORT_TCPv6:
1929 	case VIRTIO_NET_HASH_REPORT_UDPv6:
1930 	case VIRTIO_NET_HASH_REPORT_TCPv6_EX:
1931 	case VIRTIO_NET_HASH_REPORT_UDPv6_EX:
1932 		rss_hash_type = PKT_HASH_TYPE_L4;
1933 		break;
1934 	case VIRTIO_NET_HASH_REPORT_IPv4:
1935 	case VIRTIO_NET_HASH_REPORT_IPv6:
1936 	case VIRTIO_NET_HASH_REPORT_IPv6_EX:
1937 		rss_hash_type = PKT_HASH_TYPE_L3;
1938 		break;
1939 	case VIRTIO_NET_HASH_REPORT_NONE:
1940 	default:
1941 		rss_hash_type = PKT_HASH_TYPE_NONE;
1942 	}
1943 	skb_set_hash(skb, __le32_to_cpu(hdr_hash->hash_value), rss_hash_type);
1944 }
1945 
1946 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1947 			void *buf, unsigned int len, void **ctx,
1948 			unsigned int *xdp_xmit,
1949 			struct virtnet_rq_stats *stats)
1950 {
1951 	struct net_device *dev = vi->dev;
1952 	struct sk_buff *skb;
1953 	struct virtio_net_common_hdr *hdr;
1954 	u8 flags;
1955 
1956 	if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1957 		pr_debug("%s: short packet %i\n", dev->name, len);
1958 		DEV_STATS_INC(dev, rx_length_errors);
1959 		virtnet_rq_free_buf(vi, rq, buf);
1960 		return;
1961 	}
1962 
1963 	/* 1. Save the flags early, as the XDP program might overwrite them.
1964 	 * These flags ensure packets marked as VIRTIO_NET_HDR_F_DATA_VALID
1965 	 * stay valid after XDP processing.
1966 	 * 2. XDP doesn't work with partially checksummed packets (refer to
1967 	 * virtnet_xdp_set()), so packets marked as
1968 	 * VIRTIO_NET_HDR_F_NEEDS_CSUM get dropped during XDP processing.
1969 	 */
1970 	flags = ((struct virtio_net_common_hdr *)buf)->hdr.flags;
1971 
1972 	if (vi->mergeable_rx_bufs)
1973 		skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1974 					stats);
1975 	else if (vi->big_packets)
1976 		skb = receive_big(dev, vi, rq, buf, len, stats);
1977 	else
1978 		skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1979 
1980 	if (unlikely(!skb))
1981 		return;
1982 
1983 	hdr = skb_vnet_common_hdr(skb);
1984 	if (dev->features & NETIF_F_RXHASH && vi->has_rss_hash_report)
1985 		virtio_skb_set_hash(&hdr->hash_v1_hdr, skb);
1986 
1987 	if (flags & VIRTIO_NET_HDR_F_DATA_VALID)
1988 		skb->ip_summed = CHECKSUM_UNNECESSARY;
1989 
1990 	if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1991 				  virtio_is_little_endian(vi->vdev))) {
1992 		net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1993 				     dev->name, hdr->hdr.gso_type,
1994 				     hdr->hdr.gso_size);
1995 		goto frame_err;
1996 	}
1997 
1998 	skb_record_rx_queue(skb, vq2rxq(rq->vq));
1999 	skb->protocol = eth_type_trans(skb, dev);
2000 	pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
2001 		 ntohs(skb->protocol), skb->len, skb->pkt_type);
2002 
2003 	napi_gro_receive(&rq->napi, skb);
2004 	return;
2005 
2006 frame_err:
2007 	DEV_STATS_INC(dev, rx_frame_errors);
2008 	dev_kfree_skb(skb);
2009 }
2010 
2011 /* Unlike mergeable buffers, all buffers are allocated to the
2012  * same size, except for the headroom. For this reason we do
2013  * not need to use  mergeable_len_to_ctx here - it is enough
2014  * to store the headroom as the context ignoring the truesize.
2015  */
2016 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
2017 			     gfp_t gfp)
2018 {
2019 	char *buf;
2020 	unsigned int xdp_headroom = virtnet_get_headroom(vi);
2021 	void *ctx = (void *)(unsigned long)xdp_headroom;
2022 	int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
2023 	int err;
2024 
2025 	len = SKB_DATA_ALIGN(len) +
2026 	      SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
2027 
2028 	buf = virtnet_rq_alloc(rq, len, gfp);
2029 	if (unlikely(!buf))
2030 		return -ENOMEM;
2031 
2032 	virtnet_rq_init_one_sg(rq, buf + VIRTNET_RX_PAD + xdp_headroom,
2033 			       vi->hdr_len + GOOD_PACKET_LEN);
2034 
2035 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
2036 	if (err < 0) {
2037 		virtnet_rq_unmap(rq, buf, 0);
2038 		put_page(virt_to_head_page(buf));
2039 	}
2040 
2041 	return err;
2042 }
2043 
2044 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
2045 			   gfp_t gfp)
2046 {
2047 	struct page *first, *list = NULL;
2048 	char *p;
2049 	int i, err, offset;
2050 
2051 	sg_init_table(rq->sg, vi->big_packets_num_skbfrags + 2);
2052 
2053 	/* page in rq->sg[vi->big_packets_num_skbfrags + 1] is list tail */
2054 	for (i = vi->big_packets_num_skbfrags + 1; i > 1; --i) {
2055 		first = get_a_page(rq, gfp);
2056 		if (!first) {
2057 			if (list)
2058 				give_pages(rq, list);
2059 			return -ENOMEM;
2060 		}
2061 		sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
2062 
2063 		/* chain new page in list head to match sg */
2064 		first->private = (unsigned long)list;
2065 		list = first;
2066 	}
2067 
2068 	first = get_a_page(rq, gfp);
2069 	if (!first) {
2070 		give_pages(rq, list);
2071 		return -ENOMEM;
2072 	}
2073 	p = page_address(first);
2074 
2075 	/* rq->sg[0], rq->sg[1] share the same page */
2076 	/* a separated rq->sg[0] for header - required in case !any_header_sg */
2077 	sg_set_buf(&rq->sg[0], p, vi->hdr_len);
2078 
2079 	/* rq->sg[1] for data packet, from offset */
2080 	offset = sizeof(struct padded_vnet_hdr);
2081 	sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
2082 
2083 	/* chain first in list head */
2084 	first->private = (unsigned long)list;
2085 	err = virtqueue_add_inbuf(rq->vq, rq->sg, vi->big_packets_num_skbfrags + 2,
2086 				  first, gfp);
2087 	if (err < 0)
2088 		give_pages(rq, first);
2089 
2090 	return err;
2091 }
2092 
2093 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
2094 					  struct ewma_pkt_len *avg_pkt_len,
2095 					  unsigned int room)
2096 {
2097 	struct virtnet_info *vi = rq->vq->vdev->priv;
2098 	const size_t hdr_len = vi->hdr_len;
2099 	unsigned int len;
2100 
2101 	if (room)
2102 		return PAGE_SIZE - room;
2103 
2104 	len = hdr_len +	clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
2105 				rq->min_buf_len, PAGE_SIZE - hdr_len);
2106 
2107 	return ALIGN(len, L1_CACHE_BYTES);
2108 }
2109 
2110 static int add_recvbuf_mergeable(struct virtnet_info *vi,
2111 				 struct receive_queue *rq, gfp_t gfp)
2112 {
2113 	struct page_frag *alloc_frag = &rq->alloc_frag;
2114 	unsigned int headroom = virtnet_get_headroom(vi);
2115 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
2116 	unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
2117 	unsigned int len, hole;
2118 	void *ctx;
2119 	char *buf;
2120 	int err;
2121 
2122 	/* Extra tailroom is needed to satisfy XDP's assumption. This
2123 	 * means rx frags coalescing won't work, but consider we've
2124 	 * disabled GSO for XDP, it won't be a big issue.
2125 	 */
2126 	len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
2127 
2128 	buf = virtnet_rq_alloc(rq, len + room, gfp);
2129 	if (unlikely(!buf))
2130 		return -ENOMEM;
2131 
2132 	buf += headroom; /* advance address leaving hole at front of pkt */
2133 	hole = alloc_frag->size - alloc_frag->offset;
2134 	if (hole < len + room) {
2135 		/* To avoid internal fragmentation, if there is very likely not
2136 		 * enough space for another buffer, add the remaining space to
2137 		 * the current buffer.
2138 		 * XDP core assumes that frame_size of xdp_buff and the length
2139 		 * of the frag are PAGE_SIZE, so we disable the hole mechanism.
2140 		 */
2141 		if (!headroom)
2142 			len += hole;
2143 		alloc_frag->offset += hole;
2144 	}
2145 
2146 	virtnet_rq_init_one_sg(rq, buf, len);
2147 
2148 	ctx = mergeable_len_to_ctx(len + room, headroom);
2149 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
2150 	if (err < 0) {
2151 		virtnet_rq_unmap(rq, buf, 0);
2152 		put_page(virt_to_head_page(buf));
2153 	}
2154 
2155 	return err;
2156 }
2157 
2158 /*
2159  * Returns false if we couldn't fill entirely (OOM).
2160  *
2161  * Normally run in the receive path, but can also be run from ndo_open
2162  * before we're receiving packets, or from refill_work which is
2163  * careful to disable receiving (using napi_disable).
2164  */
2165 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
2166 			  gfp_t gfp)
2167 {
2168 	int err;
2169 	bool oom;
2170 
2171 	do {
2172 		if (vi->mergeable_rx_bufs)
2173 			err = add_recvbuf_mergeable(vi, rq, gfp);
2174 		else if (vi->big_packets)
2175 			err = add_recvbuf_big(vi, rq, gfp);
2176 		else
2177 			err = add_recvbuf_small(vi, rq, gfp);
2178 
2179 		oom = err == -ENOMEM;
2180 		if (err)
2181 			break;
2182 	} while (rq->vq->num_free);
2183 	if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
2184 		unsigned long flags;
2185 
2186 		flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
2187 		u64_stats_inc(&rq->stats.kicks);
2188 		u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
2189 	}
2190 
2191 	return !oom;
2192 }
2193 
2194 static void skb_recv_done(struct virtqueue *rvq)
2195 {
2196 	struct virtnet_info *vi = rvq->vdev->priv;
2197 	struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
2198 
2199 	rq->calls++;
2200 	virtqueue_napi_schedule(&rq->napi, rvq);
2201 }
2202 
2203 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
2204 {
2205 	napi_enable(napi);
2206 
2207 	/* If all buffers were filled by other side before we napi_enabled, we
2208 	 * won't get another interrupt, so process any outstanding packets now.
2209 	 * Call local_bh_enable after to trigger softIRQ processing.
2210 	 */
2211 	local_bh_disable();
2212 	virtqueue_napi_schedule(napi, vq);
2213 	local_bh_enable();
2214 }
2215 
2216 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
2217 				   struct virtqueue *vq,
2218 				   struct napi_struct *napi)
2219 {
2220 	if (!napi->weight)
2221 		return;
2222 
2223 	/* Tx napi touches cachelines on the cpu handling tx interrupts. Only
2224 	 * enable the feature if this is likely affine with the transmit path.
2225 	 */
2226 	if (!vi->affinity_hint_set) {
2227 		napi->weight = 0;
2228 		return;
2229 	}
2230 
2231 	return virtnet_napi_enable(vq, napi);
2232 }
2233 
2234 static void virtnet_napi_tx_disable(struct napi_struct *napi)
2235 {
2236 	if (napi->weight)
2237 		napi_disable(napi);
2238 }
2239 
2240 static void refill_work(struct work_struct *work)
2241 {
2242 	struct virtnet_info *vi =
2243 		container_of(work, struct virtnet_info, refill.work);
2244 	bool still_empty;
2245 	int i;
2246 
2247 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2248 		struct receive_queue *rq = &vi->rq[i];
2249 
2250 		napi_disable(&rq->napi);
2251 		still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
2252 		virtnet_napi_enable(rq->vq, &rq->napi);
2253 
2254 		/* In theory, this can happen: if we don't get any buffers in
2255 		 * we will *never* try to fill again.
2256 		 */
2257 		if (still_empty)
2258 			schedule_delayed_work(&vi->refill, HZ/2);
2259 	}
2260 }
2261 
2262 static int virtnet_receive(struct receive_queue *rq, int budget,
2263 			   unsigned int *xdp_xmit)
2264 {
2265 	struct virtnet_info *vi = rq->vq->vdev->priv;
2266 	struct virtnet_rq_stats stats = {};
2267 	unsigned int len;
2268 	int packets = 0;
2269 	void *buf;
2270 	int i;
2271 
2272 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
2273 		void *ctx;
2274 
2275 		while (packets < budget &&
2276 		       (buf = virtnet_rq_get_buf(rq, &len, &ctx))) {
2277 			receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
2278 			packets++;
2279 		}
2280 	} else {
2281 		while (packets < budget &&
2282 		       (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
2283 			receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
2284 			packets++;
2285 		}
2286 	}
2287 
2288 	if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
2289 		if (!try_fill_recv(vi, rq, GFP_ATOMIC)) {
2290 			spin_lock(&vi->refill_lock);
2291 			if (vi->refill_enabled)
2292 				schedule_delayed_work(&vi->refill, 0);
2293 			spin_unlock(&vi->refill_lock);
2294 		}
2295 	}
2296 
2297 	u64_stats_set(&stats.packets, packets);
2298 	u64_stats_update_begin(&rq->stats.syncp);
2299 	for (i = 0; i < ARRAY_SIZE(virtnet_rq_stats_desc); i++) {
2300 		size_t offset = virtnet_rq_stats_desc[i].offset;
2301 		u64_stats_t *item, *src;
2302 
2303 		item = (u64_stats_t *)((u8 *)&rq->stats + offset);
2304 		src = (u64_stats_t *)((u8 *)&stats + offset);
2305 		u64_stats_add(item, u64_stats_read(src));
2306 	}
2307 
2308 	u64_stats_add(&rq->stats.packets, u64_stats_read(&stats.packets));
2309 	u64_stats_add(&rq->stats.bytes, u64_stats_read(&stats.bytes));
2310 
2311 	u64_stats_update_end(&rq->stats.syncp);
2312 
2313 	return packets;
2314 }
2315 
2316 static void virtnet_poll_cleantx(struct receive_queue *rq)
2317 {
2318 	struct virtnet_info *vi = rq->vq->vdev->priv;
2319 	unsigned int index = vq2rxq(rq->vq);
2320 	struct send_queue *sq = &vi->sq[index];
2321 	struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
2322 
2323 	if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
2324 		return;
2325 
2326 	if (__netif_tx_trylock(txq)) {
2327 		if (sq->reset) {
2328 			__netif_tx_unlock(txq);
2329 			return;
2330 		}
2331 
2332 		do {
2333 			virtqueue_disable_cb(sq->vq);
2334 			free_old_xmit(sq, true);
2335 		} while (unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
2336 
2337 		if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS) {
2338 			if (netif_tx_queue_stopped(txq)) {
2339 				u64_stats_update_begin(&sq->stats.syncp);
2340 				u64_stats_inc(&sq->stats.wake);
2341 				u64_stats_update_end(&sq->stats.syncp);
2342 			}
2343 			netif_tx_wake_queue(txq);
2344 		}
2345 
2346 		__netif_tx_unlock(txq);
2347 	}
2348 }
2349 
2350 static void virtnet_rx_dim_update(struct virtnet_info *vi, struct receive_queue *rq)
2351 {
2352 	struct dim_sample cur_sample = {};
2353 
2354 	if (!rq->packets_in_napi)
2355 		return;
2356 
2357 	u64_stats_update_begin(&rq->stats.syncp);
2358 	dim_update_sample(rq->calls,
2359 			  u64_stats_read(&rq->stats.packets),
2360 			  u64_stats_read(&rq->stats.bytes),
2361 			  &cur_sample);
2362 	u64_stats_update_end(&rq->stats.syncp);
2363 
2364 	net_dim(&rq->dim, cur_sample);
2365 	rq->packets_in_napi = 0;
2366 }
2367 
2368 static int virtnet_poll(struct napi_struct *napi, int budget)
2369 {
2370 	struct receive_queue *rq =
2371 		container_of(napi, struct receive_queue, napi);
2372 	struct virtnet_info *vi = rq->vq->vdev->priv;
2373 	struct send_queue *sq;
2374 	unsigned int received;
2375 	unsigned int xdp_xmit = 0;
2376 	bool napi_complete;
2377 
2378 	virtnet_poll_cleantx(rq);
2379 
2380 	received = virtnet_receive(rq, budget, &xdp_xmit);
2381 	rq->packets_in_napi += received;
2382 
2383 	if (xdp_xmit & VIRTIO_XDP_REDIR)
2384 		xdp_do_flush();
2385 
2386 	/* Out of packets? */
2387 	if (received < budget) {
2388 		napi_complete = virtqueue_napi_complete(napi, rq->vq, received);
2389 		/* Intentionally not taking dim_lock here. This may result in a
2390 		 * spurious net_dim call. But if that happens virtnet_rx_dim_work
2391 		 * will not act on the scheduled work.
2392 		 */
2393 		if (napi_complete && rq->dim_enabled)
2394 			virtnet_rx_dim_update(vi, rq);
2395 	}
2396 
2397 	if (xdp_xmit & VIRTIO_XDP_TX) {
2398 		sq = virtnet_xdp_get_sq(vi);
2399 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
2400 			u64_stats_update_begin(&sq->stats.syncp);
2401 			u64_stats_inc(&sq->stats.kicks);
2402 			u64_stats_update_end(&sq->stats.syncp);
2403 		}
2404 		virtnet_xdp_put_sq(vi, sq);
2405 	}
2406 
2407 	return received;
2408 }
2409 
2410 static void virtnet_disable_queue_pair(struct virtnet_info *vi, int qp_index)
2411 {
2412 	virtnet_napi_tx_disable(&vi->sq[qp_index].napi);
2413 	napi_disable(&vi->rq[qp_index].napi);
2414 	xdp_rxq_info_unreg(&vi->rq[qp_index].xdp_rxq);
2415 }
2416 
2417 static int virtnet_enable_queue_pair(struct virtnet_info *vi, int qp_index)
2418 {
2419 	struct net_device *dev = vi->dev;
2420 	int err;
2421 
2422 	err = xdp_rxq_info_reg(&vi->rq[qp_index].xdp_rxq, dev, qp_index,
2423 			       vi->rq[qp_index].napi.napi_id);
2424 	if (err < 0)
2425 		return err;
2426 
2427 	err = xdp_rxq_info_reg_mem_model(&vi->rq[qp_index].xdp_rxq,
2428 					 MEM_TYPE_PAGE_SHARED, NULL);
2429 	if (err < 0)
2430 		goto err_xdp_reg_mem_model;
2431 
2432 	virtnet_napi_enable(vi->rq[qp_index].vq, &vi->rq[qp_index].napi);
2433 	virtnet_napi_tx_enable(vi, vi->sq[qp_index].vq, &vi->sq[qp_index].napi);
2434 
2435 	return 0;
2436 
2437 err_xdp_reg_mem_model:
2438 	xdp_rxq_info_unreg(&vi->rq[qp_index].xdp_rxq);
2439 	return err;
2440 }
2441 
2442 static int virtnet_open(struct net_device *dev)
2443 {
2444 	struct virtnet_info *vi = netdev_priv(dev);
2445 	int i, err;
2446 
2447 	enable_delayed_refill(vi);
2448 
2449 	for (i = 0; i < vi->max_queue_pairs; i++) {
2450 		if (i < vi->curr_queue_pairs)
2451 			/* Make sure we have some buffers: if oom use wq. */
2452 			if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
2453 				schedule_delayed_work(&vi->refill, 0);
2454 
2455 		err = virtnet_enable_queue_pair(vi, i);
2456 		if (err < 0)
2457 			goto err_enable_qp;
2458 	}
2459 
2460 	return 0;
2461 
2462 err_enable_qp:
2463 	disable_delayed_refill(vi);
2464 	cancel_delayed_work_sync(&vi->refill);
2465 
2466 	for (i--; i >= 0; i--) {
2467 		virtnet_disable_queue_pair(vi, i);
2468 		cancel_work_sync(&vi->rq[i].dim.work);
2469 	}
2470 
2471 	return err;
2472 }
2473 
2474 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
2475 {
2476 	struct send_queue *sq = container_of(napi, struct send_queue, napi);
2477 	struct virtnet_info *vi = sq->vq->vdev->priv;
2478 	unsigned int index = vq2txq(sq->vq);
2479 	struct netdev_queue *txq;
2480 	int opaque;
2481 	bool done;
2482 
2483 	if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
2484 		/* We don't need to enable cb for XDP */
2485 		napi_complete_done(napi, 0);
2486 		return 0;
2487 	}
2488 
2489 	txq = netdev_get_tx_queue(vi->dev, index);
2490 	__netif_tx_lock(txq, raw_smp_processor_id());
2491 	virtqueue_disable_cb(sq->vq);
2492 	free_old_xmit(sq, true);
2493 
2494 	if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS) {
2495 		if (netif_tx_queue_stopped(txq)) {
2496 			u64_stats_update_begin(&sq->stats.syncp);
2497 			u64_stats_inc(&sq->stats.wake);
2498 			u64_stats_update_end(&sq->stats.syncp);
2499 		}
2500 		netif_tx_wake_queue(txq);
2501 	}
2502 
2503 	opaque = virtqueue_enable_cb_prepare(sq->vq);
2504 
2505 	done = napi_complete_done(napi, 0);
2506 
2507 	if (!done)
2508 		virtqueue_disable_cb(sq->vq);
2509 
2510 	__netif_tx_unlock(txq);
2511 
2512 	if (done) {
2513 		if (unlikely(virtqueue_poll(sq->vq, opaque))) {
2514 			if (napi_schedule_prep(napi)) {
2515 				__netif_tx_lock(txq, raw_smp_processor_id());
2516 				virtqueue_disable_cb(sq->vq);
2517 				__netif_tx_unlock(txq);
2518 				__napi_schedule(napi);
2519 			}
2520 		}
2521 	}
2522 
2523 	return 0;
2524 }
2525 
2526 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
2527 {
2528 	struct virtio_net_hdr_mrg_rxbuf *hdr;
2529 	const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
2530 	struct virtnet_info *vi = sq->vq->vdev->priv;
2531 	int num_sg;
2532 	unsigned hdr_len = vi->hdr_len;
2533 	bool can_push;
2534 
2535 	pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
2536 
2537 	can_push = vi->any_header_sg &&
2538 		!((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
2539 		!skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
2540 	/* Even if we can, don't push here yet as this would skew
2541 	 * csum_start offset below. */
2542 	if (can_push)
2543 		hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
2544 	else
2545 		hdr = &skb_vnet_common_hdr(skb)->mrg_hdr;
2546 
2547 	if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
2548 				    virtio_is_little_endian(vi->vdev), false,
2549 				    0))
2550 		return -EPROTO;
2551 
2552 	if (vi->mergeable_rx_bufs)
2553 		hdr->num_buffers = 0;
2554 
2555 	sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
2556 	if (can_push) {
2557 		__skb_push(skb, hdr_len);
2558 		num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
2559 		if (unlikely(num_sg < 0))
2560 			return num_sg;
2561 		/* Pull header back to avoid skew in tx bytes calculations. */
2562 		__skb_pull(skb, hdr_len);
2563 	} else {
2564 		sg_set_buf(sq->sg, hdr, hdr_len);
2565 		num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
2566 		if (unlikely(num_sg < 0))
2567 			return num_sg;
2568 		num_sg++;
2569 	}
2570 	return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
2571 }
2572 
2573 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
2574 {
2575 	struct virtnet_info *vi = netdev_priv(dev);
2576 	int qnum = skb_get_queue_mapping(skb);
2577 	struct send_queue *sq = &vi->sq[qnum];
2578 	int err;
2579 	struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
2580 	bool kick = !netdev_xmit_more();
2581 	bool use_napi = sq->napi.weight;
2582 
2583 	/* Free up any pending old buffers before queueing new ones. */
2584 	do {
2585 		if (use_napi)
2586 			virtqueue_disable_cb(sq->vq);
2587 
2588 		free_old_xmit(sq, false);
2589 
2590 	} while (use_napi && kick &&
2591 	       unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
2592 
2593 	/* timestamp packet in software */
2594 	skb_tx_timestamp(skb);
2595 
2596 	/* Try to transmit */
2597 	err = xmit_skb(sq, skb);
2598 
2599 	/* This should not happen! */
2600 	if (unlikely(err)) {
2601 		DEV_STATS_INC(dev, tx_fifo_errors);
2602 		if (net_ratelimit())
2603 			dev_warn(&dev->dev,
2604 				 "Unexpected TXQ (%d) queue failure: %d\n",
2605 				 qnum, err);
2606 		DEV_STATS_INC(dev, tx_dropped);
2607 		dev_kfree_skb_any(skb);
2608 		return NETDEV_TX_OK;
2609 	}
2610 
2611 	/* Don't wait up for transmitted skbs to be freed. */
2612 	if (!use_napi) {
2613 		skb_orphan(skb);
2614 		nf_reset_ct(skb);
2615 	}
2616 
2617 	check_sq_full_and_disable(vi, dev, sq);
2618 
2619 	if (kick || netif_xmit_stopped(txq)) {
2620 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
2621 			u64_stats_update_begin(&sq->stats.syncp);
2622 			u64_stats_inc(&sq->stats.kicks);
2623 			u64_stats_update_end(&sq->stats.syncp);
2624 		}
2625 	}
2626 
2627 	return NETDEV_TX_OK;
2628 }
2629 
2630 static int virtnet_rx_resize(struct virtnet_info *vi,
2631 			     struct receive_queue *rq, u32 ring_num)
2632 {
2633 	bool running = netif_running(vi->dev);
2634 	int err, qindex;
2635 
2636 	qindex = rq - vi->rq;
2637 
2638 	if (running) {
2639 		napi_disable(&rq->napi);
2640 		cancel_work_sync(&rq->dim.work);
2641 	}
2642 
2643 	err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_unmap_free_buf);
2644 	if (err)
2645 		netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
2646 
2647 	if (!try_fill_recv(vi, rq, GFP_KERNEL))
2648 		schedule_delayed_work(&vi->refill, 0);
2649 
2650 	if (running)
2651 		virtnet_napi_enable(rq->vq, &rq->napi);
2652 	return err;
2653 }
2654 
2655 static int virtnet_tx_resize(struct virtnet_info *vi,
2656 			     struct send_queue *sq, u32 ring_num)
2657 {
2658 	bool running = netif_running(vi->dev);
2659 	struct netdev_queue *txq;
2660 	int err, qindex;
2661 
2662 	qindex = sq - vi->sq;
2663 
2664 	if (running)
2665 		virtnet_napi_tx_disable(&sq->napi);
2666 
2667 	txq = netdev_get_tx_queue(vi->dev, qindex);
2668 
2669 	/* 1. wait all ximt complete
2670 	 * 2. fix the race of netif_stop_subqueue() vs netif_start_subqueue()
2671 	 */
2672 	__netif_tx_lock_bh(txq);
2673 
2674 	/* Prevent rx poll from accessing sq. */
2675 	sq->reset = true;
2676 
2677 	/* Prevent the upper layer from trying to send packets. */
2678 	netif_stop_subqueue(vi->dev, qindex);
2679 
2680 	__netif_tx_unlock_bh(txq);
2681 
2682 	err = virtqueue_resize(sq->vq, ring_num, virtnet_sq_free_unused_buf);
2683 	if (err)
2684 		netdev_err(vi->dev, "resize tx fail: tx queue index: %d err: %d\n", qindex, err);
2685 
2686 	__netif_tx_lock_bh(txq);
2687 	sq->reset = false;
2688 	netif_tx_wake_queue(txq);
2689 	__netif_tx_unlock_bh(txq);
2690 
2691 	if (running)
2692 		virtnet_napi_tx_enable(vi, sq->vq, &sq->napi);
2693 	return err;
2694 }
2695 
2696 /*
2697  * Send command via the control virtqueue and check status.  Commands
2698  * supported by the hypervisor, as indicated by feature bits, should
2699  * never fail unless improperly formatted.
2700  */
2701 static bool virtnet_send_command_reply(struct virtnet_info *vi, u8 class, u8 cmd,
2702 				       struct scatterlist *out,
2703 				       struct scatterlist *in)
2704 {
2705 	struct scatterlist *sgs[5], hdr, stat;
2706 	u32 out_num = 0, tmp, in_num = 0;
2707 	bool ok;
2708 	int ret;
2709 
2710 	/* Caller should know better */
2711 	BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
2712 
2713 	mutex_lock(&vi->cvq_lock);
2714 	vi->ctrl->status = ~0;
2715 	vi->ctrl->hdr.class = class;
2716 	vi->ctrl->hdr.cmd = cmd;
2717 	/* Add header */
2718 	sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
2719 	sgs[out_num++] = &hdr;
2720 
2721 	if (out)
2722 		sgs[out_num++] = out;
2723 
2724 	/* Add return status. */
2725 	sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
2726 	sgs[out_num + in_num++] = &stat;
2727 
2728 	if (in)
2729 		sgs[out_num + in_num++] = in;
2730 
2731 	BUG_ON(out_num + in_num > ARRAY_SIZE(sgs));
2732 	ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, in_num, vi, GFP_ATOMIC);
2733 	if (ret < 0) {
2734 		dev_warn(&vi->vdev->dev,
2735 			 "Failed to add sgs for command vq: %d\n.", ret);
2736 		mutex_unlock(&vi->cvq_lock);
2737 		return false;
2738 	}
2739 
2740 	if (unlikely(!virtqueue_kick(vi->cvq)))
2741 		goto unlock;
2742 
2743 	/* Spin for a response, the kick causes an ioport write, trapping
2744 	 * into the hypervisor, so the request should be handled immediately.
2745 	 */
2746 	while (!virtqueue_get_buf(vi->cvq, &tmp) &&
2747 	       !virtqueue_is_broken(vi->cvq)) {
2748 		cond_resched();
2749 		cpu_relax();
2750 	}
2751 
2752 unlock:
2753 	ok = vi->ctrl->status == VIRTIO_NET_OK;
2754 	mutex_unlock(&vi->cvq_lock);
2755 	return ok;
2756 }
2757 
2758 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
2759 				 struct scatterlist *out)
2760 {
2761 	return virtnet_send_command_reply(vi, class, cmd, out, NULL);
2762 }
2763 
2764 static int virtnet_set_mac_address(struct net_device *dev, void *p)
2765 {
2766 	struct virtnet_info *vi = netdev_priv(dev);
2767 	struct virtio_device *vdev = vi->vdev;
2768 	int ret;
2769 	struct sockaddr *addr;
2770 	struct scatterlist sg;
2771 
2772 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2773 		return -EOPNOTSUPP;
2774 
2775 	addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
2776 	if (!addr)
2777 		return -ENOMEM;
2778 
2779 	ret = eth_prepare_mac_addr_change(dev, addr);
2780 	if (ret)
2781 		goto out;
2782 
2783 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
2784 		sg_init_one(&sg, addr->sa_data, dev->addr_len);
2785 		if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2786 					  VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
2787 			dev_warn(&vdev->dev,
2788 				 "Failed to set mac address by vq command.\n");
2789 			ret = -EINVAL;
2790 			goto out;
2791 		}
2792 	} else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
2793 		   !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2794 		unsigned int i;
2795 
2796 		/* Naturally, this has an atomicity problem. */
2797 		for (i = 0; i < dev->addr_len; i++)
2798 			virtio_cwrite8(vdev,
2799 				       offsetof(struct virtio_net_config, mac) +
2800 				       i, addr->sa_data[i]);
2801 	}
2802 
2803 	eth_commit_mac_addr_change(dev, p);
2804 	ret = 0;
2805 
2806 out:
2807 	kfree(addr);
2808 	return ret;
2809 }
2810 
2811 static void virtnet_stats(struct net_device *dev,
2812 			  struct rtnl_link_stats64 *tot)
2813 {
2814 	struct virtnet_info *vi = netdev_priv(dev);
2815 	unsigned int start;
2816 	int i;
2817 
2818 	for (i = 0; i < vi->max_queue_pairs; i++) {
2819 		u64 tpackets, tbytes, terrors, rpackets, rbytes, rdrops;
2820 		struct receive_queue *rq = &vi->rq[i];
2821 		struct send_queue *sq = &vi->sq[i];
2822 
2823 		do {
2824 			start = u64_stats_fetch_begin(&sq->stats.syncp);
2825 			tpackets = u64_stats_read(&sq->stats.packets);
2826 			tbytes   = u64_stats_read(&sq->stats.bytes);
2827 			terrors  = u64_stats_read(&sq->stats.tx_timeouts);
2828 		} while (u64_stats_fetch_retry(&sq->stats.syncp, start));
2829 
2830 		do {
2831 			start = u64_stats_fetch_begin(&rq->stats.syncp);
2832 			rpackets = u64_stats_read(&rq->stats.packets);
2833 			rbytes   = u64_stats_read(&rq->stats.bytes);
2834 			rdrops   = u64_stats_read(&rq->stats.drops);
2835 		} while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2836 
2837 		tot->rx_packets += rpackets;
2838 		tot->tx_packets += tpackets;
2839 		tot->rx_bytes   += rbytes;
2840 		tot->tx_bytes   += tbytes;
2841 		tot->rx_dropped += rdrops;
2842 		tot->tx_errors  += terrors;
2843 	}
2844 
2845 	tot->tx_dropped = DEV_STATS_READ(dev, tx_dropped);
2846 	tot->tx_fifo_errors = DEV_STATS_READ(dev, tx_fifo_errors);
2847 	tot->rx_length_errors = DEV_STATS_READ(dev, rx_length_errors);
2848 	tot->rx_frame_errors = DEV_STATS_READ(dev, rx_frame_errors);
2849 }
2850 
2851 static void virtnet_ack_link_announce(struct virtnet_info *vi)
2852 {
2853 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
2854 				  VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
2855 		dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
2856 }
2857 
2858 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2859 {
2860 	struct virtio_net_ctrl_mq *mq __free(kfree) = NULL;
2861 	struct scatterlist sg;
2862 	struct net_device *dev = vi->dev;
2863 
2864 	if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
2865 		return 0;
2866 
2867 	mq = kzalloc(sizeof(*mq), GFP_KERNEL);
2868 	if (!mq)
2869 		return -ENOMEM;
2870 
2871 	mq->virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
2872 	sg_init_one(&sg, mq, sizeof(*mq));
2873 
2874 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2875 				  VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
2876 		dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
2877 			 queue_pairs);
2878 		return -EINVAL;
2879 	} else {
2880 		vi->curr_queue_pairs = queue_pairs;
2881 		/* virtnet_open() will refill when device is going to up. */
2882 		if (dev->flags & IFF_UP)
2883 			schedule_delayed_work(&vi->refill, 0);
2884 	}
2885 
2886 	return 0;
2887 }
2888 
2889 static int virtnet_close(struct net_device *dev)
2890 {
2891 	struct virtnet_info *vi = netdev_priv(dev);
2892 	int i;
2893 
2894 	/* Make sure NAPI doesn't schedule refill work */
2895 	disable_delayed_refill(vi);
2896 	/* Make sure refill_work doesn't re-enable napi! */
2897 	cancel_delayed_work_sync(&vi->refill);
2898 
2899 	for (i = 0; i < vi->max_queue_pairs; i++) {
2900 		virtnet_disable_queue_pair(vi, i);
2901 		cancel_work_sync(&vi->rq[i].dim.work);
2902 	}
2903 
2904 	return 0;
2905 }
2906 
2907 static void virtnet_rx_mode_work(struct work_struct *work)
2908 {
2909 	struct virtnet_info *vi =
2910 		container_of(work, struct virtnet_info, rx_mode_work);
2911 	u8 *promisc_allmulti  __free(kfree) = NULL;
2912 	struct net_device *dev = vi->dev;
2913 	struct scatterlist sg[2];
2914 	struct virtio_net_ctrl_mac *mac_data;
2915 	struct netdev_hw_addr *ha;
2916 	int uc_count;
2917 	int mc_count;
2918 	void *buf;
2919 	int i;
2920 
2921 	/* We can't dynamically set ndo_set_rx_mode, so return gracefully */
2922 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
2923 		return;
2924 
2925 	promisc_allmulti = kzalloc(sizeof(*promisc_allmulti), GFP_KERNEL);
2926 	if (!promisc_allmulti) {
2927 		dev_warn(&dev->dev, "Failed to set RX mode, no memory.\n");
2928 		return;
2929 	}
2930 
2931 	rtnl_lock();
2932 
2933 	*promisc_allmulti = !!(dev->flags & IFF_PROMISC);
2934 	sg_init_one(sg, promisc_allmulti, sizeof(*promisc_allmulti));
2935 
2936 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2937 				  VIRTIO_NET_CTRL_RX_PROMISC, sg))
2938 		dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
2939 			 *promisc_allmulti ? "en" : "dis");
2940 
2941 	*promisc_allmulti = !!(dev->flags & IFF_ALLMULTI);
2942 	sg_init_one(sg, promisc_allmulti, sizeof(*promisc_allmulti));
2943 
2944 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2945 				  VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
2946 		dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
2947 			 *promisc_allmulti ? "en" : "dis");
2948 
2949 	netif_addr_lock_bh(dev);
2950 
2951 	uc_count = netdev_uc_count(dev);
2952 	mc_count = netdev_mc_count(dev);
2953 	/* MAC filter - use one buffer for both lists */
2954 	buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
2955 		      (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
2956 	mac_data = buf;
2957 	if (!buf) {
2958 		netif_addr_unlock_bh(dev);
2959 		rtnl_unlock();
2960 		return;
2961 	}
2962 
2963 	sg_init_table(sg, 2);
2964 
2965 	/* Store the unicast list and count in the front of the buffer */
2966 	mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2967 	i = 0;
2968 	netdev_for_each_uc_addr(ha, dev)
2969 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2970 
2971 	sg_set_buf(&sg[0], mac_data,
2972 		   sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2973 
2974 	/* multicast list and count fill the end */
2975 	mac_data = (void *)&mac_data->macs[uc_count][0];
2976 
2977 	mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2978 	i = 0;
2979 	netdev_for_each_mc_addr(ha, dev)
2980 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2981 
2982 	netif_addr_unlock_bh(dev);
2983 
2984 	sg_set_buf(&sg[1], mac_data,
2985 		   sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2986 
2987 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2988 				  VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2989 		dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2990 
2991 	rtnl_unlock();
2992 
2993 	kfree(buf);
2994 }
2995 
2996 static void virtnet_set_rx_mode(struct net_device *dev)
2997 {
2998 	struct virtnet_info *vi = netdev_priv(dev);
2999 
3000 	if (vi->rx_mode_work_enabled)
3001 		schedule_work(&vi->rx_mode_work);
3002 }
3003 
3004 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
3005 				   __be16 proto, u16 vid)
3006 {
3007 	struct virtnet_info *vi = netdev_priv(dev);
3008 	__virtio16 *_vid __free(kfree) = NULL;
3009 	struct scatterlist sg;
3010 
3011 	_vid = kzalloc(sizeof(*_vid), GFP_KERNEL);
3012 	if (!_vid)
3013 		return -ENOMEM;
3014 
3015 	*_vid = cpu_to_virtio16(vi->vdev, vid);
3016 	sg_init_one(&sg, _vid, sizeof(*_vid));
3017 
3018 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
3019 				  VIRTIO_NET_CTRL_VLAN_ADD, &sg))
3020 		dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
3021 	return 0;
3022 }
3023 
3024 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
3025 				    __be16 proto, u16 vid)
3026 {
3027 	struct virtnet_info *vi = netdev_priv(dev);
3028 	__virtio16 *_vid __free(kfree) = NULL;
3029 	struct scatterlist sg;
3030 
3031 	_vid = kzalloc(sizeof(*_vid), GFP_KERNEL);
3032 	if (!_vid)
3033 		return -ENOMEM;
3034 
3035 	*_vid = cpu_to_virtio16(vi->vdev, vid);
3036 	sg_init_one(&sg, _vid, sizeof(*_vid));
3037 
3038 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
3039 				  VIRTIO_NET_CTRL_VLAN_DEL, &sg))
3040 		dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
3041 	return 0;
3042 }
3043 
3044 static void virtnet_clean_affinity(struct virtnet_info *vi)
3045 {
3046 	int i;
3047 
3048 	if (vi->affinity_hint_set) {
3049 		for (i = 0; i < vi->max_queue_pairs; i++) {
3050 			virtqueue_set_affinity(vi->rq[i].vq, NULL);
3051 			virtqueue_set_affinity(vi->sq[i].vq, NULL);
3052 		}
3053 
3054 		vi->affinity_hint_set = false;
3055 	}
3056 }
3057 
3058 static void virtnet_set_affinity(struct virtnet_info *vi)
3059 {
3060 	cpumask_var_t mask;
3061 	int stragglers;
3062 	int group_size;
3063 	int i, j, cpu;
3064 	int num_cpu;
3065 	int stride;
3066 
3067 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
3068 		virtnet_clean_affinity(vi);
3069 		return;
3070 	}
3071 
3072 	num_cpu = num_online_cpus();
3073 	stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
3074 	stragglers = num_cpu >= vi->curr_queue_pairs ?
3075 			num_cpu % vi->curr_queue_pairs :
3076 			0;
3077 	cpu = cpumask_first(cpu_online_mask);
3078 
3079 	for (i = 0; i < vi->curr_queue_pairs; i++) {
3080 		group_size = stride + (i < stragglers ? 1 : 0);
3081 
3082 		for (j = 0; j < group_size; j++) {
3083 			cpumask_set_cpu(cpu, mask);
3084 			cpu = cpumask_next_wrap(cpu, cpu_online_mask,
3085 						nr_cpu_ids, false);
3086 		}
3087 		virtqueue_set_affinity(vi->rq[i].vq, mask);
3088 		virtqueue_set_affinity(vi->sq[i].vq, mask);
3089 		__netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
3090 		cpumask_clear(mask);
3091 	}
3092 
3093 	vi->affinity_hint_set = true;
3094 	free_cpumask_var(mask);
3095 }
3096 
3097 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
3098 {
3099 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
3100 						   node);
3101 	virtnet_set_affinity(vi);
3102 	return 0;
3103 }
3104 
3105 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
3106 {
3107 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
3108 						   node_dead);
3109 	virtnet_set_affinity(vi);
3110 	return 0;
3111 }
3112 
3113 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
3114 {
3115 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
3116 						   node);
3117 
3118 	virtnet_clean_affinity(vi);
3119 	return 0;
3120 }
3121 
3122 static enum cpuhp_state virtionet_online;
3123 
3124 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
3125 {
3126 	int ret;
3127 
3128 	ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
3129 	if (ret)
3130 		return ret;
3131 	ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
3132 					       &vi->node_dead);
3133 	if (!ret)
3134 		return ret;
3135 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
3136 	return ret;
3137 }
3138 
3139 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
3140 {
3141 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
3142 	cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
3143 					    &vi->node_dead);
3144 }
3145 
3146 static int virtnet_send_ctrl_coal_vq_cmd(struct virtnet_info *vi,
3147 					 u16 vqn, u32 max_usecs, u32 max_packets)
3148 {
3149 	struct virtio_net_ctrl_coal_vq *coal_vq __free(kfree) = NULL;
3150 	struct scatterlist sgs;
3151 
3152 	coal_vq = kzalloc(sizeof(*coal_vq), GFP_KERNEL);
3153 	if (!coal_vq)
3154 		return -ENOMEM;
3155 
3156 	coal_vq->vqn = cpu_to_le16(vqn);
3157 	coal_vq->coal.max_usecs = cpu_to_le32(max_usecs);
3158 	coal_vq->coal.max_packets = cpu_to_le32(max_packets);
3159 	sg_init_one(&sgs, coal_vq, sizeof(*coal_vq));
3160 
3161 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
3162 				  VIRTIO_NET_CTRL_NOTF_COAL_VQ_SET,
3163 				  &sgs))
3164 		return -EINVAL;
3165 
3166 	return 0;
3167 }
3168 
3169 static int virtnet_send_rx_ctrl_coal_vq_cmd(struct virtnet_info *vi,
3170 					    u16 queue, u32 max_usecs,
3171 					    u32 max_packets)
3172 {
3173 	int err;
3174 
3175 	err = virtnet_send_ctrl_coal_vq_cmd(vi, rxq2vq(queue),
3176 					    max_usecs, max_packets);
3177 	if (err)
3178 		return err;
3179 
3180 	vi->rq[queue].intr_coal.max_usecs = max_usecs;
3181 	vi->rq[queue].intr_coal.max_packets = max_packets;
3182 
3183 	return 0;
3184 }
3185 
3186 static int virtnet_send_tx_ctrl_coal_vq_cmd(struct virtnet_info *vi,
3187 					    u16 queue, u32 max_usecs,
3188 					    u32 max_packets)
3189 {
3190 	int err;
3191 
3192 	err = virtnet_send_ctrl_coal_vq_cmd(vi, txq2vq(queue),
3193 					    max_usecs, max_packets);
3194 	if (err)
3195 		return err;
3196 
3197 	vi->sq[queue].intr_coal.max_usecs = max_usecs;
3198 	vi->sq[queue].intr_coal.max_packets = max_packets;
3199 
3200 	return 0;
3201 }
3202 
3203 static void virtnet_get_ringparam(struct net_device *dev,
3204 				  struct ethtool_ringparam *ring,
3205 				  struct kernel_ethtool_ringparam *kernel_ring,
3206 				  struct netlink_ext_ack *extack)
3207 {
3208 	struct virtnet_info *vi = netdev_priv(dev);
3209 
3210 	ring->rx_max_pending = vi->rq[0].vq->num_max;
3211 	ring->tx_max_pending = vi->sq[0].vq->num_max;
3212 	ring->rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
3213 	ring->tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
3214 }
3215 
3216 static int virtnet_set_ringparam(struct net_device *dev,
3217 				 struct ethtool_ringparam *ring,
3218 				 struct kernel_ethtool_ringparam *kernel_ring,
3219 				 struct netlink_ext_ack *extack)
3220 {
3221 	struct virtnet_info *vi = netdev_priv(dev);
3222 	u32 rx_pending, tx_pending;
3223 	struct receive_queue *rq;
3224 	struct send_queue *sq;
3225 	int i, err;
3226 
3227 	if (ring->rx_mini_pending || ring->rx_jumbo_pending)
3228 		return -EINVAL;
3229 
3230 	rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
3231 	tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
3232 
3233 	if (ring->rx_pending == rx_pending &&
3234 	    ring->tx_pending == tx_pending)
3235 		return 0;
3236 
3237 	if (ring->rx_pending > vi->rq[0].vq->num_max)
3238 		return -EINVAL;
3239 
3240 	if (ring->tx_pending > vi->sq[0].vq->num_max)
3241 		return -EINVAL;
3242 
3243 	for (i = 0; i < vi->max_queue_pairs; i++) {
3244 		rq = vi->rq + i;
3245 		sq = vi->sq + i;
3246 
3247 		if (ring->tx_pending != tx_pending) {
3248 			err = virtnet_tx_resize(vi, sq, ring->tx_pending);
3249 			if (err)
3250 				return err;
3251 
3252 			/* Upon disabling and re-enabling a transmit virtqueue, the device must
3253 			 * set the coalescing parameters of the virtqueue to those configured
3254 			 * through the VIRTIO_NET_CTRL_NOTF_COAL_TX_SET command, or, if the driver
3255 			 * did not set any TX coalescing parameters, to 0.
3256 			 */
3257 			err = virtnet_send_tx_ctrl_coal_vq_cmd(vi, i,
3258 							       vi->intr_coal_tx.max_usecs,
3259 							       vi->intr_coal_tx.max_packets);
3260 			if (err)
3261 				return err;
3262 		}
3263 
3264 		if (ring->rx_pending != rx_pending) {
3265 			err = virtnet_rx_resize(vi, rq, ring->rx_pending);
3266 			if (err)
3267 				return err;
3268 
3269 			/* The reason is same as the transmit virtqueue reset */
3270 			mutex_lock(&vi->rq[i].dim_lock);
3271 			err = virtnet_send_rx_ctrl_coal_vq_cmd(vi, i,
3272 							       vi->intr_coal_rx.max_usecs,
3273 							       vi->intr_coal_rx.max_packets);
3274 			mutex_unlock(&vi->rq[i].dim_lock);
3275 			if (err)
3276 				return err;
3277 		}
3278 	}
3279 
3280 	return 0;
3281 }
3282 
3283 static bool virtnet_commit_rss_command(struct virtnet_info *vi)
3284 {
3285 	struct net_device *dev = vi->dev;
3286 	struct scatterlist sgs[4];
3287 	unsigned int sg_buf_size;
3288 
3289 	/* prepare sgs */
3290 	sg_init_table(sgs, 4);
3291 
3292 	sg_buf_size = offsetof(struct virtio_net_ctrl_rss, indirection_table);
3293 	sg_set_buf(&sgs[0], &vi->rss, sg_buf_size);
3294 
3295 	sg_buf_size = sizeof(uint16_t) * (vi->rss.indirection_table_mask + 1);
3296 	sg_set_buf(&sgs[1], vi->rss.indirection_table, sg_buf_size);
3297 
3298 	sg_buf_size = offsetof(struct virtio_net_ctrl_rss, key)
3299 			- offsetof(struct virtio_net_ctrl_rss, max_tx_vq);
3300 	sg_set_buf(&sgs[2], &vi->rss.max_tx_vq, sg_buf_size);
3301 
3302 	sg_buf_size = vi->rss_key_size;
3303 	sg_set_buf(&sgs[3], vi->rss.key, sg_buf_size);
3304 
3305 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
3306 				  vi->has_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG
3307 				  : VIRTIO_NET_CTRL_MQ_HASH_CONFIG, sgs))
3308 		goto err;
3309 
3310 	return true;
3311 
3312 err:
3313 	dev_warn(&dev->dev, "VIRTIONET issue with committing RSS sgs\n");
3314 	return false;
3315 
3316 }
3317 
3318 static void virtnet_init_default_rss(struct virtnet_info *vi)
3319 {
3320 	u32 indir_val = 0;
3321 	int i = 0;
3322 
3323 	vi->rss.hash_types = vi->rss_hash_types_supported;
3324 	vi->rss_hash_types_saved = vi->rss_hash_types_supported;
3325 	vi->rss.indirection_table_mask = vi->rss_indir_table_size
3326 						? vi->rss_indir_table_size - 1 : 0;
3327 	vi->rss.unclassified_queue = 0;
3328 
3329 	for (; i < vi->rss_indir_table_size; ++i) {
3330 		indir_val = ethtool_rxfh_indir_default(i, vi->curr_queue_pairs);
3331 		vi->rss.indirection_table[i] = indir_val;
3332 	}
3333 
3334 	vi->rss.max_tx_vq = vi->has_rss ? vi->curr_queue_pairs : 0;
3335 	vi->rss.hash_key_length = vi->rss_key_size;
3336 
3337 	netdev_rss_key_fill(vi->rss.key, vi->rss_key_size);
3338 }
3339 
3340 static void virtnet_get_hashflow(const struct virtnet_info *vi, struct ethtool_rxnfc *info)
3341 {
3342 	info->data = 0;
3343 	switch (info->flow_type) {
3344 	case TCP_V4_FLOW:
3345 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
3346 			info->data = RXH_IP_SRC | RXH_IP_DST |
3347 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
3348 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
3349 			info->data = RXH_IP_SRC | RXH_IP_DST;
3350 		}
3351 		break;
3352 	case TCP_V6_FLOW:
3353 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
3354 			info->data = RXH_IP_SRC | RXH_IP_DST |
3355 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
3356 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
3357 			info->data = RXH_IP_SRC | RXH_IP_DST;
3358 		}
3359 		break;
3360 	case UDP_V4_FLOW:
3361 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
3362 			info->data = RXH_IP_SRC | RXH_IP_DST |
3363 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
3364 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
3365 			info->data = RXH_IP_SRC | RXH_IP_DST;
3366 		}
3367 		break;
3368 	case UDP_V6_FLOW:
3369 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
3370 			info->data = RXH_IP_SRC | RXH_IP_DST |
3371 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
3372 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
3373 			info->data = RXH_IP_SRC | RXH_IP_DST;
3374 		}
3375 		break;
3376 	case IPV4_FLOW:
3377 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4)
3378 			info->data = RXH_IP_SRC | RXH_IP_DST;
3379 
3380 		break;
3381 	case IPV6_FLOW:
3382 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6)
3383 			info->data = RXH_IP_SRC | RXH_IP_DST;
3384 
3385 		break;
3386 	default:
3387 		info->data = 0;
3388 		break;
3389 	}
3390 }
3391 
3392 static bool virtnet_set_hashflow(struct virtnet_info *vi, struct ethtool_rxnfc *info)
3393 {
3394 	u32 new_hashtypes = vi->rss_hash_types_saved;
3395 	bool is_disable = info->data & RXH_DISCARD;
3396 	bool is_l4 = info->data == (RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3);
3397 
3398 	/* supports only 'sd', 'sdfn' and 'r' */
3399 	if (!((info->data == (RXH_IP_SRC | RXH_IP_DST)) | is_l4 | is_disable))
3400 		return false;
3401 
3402 	switch (info->flow_type) {
3403 	case TCP_V4_FLOW:
3404 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_TCPv4);
3405 		if (!is_disable)
3406 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
3407 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0);
3408 		break;
3409 	case UDP_V4_FLOW:
3410 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_UDPv4);
3411 		if (!is_disable)
3412 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
3413 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0);
3414 		break;
3415 	case IPV4_FLOW:
3416 		new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv4;
3417 		if (!is_disable)
3418 			new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv4;
3419 		break;
3420 	case TCP_V6_FLOW:
3421 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_TCPv6);
3422 		if (!is_disable)
3423 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
3424 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0);
3425 		break;
3426 	case UDP_V6_FLOW:
3427 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_UDPv6);
3428 		if (!is_disable)
3429 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
3430 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0);
3431 		break;
3432 	case IPV6_FLOW:
3433 		new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv6;
3434 		if (!is_disable)
3435 			new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv6;
3436 		break;
3437 	default:
3438 		/* unsupported flow */
3439 		return false;
3440 	}
3441 
3442 	/* if unsupported hashtype was set */
3443 	if (new_hashtypes != (new_hashtypes & vi->rss_hash_types_supported))
3444 		return false;
3445 
3446 	if (new_hashtypes != vi->rss_hash_types_saved) {
3447 		vi->rss_hash_types_saved = new_hashtypes;
3448 		vi->rss.hash_types = vi->rss_hash_types_saved;
3449 		if (vi->dev->features & NETIF_F_RXHASH)
3450 			return virtnet_commit_rss_command(vi);
3451 	}
3452 
3453 	return true;
3454 }
3455 
3456 static void virtnet_get_drvinfo(struct net_device *dev,
3457 				struct ethtool_drvinfo *info)
3458 {
3459 	struct virtnet_info *vi = netdev_priv(dev);
3460 	struct virtio_device *vdev = vi->vdev;
3461 
3462 	strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
3463 	strscpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
3464 	strscpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
3465 
3466 }
3467 
3468 /* TODO: Eliminate OOO packets during switching */
3469 static int virtnet_set_channels(struct net_device *dev,
3470 				struct ethtool_channels *channels)
3471 {
3472 	struct virtnet_info *vi = netdev_priv(dev);
3473 	u16 queue_pairs = channels->combined_count;
3474 	int err;
3475 
3476 	/* We don't support separate rx/tx channels.
3477 	 * We don't allow setting 'other' channels.
3478 	 */
3479 	if (channels->rx_count || channels->tx_count || channels->other_count)
3480 		return -EINVAL;
3481 
3482 	if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
3483 		return -EINVAL;
3484 
3485 	/* For now we don't support modifying channels while XDP is loaded
3486 	 * also when XDP is loaded all RX queues have XDP programs so we only
3487 	 * need to check a single RX queue.
3488 	 */
3489 	if (vi->rq[0].xdp_prog)
3490 		return -EINVAL;
3491 
3492 	cpus_read_lock();
3493 	err = virtnet_set_queues(vi, queue_pairs);
3494 	if (err) {
3495 		cpus_read_unlock();
3496 		goto err;
3497 	}
3498 	virtnet_set_affinity(vi);
3499 	cpus_read_unlock();
3500 
3501 	netif_set_real_num_tx_queues(dev, queue_pairs);
3502 	netif_set_real_num_rx_queues(dev, queue_pairs);
3503  err:
3504 	return err;
3505 }
3506 
3507 static void virtnet_stats_sprintf(u8 **p, const char *fmt, const char *noq_fmt,
3508 				  int num, int qid, const struct virtnet_stat_desc *desc)
3509 {
3510 	int i;
3511 
3512 	if (qid < 0) {
3513 		for (i = 0; i < num; ++i)
3514 			ethtool_sprintf(p, noq_fmt, desc[i].desc);
3515 	} else {
3516 		for (i = 0; i < num; ++i)
3517 			ethtool_sprintf(p, fmt, qid, desc[i].desc);
3518 	}
3519 }
3520 
3521 /* qid == -1: for rx/tx queue total field */
3522 static void virtnet_get_stats_string(struct virtnet_info *vi, int type, int qid, u8 **data)
3523 {
3524 	const struct virtnet_stat_desc *desc;
3525 	const char *fmt, *noq_fmt;
3526 	u8 *p = *data;
3527 	u32 num;
3528 
3529 	if (type == VIRTNET_Q_TYPE_CQ && qid >= 0) {
3530 		noq_fmt = "cq_hw_%s";
3531 
3532 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_CVQ) {
3533 			desc = &virtnet_stats_cvq_desc[0];
3534 			num = ARRAY_SIZE(virtnet_stats_cvq_desc);
3535 
3536 			virtnet_stats_sprintf(&p, NULL, noq_fmt, num, -1, desc);
3537 		}
3538 	}
3539 
3540 	if (type == VIRTNET_Q_TYPE_RX) {
3541 		fmt = "rx%u_%s";
3542 		noq_fmt = "rx_%s";
3543 
3544 		desc = &virtnet_rq_stats_desc[0];
3545 		num = ARRAY_SIZE(virtnet_rq_stats_desc);
3546 
3547 		virtnet_stats_sprintf(&p, fmt, noq_fmt, num, qid, desc);
3548 
3549 		fmt = "rx%u_hw_%s";
3550 		noq_fmt = "rx_hw_%s";
3551 
3552 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_BASIC) {
3553 			desc = &virtnet_stats_rx_basic_desc[0];
3554 			num = ARRAY_SIZE(virtnet_stats_rx_basic_desc);
3555 
3556 			virtnet_stats_sprintf(&p, fmt, noq_fmt, num, qid, desc);
3557 		}
3558 
3559 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_CSUM) {
3560 			desc = &virtnet_stats_rx_csum_desc[0];
3561 			num = ARRAY_SIZE(virtnet_stats_rx_csum_desc);
3562 
3563 			virtnet_stats_sprintf(&p, fmt, noq_fmt, num, qid, desc);
3564 		}
3565 
3566 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_SPEED) {
3567 			desc = &virtnet_stats_rx_speed_desc[0];
3568 			num = ARRAY_SIZE(virtnet_stats_rx_speed_desc);
3569 
3570 			virtnet_stats_sprintf(&p, fmt, noq_fmt, num, qid, desc);
3571 		}
3572 	}
3573 
3574 	if (type == VIRTNET_Q_TYPE_TX) {
3575 		fmt = "tx%u_%s";
3576 		noq_fmt = "tx_%s";
3577 
3578 		desc = &virtnet_sq_stats_desc[0];
3579 		num = ARRAY_SIZE(virtnet_sq_stats_desc);
3580 
3581 		virtnet_stats_sprintf(&p, fmt, noq_fmt, num, qid, desc);
3582 
3583 		fmt = "tx%u_hw_%s";
3584 		noq_fmt = "tx_hw_%s";
3585 
3586 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_BASIC) {
3587 			desc = &virtnet_stats_tx_basic_desc[0];
3588 			num = ARRAY_SIZE(virtnet_stats_tx_basic_desc);
3589 
3590 			virtnet_stats_sprintf(&p, fmt, noq_fmt, num, qid, desc);
3591 		}
3592 
3593 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_GSO) {
3594 			desc = &virtnet_stats_tx_gso_desc[0];
3595 			num = ARRAY_SIZE(virtnet_stats_tx_gso_desc);
3596 
3597 			virtnet_stats_sprintf(&p, fmt, noq_fmt, num, qid, desc);
3598 		}
3599 
3600 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_SPEED) {
3601 			desc = &virtnet_stats_tx_speed_desc[0];
3602 			num = ARRAY_SIZE(virtnet_stats_tx_speed_desc);
3603 
3604 			virtnet_stats_sprintf(&p, fmt, noq_fmt, num, qid, desc);
3605 		}
3606 	}
3607 
3608 	*data = p;
3609 }
3610 
3611 struct virtnet_stats_ctx {
3612 	/* The stats are write to qstats or ethtool -S */
3613 	bool to_qstat;
3614 
3615 	/* Used to calculate the offset inside the output buffer. */
3616 	u32 desc_num[3];
3617 
3618 	/* The actual supported stat types. */
3619 	u32 bitmap[3];
3620 
3621 	/* Used to calculate the reply buffer size. */
3622 	u32 size[3];
3623 
3624 	/* Record the output buffer. */
3625 	u64 *data;
3626 };
3627 
3628 static void virtnet_stats_ctx_init(struct virtnet_info *vi,
3629 				   struct virtnet_stats_ctx *ctx,
3630 				   u64 *data, bool to_qstat)
3631 {
3632 	u32 queue_type;
3633 
3634 	ctx->data = data;
3635 	ctx->to_qstat = to_qstat;
3636 
3637 	if (to_qstat) {
3638 		ctx->desc_num[VIRTNET_Q_TYPE_RX] = ARRAY_SIZE(virtnet_rq_stats_desc_qstat);
3639 		ctx->desc_num[VIRTNET_Q_TYPE_TX] = ARRAY_SIZE(virtnet_sq_stats_desc_qstat);
3640 
3641 		queue_type = VIRTNET_Q_TYPE_RX;
3642 
3643 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_BASIC) {
3644 			ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_RX_BASIC;
3645 			ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_rx_basic_desc_qstat);
3646 			ctx->size[queue_type]     += sizeof(struct virtio_net_stats_rx_basic);
3647 		}
3648 
3649 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_CSUM) {
3650 			ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_RX_CSUM;
3651 			ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_rx_csum_desc_qstat);
3652 			ctx->size[queue_type]     += sizeof(struct virtio_net_stats_rx_csum);
3653 		}
3654 
3655 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_GSO) {
3656 			ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_RX_GSO;
3657 			ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_rx_gso_desc_qstat);
3658 			ctx->size[queue_type]     += sizeof(struct virtio_net_stats_rx_gso);
3659 		}
3660 
3661 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_SPEED) {
3662 			ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_RX_SPEED;
3663 			ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_rx_speed_desc_qstat);
3664 			ctx->size[queue_type]     += sizeof(struct virtio_net_stats_rx_speed);
3665 		}
3666 
3667 		queue_type = VIRTNET_Q_TYPE_TX;
3668 
3669 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_BASIC) {
3670 			ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_TX_BASIC;
3671 			ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_tx_basic_desc_qstat);
3672 			ctx->size[queue_type]     += sizeof(struct virtio_net_stats_tx_basic);
3673 		}
3674 
3675 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_CSUM) {
3676 			ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_TX_CSUM;
3677 			ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_tx_csum_desc_qstat);
3678 			ctx->size[queue_type]     += sizeof(struct virtio_net_stats_tx_csum);
3679 		}
3680 
3681 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_GSO) {
3682 			ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_TX_GSO;
3683 			ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_tx_gso_desc_qstat);
3684 			ctx->size[queue_type]     += sizeof(struct virtio_net_stats_tx_gso);
3685 		}
3686 
3687 		if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_SPEED) {
3688 			ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_TX_SPEED;
3689 			ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_tx_speed_desc_qstat);
3690 			ctx->size[queue_type]     += sizeof(struct virtio_net_stats_tx_speed);
3691 		}
3692 
3693 		return;
3694 	}
3695 
3696 	ctx->desc_num[VIRTNET_Q_TYPE_RX] = ARRAY_SIZE(virtnet_rq_stats_desc);
3697 	ctx->desc_num[VIRTNET_Q_TYPE_TX] = ARRAY_SIZE(virtnet_sq_stats_desc);
3698 
3699 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_CVQ) {
3700 		queue_type = VIRTNET_Q_TYPE_CQ;
3701 
3702 		ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_CVQ;
3703 		ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_cvq_desc);
3704 		ctx->size[queue_type]     += sizeof(struct virtio_net_stats_cvq);
3705 	}
3706 
3707 	queue_type = VIRTNET_Q_TYPE_RX;
3708 
3709 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_BASIC) {
3710 		ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_RX_BASIC;
3711 		ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_rx_basic_desc);
3712 		ctx->size[queue_type]     += sizeof(struct virtio_net_stats_rx_basic);
3713 	}
3714 
3715 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_CSUM) {
3716 		ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_RX_CSUM;
3717 		ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_rx_csum_desc);
3718 		ctx->size[queue_type]     += sizeof(struct virtio_net_stats_rx_csum);
3719 	}
3720 
3721 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_SPEED) {
3722 		ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_RX_SPEED;
3723 		ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_rx_speed_desc);
3724 		ctx->size[queue_type]     += sizeof(struct virtio_net_stats_rx_speed);
3725 	}
3726 
3727 	queue_type = VIRTNET_Q_TYPE_TX;
3728 
3729 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_BASIC) {
3730 		ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_TX_BASIC;
3731 		ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_tx_basic_desc);
3732 		ctx->size[queue_type]     += sizeof(struct virtio_net_stats_tx_basic);
3733 	}
3734 
3735 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_GSO) {
3736 		ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_TX_GSO;
3737 		ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_tx_gso_desc);
3738 		ctx->size[queue_type]     += sizeof(struct virtio_net_stats_tx_gso);
3739 	}
3740 
3741 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_SPEED) {
3742 		ctx->bitmap[queue_type]   |= VIRTIO_NET_STATS_TYPE_TX_SPEED;
3743 		ctx->desc_num[queue_type] += ARRAY_SIZE(virtnet_stats_tx_speed_desc);
3744 		ctx->size[queue_type]     += sizeof(struct virtio_net_stats_tx_speed);
3745 	}
3746 }
3747 
3748 /* stats_sum_queue - Calculate the sum of the same fields in sq or rq.
3749  * @sum: the position to store the sum values
3750  * @num: field num
3751  * @q_value: the first queue fields
3752  * @q_num: number of the queues
3753  */
3754 static void stats_sum_queue(u64 *sum, u32 num, u64 *q_value, u32 q_num)
3755 {
3756 	u32 step = num;
3757 	int i, j;
3758 	u64 *p;
3759 
3760 	for (i = 0; i < num; ++i) {
3761 		p = sum + i;
3762 		*p = 0;
3763 
3764 		for (j = 0; j < q_num; ++j)
3765 			*p += *(q_value + i + j * step);
3766 	}
3767 }
3768 
3769 static void virtnet_fill_total_fields(struct virtnet_info *vi,
3770 				      struct virtnet_stats_ctx *ctx)
3771 {
3772 	u64 *data, *first_rx_q, *first_tx_q;
3773 	u32 num_cq, num_rx, num_tx;
3774 
3775 	num_cq = ctx->desc_num[VIRTNET_Q_TYPE_CQ];
3776 	num_rx = ctx->desc_num[VIRTNET_Q_TYPE_RX];
3777 	num_tx = ctx->desc_num[VIRTNET_Q_TYPE_TX];
3778 
3779 	first_rx_q = ctx->data + num_rx + num_tx + num_cq;
3780 	first_tx_q = first_rx_q + vi->curr_queue_pairs * num_rx;
3781 
3782 	data = ctx->data;
3783 
3784 	stats_sum_queue(data, num_rx, first_rx_q, vi->curr_queue_pairs);
3785 
3786 	data = ctx->data + num_rx;
3787 
3788 	stats_sum_queue(data, num_tx, first_tx_q, vi->curr_queue_pairs);
3789 }
3790 
3791 static void virtnet_fill_stats_qstat(struct virtnet_info *vi, u32 qid,
3792 				     struct virtnet_stats_ctx *ctx,
3793 				     const u8 *base, bool drv_stats, u8 reply_type)
3794 {
3795 	const struct virtnet_stat_desc *desc;
3796 	const u64_stats_t *v_stat;
3797 	u64 offset, bitmap;
3798 	const __le64 *v;
3799 	u32 queue_type;
3800 	int i, num;
3801 
3802 	queue_type = vq_type(vi, qid);
3803 	bitmap = ctx->bitmap[queue_type];
3804 
3805 	if (drv_stats) {
3806 		if (queue_type == VIRTNET_Q_TYPE_RX) {
3807 			desc = &virtnet_rq_stats_desc_qstat[0];
3808 			num = ARRAY_SIZE(virtnet_rq_stats_desc_qstat);
3809 		} else {
3810 			desc = &virtnet_sq_stats_desc_qstat[0];
3811 			num = ARRAY_SIZE(virtnet_sq_stats_desc_qstat);
3812 		}
3813 
3814 		for (i = 0; i < num; ++i) {
3815 			offset = desc[i].qstat_offset / sizeof(*ctx->data);
3816 			v_stat = (const u64_stats_t *)(base + desc[i].offset);
3817 			ctx->data[offset] = u64_stats_read(v_stat);
3818 		}
3819 		return;
3820 	}
3821 
3822 	if (bitmap & VIRTIO_NET_STATS_TYPE_RX_BASIC) {
3823 		desc = &virtnet_stats_rx_basic_desc_qstat[0];
3824 		num = ARRAY_SIZE(virtnet_stats_rx_basic_desc_qstat);
3825 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_RX_BASIC)
3826 			goto found;
3827 	}
3828 
3829 	if (bitmap & VIRTIO_NET_STATS_TYPE_RX_CSUM) {
3830 		desc = &virtnet_stats_rx_csum_desc_qstat[0];
3831 		num = ARRAY_SIZE(virtnet_stats_rx_csum_desc_qstat);
3832 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_RX_CSUM)
3833 			goto found;
3834 	}
3835 
3836 	if (bitmap & VIRTIO_NET_STATS_TYPE_RX_GSO) {
3837 		desc = &virtnet_stats_rx_gso_desc_qstat[0];
3838 		num = ARRAY_SIZE(virtnet_stats_rx_gso_desc_qstat);
3839 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_RX_GSO)
3840 			goto found;
3841 	}
3842 
3843 	if (bitmap & VIRTIO_NET_STATS_TYPE_RX_SPEED) {
3844 		desc = &virtnet_stats_rx_speed_desc_qstat[0];
3845 		num = ARRAY_SIZE(virtnet_stats_rx_speed_desc_qstat);
3846 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_RX_SPEED)
3847 			goto found;
3848 	}
3849 
3850 	if (bitmap & VIRTIO_NET_STATS_TYPE_TX_BASIC) {
3851 		desc = &virtnet_stats_tx_basic_desc_qstat[0];
3852 		num = ARRAY_SIZE(virtnet_stats_tx_basic_desc_qstat);
3853 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_TX_BASIC)
3854 			goto found;
3855 	}
3856 
3857 	if (bitmap & VIRTIO_NET_STATS_TYPE_TX_CSUM) {
3858 		desc = &virtnet_stats_tx_csum_desc_qstat[0];
3859 		num = ARRAY_SIZE(virtnet_stats_tx_csum_desc_qstat);
3860 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_TX_CSUM)
3861 			goto found;
3862 	}
3863 
3864 	if (bitmap & VIRTIO_NET_STATS_TYPE_TX_GSO) {
3865 		desc = &virtnet_stats_tx_gso_desc_qstat[0];
3866 		num = ARRAY_SIZE(virtnet_stats_tx_gso_desc_qstat);
3867 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_TX_GSO)
3868 			goto found;
3869 	}
3870 
3871 	if (bitmap & VIRTIO_NET_STATS_TYPE_TX_SPEED) {
3872 		desc = &virtnet_stats_tx_speed_desc_qstat[0];
3873 		num = ARRAY_SIZE(virtnet_stats_tx_speed_desc_qstat);
3874 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_TX_SPEED)
3875 			goto found;
3876 	}
3877 
3878 	return;
3879 
3880 found:
3881 	for (i = 0; i < num; ++i) {
3882 		offset = desc[i].qstat_offset / sizeof(*ctx->data);
3883 		v = (const __le64 *)(base + desc[i].offset);
3884 		ctx->data[offset] = le64_to_cpu(*v);
3885 	}
3886 }
3887 
3888 /* virtnet_fill_stats - copy the stats to qstats or ethtool -S
3889  * The stats source is the device or the driver.
3890  *
3891  * @vi: virtio net info
3892  * @qid: the vq id
3893  * @ctx: stats ctx (initiated by virtnet_stats_ctx_init())
3894  * @base: pointer to the device reply or the driver stats structure.
3895  * @drv_stats: designate the base type (device reply, driver stats)
3896  * @type: the type of the device reply (if drv_stats is true, this must be zero)
3897  */
3898 static void virtnet_fill_stats(struct virtnet_info *vi, u32 qid,
3899 			       struct virtnet_stats_ctx *ctx,
3900 			       const u8 *base, bool drv_stats, u8 reply_type)
3901 {
3902 	u32 queue_type, num_rx, num_tx, num_cq;
3903 	const struct virtnet_stat_desc *desc;
3904 	const u64_stats_t *v_stat;
3905 	u64 offset, bitmap;
3906 	const __le64 *v;
3907 	int i, num;
3908 
3909 	if (ctx->to_qstat)
3910 		return virtnet_fill_stats_qstat(vi, qid, ctx, base, drv_stats, reply_type);
3911 
3912 	num_cq = ctx->desc_num[VIRTNET_Q_TYPE_CQ];
3913 	num_rx = ctx->desc_num[VIRTNET_Q_TYPE_RX];
3914 	num_tx = ctx->desc_num[VIRTNET_Q_TYPE_TX];
3915 
3916 	queue_type = vq_type(vi, qid);
3917 	bitmap = ctx->bitmap[queue_type];
3918 
3919 	/* skip the total fields of pairs */
3920 	offset = num_rx + num_tx;
3921 
3922 	if (queue_type == VIRTNET_Q_TYPE_TX) {
3923 		offset += num_cq + num_rx * vi->curr_queue_pairs + num_tx * (qid / 2);
3924 
3925 		num = ARRAY_SIZE(virtnet_sq_stats_desc);
3926 		if (drv_stats) {
3927 			desc = &virtnet_sq_stats_desc[0];
3928 			goto drv_stats;
3929 		}
3930 
3931 		offset += num;
3932 
3933 	} else if (queue_type == VIRTNET_Q_TYPE_RX) {
3934 		offset += num_cq + num_rx * (qid / 2);
3935 
3936 		num = ARRAY_SIZE(virtnet_rq_stats_desc);
3937 		if (drv_stats) {
3938 			desc = &virtnet_rq_stats_desc[0];
3939 			goto drv_stats;
3940 		}
3941 
3942 		offset += num;
3943 	}
3944 
3945 	if (bitmap & VIRTIO_NET_STATS_TYPE_CVQ) {
3946 		desc = &virtnet_stats_cvq_desc[0];
3947 		num = ARRAY_SIZE(virtnet_stats_cvq_desc);
3948 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_CVQ)
3949 			goto found;
3950 
3951 		offset += num;
3952 	}
3953 
3954 	if (bitmap & VIRTIO_NET_STATS_TYPE_RX_BASIC) {
3955 		desc = &virtnet_stats_rx_basic_desc[0];
3956 		num = ARRAY_SIZE(virtnet_stats_rx_basic_desc);
3957 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_RX_BASIC)
3958 			goto found;
3959 
3960 		offset += num;
3961 	}
3962 
3963 	if (bitmap & VIRTIO_NET_STATS_TYPE_RX_CSUM) {
3964 		desc = &virtnet_stats_rx_csum_desc[0];
3965 		num = ARRAY_SIZE(virtnet_stats_rx_csum_desc);
3966 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_RX_CSUM)
3967 			goto found;
3968 
3969 		offset += num;
3970 	}
3971 
3972 	if (bitmap & VIRTIO_NET_STATS_TYPE_RX_SPEED) {
3973 		desc = &virtnet_stats_rx_speed_desc[0];
3974 		num = ARRAY_SIZE(virtnet_stats_rx_speed_desc);
3975 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_RX_SPEED)
3976 			goto found;
3977 
3978 		offset += num;
3979 	}
3980 
3981 	if (bitmap & VIRTIO_NET_STATS_TYPE_TX_BASIC) {
3982 		desc = &virtnet_stats_tx_basic_desc[0];
3983 		num = ARRAY_SIZE(virtnet_stats_tx_basic_desc);
3984 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_TX_BASIC)
3985 			goto found;
3986 
3987 		offset += num;
3988 	}
3989 
3990 	if (bitmap & VIRTIO_NET_STATS_TYPE_TX_GSO) {
3991 		desc = &virtnet_stats_tx_gso_desc[0];
3992 		num = ARRAY_SIZE(virtnet_stats_tx_gso_desc);
3993 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_TX_GSO)
3994 			goto found;
3995 
3996 		offset += num;
3997 	}
3998 
3999 	if (bitmap & VIRTIO_NET_STATS_TYPE_TX_SPEED) {
4000 		desc = &virtnet_stats_tx_speed_desc[0];
4001 		num = ARRAY_SIZE(virtnet_stats_tx_speed_desc);
4002 		if (reply_type == VIRTIO_NET_STATS_TYPE_REPLY_TX_SPEED)
4003 			goto found;
4004 
4005 		offset += num;
4006 	}
4007 
4008 	return;
4009 
4010 found:
4011 	for (i = 0; i < num; ++i) {
4012 		v = (const __le64 *)(base + desc[i].offset);
4013 		ctx->data[offset + i] = le64_to_cpu(*v);
4014 	}
4015 
4016 	return;
4017 
4018 drv_stats:
4019 	for (i = 0; i < num; ++i) {
4020 		v_stat = (const u64_stats_t *)(base + desc[i].offset);
4021 		ctx->data[offset + i] = u64_stats_read(v_stat);
4022 	}
4023 }
4024 
4025 static int __virtnet_get_hw_stats(struct virtnet_info *vi,
4026 				  struct virtnet_stats_ctx *ctx,
4027 				  struct virtio_net_ctrl_queue_stats *req,
4028 				  int req_size, void *reply, int res_size)
4029 {
4030 	struct virtio_net_stats_reply_hdr *hdr;
4031 	struct scatterlist sgs_in, sgs_out;
4032 	void *p;
4033 	u32 qid;
4034 	int ok;
4035 
4036 	sg_init_one(&sgs_out, req, req_size);
4037 	sg_init_one(&sgs_in, reply, res_size);
4038 
4039 	ok = virtnet_send_command_reply(vi, VIRTIO_NET_CTRL_STATS,
4040 					VIRTIO_NET_CTRL_STATS_GET,
4041 					&sgs_out, &sgs_in);
4042 
4043 	if (!ok)
4044 		return ok;
4045 
4046 	for (p = reply; p - reply < res_size; p += le16_to_cpu(hdr->size)) {
4047 		hdr = p;
4048 		qid = le16_to_cpu(hdr->vq_index);
4049 		virtnet_fill_stats(vi, qid, ctx, p, false, hdr->type);
4050 	}
4051 
4052 	return 0;
4053 }
4054 
4055 static void virtnet_make_stat_req(struct virtnet_info *vi,
4056 				  struct virtnet_stats_ctx *ctx,
4057 				  struct virtio_net_ctrl_queue_stats *req,
4058 				  int qid, int *idx)
4059 {
4060 	int qtype = vq_type(vi, qid);
4061 	u64 bitmap = ctx->bitmap[qtype];
4062 
4063 	if (!bitmap)
4064 		return;
4065 
4066 	req->stats[*idx].vq_index = cpu_to_le16(qid);
4067 	req->stats[*idx].types_bitmap[0] = cpu_to_le64(bitmap);
4068 	*idx += 1;
4069 }
4070 
4071 /* qid: -1: get stats of all vq.
4072  *     > 0: get the stats for the special vq. This must not be cvq.
4073  */
4074 static int virtnet_get_hw_stats(struct virtnet_info *vi,
4075 				struct virtnet_stats_ctx *ctx, int qid)
4076 {
4077 	int qnum, i, j, res_size, qtype, last_vq, first_vq;
4078 	struct virtio_net_ctrl_queue_stats *req;
4079 	bool enable_cvq;
4080 	void *reply;
4081 	int ok;
4082 
4083 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_DEVICE_STATS))
4084 		return 0;
4085 
4086 	if (qid == -1) {
4087 		last_vq = vi->curr_queue_pairs * 2 - 1;
4088 		first_vq = 0;
4089 		enable_cvq = true;
4090 	} else {
4091 		last_vq = qid;
4092 		first_vq = qid;
4093 		enable_cvq = false;
4094 	}
4095 
4096 	qnum = 0;
4097 	res_size = 0;
4098 	for (i = first_vq; i <= last_vq ; ++i) {
4099 		qtype = vq_type(vi, i);
4100 		if (ctx->bitmap[qtype]) {
4101 			++qnum;
4102 			res_size += ctx->size[qtype];
4103 		}
4104 	}
4105 
4106 	if (enable_cvq && ctx->bitmap[VIRTNET_Q_TYPE_CQ]) {
4107 		res_size += ctx->size[VIRTNET_Q_TYPE_CQ];
4108 		qnum += 1;
4109 	}
4110 
4111 	req = kcalloc(qnum, sizeof(*req), GFP_KERNEL);
4112 	if (!req)
4113 		return -ENOMEM;
4114 
4115 	reply = kmalloc(res_size, GFP_KERNEL);
4116 	if (!reply) {
4117 		kfree(req);
4118 		return -ENOMEM;
4119 	}
4120 
4121 	j = 0;
4122 	for (i = first_vq; i <= last_vq ; ++i)
4123 		virtnet_make_stat_req(vi, ctx, req, i, &j);
4124 
4125 	if (enable_cvq)
4126 		virtnet_make_stat_req(vi, ctx, req, vi->max_queue_pairs * 2, &j);
4127 
4128 	ok = __virtnet_get_hw_stats(vi, ctx, req, sizeof(*req) * j, reply, res_size);
4129 
4130 	kfree(req);
4131 	kfree(reply);
4132 
4133 	return ok;
4134 }
4135 
4136 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
4137 {
4138 	struct virtnet_info *vi = netdev_priv(dev);
4139 	unsigned int i;
4140 	u8 *p = data;
4141 
4142 	switch (stringset) {
4143 	case ETH_SS_STATS:
4144 		/* Generate the total field names. */
4145 		virtnet_get_stats_string(vi, VIRTNET_Q_TYPE_RX, -1, &p);
4146 		virtnet_get_stats_string(vi, VIRTNET_Q_TYPE_TX, -1, &p);
4147 
4148 		virtnet_get_stats_string(vi, VIRTNET_Q_TYPE_CQ, 0, &p);
4149 
4150 		for (i = 0; i < vi->curr_queue_pairs; ++i)
4151 			virtnet_get_stats_string(vi, VIRTNET_Q_TYPE_RX, i, &p);
4152 
4153 		for (i = 0; i < vi->curr_queue_pairs; ++i)
4154 			virtnet_get_stats_string(vi, VIRTNET_Q_TYPE_TX, i, &p);
4155 		break;
4156 	}
4157 }
4158 
4159 static int virtnet_get_sset_count(struct net_device *dev, int sset)
4160 {
4161 	struct virtnet_info *vi = netdev_priv(dev);
4162 	struct virtnet_stats_ctx ctx = {0};
4163 	u32 pair_count;
4164 
4165 	switch (sset) {
4166 	case ETH_SS_STATS:
4167 		virtnet_stats_ctx_init(vi, &ctx, NULL, false);
4168 
4169 		pair_count = ctx.desc_num[VIRTNET_Q_TYPE_RX] + ctx.desc_num[VIRTNET_Q_TYPE_TX];
4170 
4171 		return pair_count + ctx.desc_num[VIRTNET_Q_TYPE_CQ] +
4172 			vi->curr_queue_pairs * pair_count;
4173 	default:
4174 		return -EOPNOTSUPP;
4175 	}
4176 }
4177 
4178 static void virtnet_get_ethtool_stats(struct net_device *dev,
4179 				      struct ethtool_stats *stats, u64 *data)
4180 {
4181 	struct virtnet_info *vi = netdev_priv(dev);
4182 	struct virtnet_stats_ctx ctx = {0};
4183 	unsigned int start, i;
4184 	const u8 *stats_base;
4185 
4186 	virtnet_stats_ctx_init(vi, &ctx, data, false);
4187 	if (virtnet_get_hw_stats(vi, &ctx, -1))
4188 		dev_warn(&vi->dev->dev, "Failed to get hw stats.\n");
4189 
4190 	for (i = 0; i < vi->curr_queue_pairs; i++) {
4191 		struct receive_queue *rq = &vi->rq[i];
4192 		struct send_queue *sq = &vi->sq[i];
4193 
4194 		stats_base = (const u8 *)&rq->stats;
4195 		do {
4196 			start = u64_stats_fetch_begin(&rq->stats.syncp);
4197 			virtnet_fill_stats(vi, i * 2, &ctx, stats_base, true, 0);
4198 		} while (u64_stats_fetch_retry(&rq->stats.syncp, start));
4199 
4200 		stats_base = (const u8 *)&sq->stats;
4201 		do {
4202 			start = u64_stats_fetch_begin(&sq->stats.syncp);
4203 			virtnet_fill_stats(vi, i * 2 + 1, &ctx, stats_base, true, 0);
4204 		} while (u64_stats_fetch_retry(&sq->stats.syncp, start));
4205 	}
4206 
4207 	virtnet_fill_total_fields(vi, &ctx);
4208 }
4209 
4210 static void virtnet_get_channels(struct net_device *dev,
4211 				 struct ethtool_channels *channels)
4212 {
4213 	struct virtnet_info *vi = netdev_priv(dev);
4214 
4215 	channels->combined_count = vi->curr_queue_pairs;
4216 	channels->max_combined = vi->max_queue_pairs;
4217 	channels->max_other = 0;
4218 	channels->rx_count = 0;
4219 	channels->tx_count = 0;
4220 	channels->other_count = 0;
4221 }
4222 
4223 static int virtnet_set_link_ksettings(struct net_device *dev,
4224 				      const struct ethtool_link_ksettings *cmd)
4225 {
4226 	struct virtnet_info *vi = netdev_priv(dev);
4227 
4228 	return ethtool_virtdev_set_link_ksettings(dev, cmd,
4229 						  &vi->speed, &vi->duplex);
4230 }
4231 
4232 static int virtnet_get_link_ksettings(struct net_device *dev,
4233 				      struct ethtool_link_ksettings *cmd)
4234 {
4235 	struct virtnet_info *vi = netdev_priv(dev);
4236 
4237 	cmd->base.speed = vi->speed;
4238 	cmd->base.duplex = vi->duplex;
4239 	cmd->base.port = PORT_OTHER;
4240 
4241 	return 0;
4242 }
4243 
4244 static int virtnet_send_tx_notf_coal_cmds(struct virtnet_info *vi,
4245 					  struct ethtool_coalesce *ec)
4246 {
4247 	struct virtio_net_ctrl_coal_tx *coal_tx __free(kfree) = NULL;
4248 	struct scatterlist sgs_tx;
4249 	int i;
4250 
4251 	coal_tx = kzalloc(sizeof(*coal_tx), GFP_KERNEL);
4252 	if (!coal_tx)
4253 		return -ENOMEM;
4254 
4255 	coal_tx->tx_usecs = cpu_to_le32(ec->tx_coalesce_usecs);
4256 	coal_tx->tx_max_packets = cpu_to_le32(ec->tx_max_coalesced_frames);
4257 	sg_init_one(&sgs_tx, coal_tx, sizeof(*coal_tx));
4258 
4259 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
4260 				  VIRTIO_NET_CTRL_NOTF_COAL_TX_SET,
4261 				  &sgs_tx))
4262 		return -EINVAL;
4263 
4264 	vi->intr_coal_tx.max_usecs = ec->tx_coalesce_usecs;
4265 	vi->intr_coal_tx.max_packets = ec->tx_max_coalesced_frames;
4266 	for (i = 0; i < vi->max_queue_pairs; i++) {
4267 		vi->sq[i].intr_coal.max_usecs = ec->tx_coalesce_usecs;
4268 		vi->sq[i].intr_coal.max_packets = ec->tx_max_coalesced_frames;
4269 	}
4270 
4271 	return 0;
4272 }
4273 
4274 static int virtnet_send_rx_notf_coal_cmds(struct virtnet_info *vi,
4275 					  struct ethtool_coalesce *ec)
4276 {
4277 	struct virtio_net_ctrl_coal_rx *coal_rx __free(kfree) = NULL;
4278 	bool rx_ctrl_dim_on = !!ec->use_adaptive_rx_coalesce;
4279 	struct scatterlist sgs_rx;
4280 	int i;
4281 
4282 	if (rx_ctrl_dim_on && !virtio_has_feature(vi->vdev, VIRTIO_NET_F_VQ_NOTF_COAL))
4283 		return -EOPNOTSUPP;
4284 
4285 	if (rx_ctrl_dim_on && (ec->rx_coalesce_usecs != vi->intr_coal_rx.max_usecs ||
4286 			       ec->rx_max_coalesced_frames != vi->intr_coal_rx.max_packets))
4287 		return -EINVAL;
4288 
4289 	if (rx_ctrl_dim_on && !vi->rx_dim_enabled) {
4290 		vi->rx_dim_enabled = true;
4291 		for (i = 0; i < vi->max_queue_pairs; i++) {
4292 			mutex_lock(&vi->rq[i].dim_lock);
4293 			vi->rq[i].dim_enabled = true;
4294 			mutex_unlock(&vi->rq[i].dim_lock);
4295 		}
4296 		return 0;
4297 	}
4298 
4299 	coal_rx = kzalloc(sizeof(*coal_rx), GFP_KERNEL);
4300 	if (!coal_rx)
4301 		return -ENOMEM;
4302 
4303 	if (!rx_ctrl_dim_on && vi->rx_dim_enabled) {
4304 		vi->rx_dim_enabled = false;
4305 		for (i = 0; i < vi->max_queue_pairs; i++) {
4306 			mutex_lock(&vi->rq[i].dim_lock);
4307 			vi->rq[i].dim_enabled = false;
4308 			mutex_unlock(&vi->rq[i].dim_lock);
4309 		}
4310 	}
4311 
4312 	/* Since the per-queue coalescing params can be set,
4313 	 * we need apply the global new params even if they
4314 	 * are not updated.
4315 	 */
4316 	coal_rx->rx_usecs = cpu_to_le32(ec->rx_coalesce_usecs);
4317 	coal_rx->rx_max_packets = cpu_to_le32(ec->rx_max_coalesced_frames);
4318 	sg_init_one(&sgs_rx, coal_rx, sizeof(*coal_rx));
4319 
4320 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
4321 				  VIRTIO_NET_CTRL_NOTF_COAL_RX_SET,
4322 				  &sgs_rx))
4323 		return -EINVAL;
4324 
4325 	vi->intr_coal_rx.max_usecs = ec->rx_coalesce_usecs;
4326 	vi->intr_coal_rx.max_packets = ec->rx_max_coalesced_frames;
4327 	for (i = 0; i < vi->max_queue_pairs; i++) {
4328 		mutex_lock(&vi->rq[i].dim_lock);
4329 		vi->rq[i].intr_coal.max_usecs = ec->rx_coalesce_usecs;
4330 		vi->rq[i].intr_coal.max_packets = ec->rx_max_coalesced_frames;
4331 		mutex_unlock(&vi->rq[i].dim_lock);
4332 	}
4333 
4334 	return 0;
4335 }
4336 
4337 static int virtnet_send_notf_coal_cmds(struct virtnet_info *vi,
4338 				       struct ethtool_coalesce *ec)
4339 {
4340 	int err;
4341 
4342 	err = virtnet_send_tx_notf_coal_cmds(vi, ec);
4343 	if (err)
4344 		return err;
4345 
4346 	err = virtnet_send_rx_notf_coal_cmds(vi, ec);
4347 	if (err)
4348 		return err;
4349 
4350 	return 0;
4351 }
4352 
4353 static int virtnet_send_rx_notf_coal_vq_cmds(struct virtnet_info *vi,
4354 					     struct ethtool_coalesce *ec,
4355 					     u16 queue)
4356 {
4357 	bool rx_ctrl_dim_on = !!ec->use_adaptive_rx_coalesce;
4358 	u32 max_usecs, max_packets;
4359 	bool cur_rx_dim;
4360 	int err;
4361 
4362 	mutex_lock(&vi->rq[queue].dim_lock);
4363 	cur_rx_dim = vi->rq[queue].dim_enabled;
4364 	max_usecs = vi->rq[queue].intr_coal.max_usecs;
4365 	max_packets = vi->rq[queue].intr_coal.max_packets;
4366 
4367 	if (rx_ctrl_dim_on && (ec->rx_coalesce_usecs != max_usecs ||
4368 			       ec->rx_max_coalesced_frames != max_packets)) {
4369 		mutex_unlock(&vi->rq[queue].dim_lock);
4370 		return -EINVAL;
4371 	}
4372 
4373 	if (rx_ctrl_dim_on && !cur_rx_dim) {
4374 		vi->rq[queue].dim_enabled = true;
4375 		mutex_unlock(&vi->rq[queue].dim_lock);
4376 		return 0;
4377 	}
4378 
4379 	if (!rx_ctrl_dim_on && cur_rx_dim)
4380 		vi->rq[queue].dim_enabled = false;
4381 
4382 	/* If no params are updated, userspace ethtool will
4383 	 * reject the modification.
4384 	 */
4385 	err = virtnet_send_rx_ctrl_coal_vq_cmd(vi, queue,
4386 					       ec->rx_coalesce_usecs,
4387 					       ec->rx_max_coalesced_frames);
4388 	mutex_unlock(&vi->rq[queue].dim_lock);
4389 	return err;
4390 }
4391 
4392 static int virtnet_send_notf_coal_vq_cmds(struct virtnet_info *vi,
4393 					  struct ethtool_coalesce *ec,
4394 					  u16 queue)
4395 {
4396 	int err;
4397 
4398 	err = virtnet_send_rx_notf_coal_vq_cmds(vi, ec, queue);
4399 	if (err)
4400 		return err;
4401 
4402 	err = virtnet_send_tx_ctrl_coal_vq_cmd(vi, queue,
4403 					       ec->tx_coalesce_usecs,
4404 					       ec->tx_max_coalesced_frames);
4405 	if (err)
4406 		return err;
4407 
4408 	return 0;
4409 }
4410 
4411 static void virtnet_rx_dim_work(struct work_struct *work)
4412 {
4413 	struct dim *dim = container_of(work, struct dim, work);
4414 	struct receive_queue *rq = container_of(dim,
4415 			struct receive_queue, dim);
4416 	struct virtnet_info *vi = rq->vq->vdev->priv;
4417 	struct net_device *dev = vi->dev;
4418 	struct dim_cq_moder update_moder;
4419 	int qnum, err;
4420 
4421 	qnum = rq - vi->rq;
4422 
4423 	mutex_lock(&rq->dim_lock);
4424 	if (!rq->dim_enabled)
4425 		goto out;
4426 
4427 	update_moder = net_dim_get_rx_moderation(dim->mode, dim->profile_ix);
4428 	if (update_moder.usec != rq->intr_coal.max_usecs ||
4429 	    update_moder.pkts != rq->intr_coal.max_packets) {
4430 		err = virtnet_send_rx_ctrl_coal_vq_cmd(vi, qnum,
4431 						       update_moder.usec,
4432 						       update_moder.pkts);
4433 		if (err)
4434 			pr_debug("%s: Failed to send dim parameters on rxq%d\n",
4435 				 dev->name, qnum);
4436 	}
4437 out:
4438 	dim->state = DIM_START_MEASURE;
4439 	mutex_unlock(&rq->dim_lock);
4440 }
4441 
4442 static int virtnet_coal_params_supported(struct ethtool_coalesce *ec)
4443 {
4444 	/* usecs coalescing is supported only if VIRTIO_NET_F_NOTF_COAL
4445 	 * or VIRTIO_NET_F_VQ_NOTF_COAL feature is negotiated.
4446 	 */
4447 	if (ec->rx_coalesce_usecs || ec->tx_coalesce_usecs)
4448 		return -EOPNOTSUPP;
4449 
4450 	if (ec->tx_max_coalesced_frames > 1 ||
4451 	    ec->rx_max_coalesced_frames != 1)
4452 		return -EINVAL;
4453 
4454 	return 0;
4455 }
4456 
4457 static int virtnet_should_update_vq_weight(int dev_flags, int weight,
4458 					   int vq_weight, bool *should_update)
4459 {
4460 	if (weight ^ vq_weight) {
4461 		if (dev_flags & IFF_UP)
4462 			return -EBUSY;
4463 		*should_update = true;
4464 	}
4465 
4466 	return 0;
4467 }
4468 
4469 static int virtnet_set_coalesce(struct net_device *dev,
4470 				struct ethtool_coalesce *ec,
4471 				struct kernel_ethtool_coalesce *kernel_coal,
4472 				struct netlink_ext_ack *extack)
4473 {
4474 	struct virtnet_info *vi = netdev_priv(dev);
4475 	int ret, queue_number, napi_weight;
4476 	bool update_napi = false;
4477 
4478 	/* Can't change NAPI weight if the link is up */
4479 	napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
4480 	for (queue_number = 0; queue_number < vi->max_queue_pairs; queue_number++) {
4481 		ret = virtnet_should_update_vq_weight(dev->flags, napi_weight,
4482 						      vi->sq[queue_number].napi.weight,
4483 						      &update_napi);
4484 		if (ret)
4485 			return ret;
4486 
4487 		if (update_napi) {
4488 			/* All queues that belong to [queue_number, vi->max_queue_pairs] will be
4489 			 * updated for the sake of simplicity, which might not be necessary
4490 			 */
4491 			break;
4492 		}
4493 	}
4494 
4495 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL))
4496 		ret = virtnet_send_notf_coal_cmds(vi, ec);
4497 	else
4498 		ret = virtnet_coal_params_supported(ec);
4499 
4500 	if (ret)
4501 		return ret;
4502 
4503 	if (update_napi) {
4504 		for (; queue_number < vi->max_queue_pairs; queue_number++)
4505 			vi->sq[queue_number].napi.weight = napi_weight;
4506 	}
4507 
4508 	return ret;
4509 }
4510 
4511 static int virtnet_get_coalesce(struct net_device *dev,
4512 				struct ethtool_coalesce *ec,
4513 				struct kernel_ethtool_coalesce *kernel_coal,
4514 				struct netlink_ext_ack *extack)
4515 {
4516 	struct virtnet_info *vi = netdev_priv(dev);
4517 
4518 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
4519 		ec->rx_coalesce_usecs = vi->intr_coal_rx.max_usecs;
4520 		ec->tx_coalesce_usecs = vi->intr_coal_tx.max_usecs;
4521 		ec->tx_max_coalesced_frames = vi->intr_coal_tx.max_packets;
4522 		ec->rx_max_coalesced_frames = vi->intr_coal_rx.max_packets;
4523 		ec->use_adaptive_rx_coalesce = vi->rx_dim_enabled;
4524 	} else {
4525 		ec->rx_max_coalesced_frames = 1;
4526 
4527 		if (vi->sq[0].napi.weight)
4528 			ec->tx_max_coalesced_frames = 1;
4529 	}
4530 
4531 	return 0;
4532 }
4533 
4534 static int virtnet_set_per_queue_coalesce(struct net_device *dev,
4535 					  u32 queue,
4536 					  struct ethtool_coalesce *ec)
4537 {
4538 	struct virtnet_info *vi = netdev_priv(dev);
4539 	int ret, napi_weight;
4540 	bool update_napi = false;
4541 
4542 	if (queue >= vi->max_queue_pairs)
4543 		return -EINVAL;
4544 
4545 	/* Can't change NAPI weight if the link is up */
4546 	napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
4547 	ret = virtnet_should_update_vq_weight(dev->flags, napi_weight,
4548 					      vi->sq[queue].napi.weight,
4549 					      &update_napi);
4550 	if (ret)
4551 		return ret;
4552 
4553 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_VQ_NOTF_COAL))
4554 		ret = virtnet_send_notf_coal_vq_cmds(vi, ec, queue);
4555 	else
4556 		ret = virtnet_coal_params_supported(ec);
4557 
4558 	if (ret)
4559 		return ret;
4560 
4561 	if (update_napi)
4562 		vi->sq[queue].napi.weight = napi_weight;
4563 
4564 	return 0;
4565 }
4566 
4567 static int virtnet_get_per_queue_coalesce(struct net_device *dev,
4568 					  u32 queue,
4569 					  struct ethtool_coalesce *ec)
4570 {
4571 	struct virtnet_info *vi = netdev_priv(dev);
4572 
4573 	if (queue >= vi->max_queue_pairs)
4574 		return -EINVAL;
4575 
4576 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_VQ_NOTF_COAL)) {
4577 		mutex_lock(&vi->rq[queue].dim_lock);
4578 		ec->rx_coalesce_usecs = vi->rq[queue].intr_coal.max_usecs;
4579 		ec->tx_coalesce_usecs = vi->sq[queue].intr_coal.max_usecs;
4580 		ec->tx_max_coalesced_frames = vi->sq[queue].intr_coal.max_packets;
4581 		ec->rx_max_coalesced_frames = vi->rq[queue].intr_coal.max_packets;
4582 		ec->use_adaptive_rx_coalesce = vi->rq[queue].dim_enabled;
4583 		mutex_unlock(&vi->rq[queue].dim_lock);
4584 	} else {
4585 		ec->rx_max_coalesced_frames = 1;
4586 
4587 		if (vi->sq[queue].napi.weight)
4588 			ec->tx_max_coalesced_frames = 1;
4589 	}
4590 
4591 	return 0;
4592 }
4593 
4594 static void virtnet_init_settings(struct net_device *dev)
4595 {
4596 	struct virtnet_info *vi = netdev_priv(dev);
4597 
4598 	vi->speed = SPEED_UNKNOWN;
4599 	vi->duplex = DUPLEX_UNKNOWN;
4600 }
4601 
4602 static void virtnet_update_settings(struct virtnet_info *vi)
4603 {
4604 	u32 speed;
4605 	u8 duplex;
4606 
4607 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
4608 		return;
4609 
4610 	virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
4611 
4612 	if (ethtool_validate_speed(speed))
4613 		vi->speed = speed;
4614 
4615 	virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
4616 
4617 	if (ethtool_validate_duplex(duplex))
4618 		vi->duplex = duplex;
4619 }
4620 
4621 static u32 virtnet_get_rxfh_key_size(struct net_device *dev)
4622 {
4623 	return ((struct virtnet_info *)netdev_priv(dev))->rss_key_size;
4624 }
4625 
4626 static u32 virtnet_get_rxfh_indir_size(struct net_device *dev)
4627 {
4628 	return ((struct virtnet_info *)netdev_priv(dev))->rss_indir_table_size;
4629 }
4630 
4631 static int virtnet_get_rxfh(struct net_device *dev,
4632 			    struct ethtool_rxfh_param *rxfh)
4633 {
4634 	struct virtnet_info *vi = netdev_priv(dev);
4635 	int i;
4636 
4637 	if (rxfh->indir) {
4638 		for (i = 0; i < vi->rss_indir_table_size; ++i)
4639 			rxfh->indir[i] = vi->rss.indirection_table[i];
4640 	}
4641 
4642 	if (rxfh->key)
4643 		memcpy(rxfh->key, vi->rss.key, vi->rss_key_size);
4644 
4645 	rxfh->hfunc = ETH_RSS_HASH_TOP;
4646 
4647 	return 0;
4648 }
4649 
4650 static int virtnet_set_rxfh(struct net_device *dev,
4651 			    struct ethtool_rxfh_param *rxfh,
4652 			    struct netlink_ext_ack *extack)
4653 {
4654 	struct virtnet_info *vi = netdev_priv(dev);
4655 	bool update = false;
4656 	int i;
4657 
4658 	if (rxfh->hfunc != ETH_RSS_HASH_NO_CHANGE &&
4659 	    rxfh->hfunc != ETH_RSS_HASH_TOP)
4660 		return -EOPNOTSUPP;
4661 
4662 	if (rxfh->indir) {
4663 		if (!vi->has_rss)
4664 			return -EOPNOTSUPP;
4665 
4666 		for (i = 0; i < vi->rss_indir_table_size; ++i)
4667 			vi->rss.indirection_table[i] = rxfh->indir[i];
4668 		update = true;
4669 	}
4670 
4671 	if (rxfh->key) {
4672 		/* If either _F_HASH_REPORT or _F_RSS are negotiated, the
4673 		 * device provides hash calculation capabilities, that is,
4674 		 * hash_key is configured.
4675 		 */
4676 		if (!vi->has_rss && !vi->has_rss_hash_report)
4677 			return -EOPNOTSUPP;
4678 
4679 		memcpy(vi->rss.key, rxfh->key, vi->rss_key_size);
4680 		update = true;
4681 	}
4682 
4683 	if (update)
4684 		virtnet_commit_rss_command(vi);
4685 
4686 	return 0;
4687 }
4688 
4689 static int virtnet_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rule_locs)
4690 {
4691 	struct virtnet_info *vi = netdev_priv(dev);
4692 	int rc = 0;
4693 
4694 	switch (info->cmd) {
4695 	case ETHTOOL_GRXRINGS:
4696 		info->data = vi->curr_queue_pairs;
4697 		break;
4698 	case ETHTOOL_GRXFH:
4699 		virtnet_get_hashflow(vi, info);
4700 		break;
4701 	default:
4702 		rc = -EOPNOTSUPP;
4703 	}
4704 
4705 	return rc;
4706 }
4707 
4708 static int virtnet_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info)
4709 {
4710 	struct virtnet_info *vi = netdev_priv(dev);
4711 	int rc = 0;
4712 
4713 	switch (info->cmd) {
4714 	case ETHTOOL_SRXFH:
4715 		if (!virtnet_set_hashflow(vi, info))
4716 			rc = -EINVAL;
4717 
4718 		break;
4719 	default:
4720 		rc = -EOPNOTSUPP;
4721 	}
4722 
4723 	return rc;
4724 }
4725 
4726 static const struct ethtool_ops virtnet_ethtool_ops = {
4727 	.supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES |
4728 		ETHTOOL_COALESCE_USECS | ETHTOOL_COALESCE_USE_ADAPTIVE_RX,
4729 	.get_drvinfo = virtnet_get_drvinfo,
4730 	.get_link = ethtool_op_get_link,
4731 	.get_ringparam = virtnet_get_ringparam,
4732 	.set_ringparam = virtnet_set_ringparam,
4733 	.get_strings = virtnet_get_strings,
4734 	.get_sset_count = virtnet_get_sset_count,
4735 	.get_ethtool_stats = virtnet_get_ethtool_stats,
4736 	.set_channels = virtnet_set_channels,
4737 	.get_channels = virtnet_get_channels,
4738 	.get_ts_info = ethtool_op_get_ts_info,
4739 	.get_link_ksettings = virtnet_get_link_ksettings,
4740 	.set_link_ksettings = virtnet_set_link_ksettings,
4741 	.set_coalesce = virtnet_set_coalesce,
4742 	.get_coalesce = virtnet_get_coalesce,
4743 	.set_per_queue_coalesce = virtnet_set_per_queue_coalesce,
4744 	.get_per_queue_coalesce = virtnet_get_per_queue_coalesce,
4745 	.get_rxfh_key_size = virtnet_get_rxfh_key_size,
4746 	.get_rxfh_indir_size = virtnet_get_rxfh_indir_size,
4747 	.get_rxfh = virtnet_get_rxfh,
4748 	.set_rxfh = virtnet_set_rxfh,
4749 	.get_rxnfc = virtnet_get_rxnfc,
4750 	.set_rxnfc = virtnet_set_rxnfc,
4751 };
4752 
4753 static void virtnet_get_queue_stats_rx(struct net_device *dev, int i,
4754 				       struct netdev_queue_stats_rx *stats)
4755 {
4756 	struct virtnet_info *vi = netdev_priv(dev);
4757 	struct receive_queue *rq = &vi->rq[i];
4758 	struct virtnet_stats_ctx ctx = {0};
4759 
4760 	virtnet_stats_ctx_init(vi, &ctx, (void *)stats, true);
4761 
4762 	virtnet_get_hw_stats(vi, &ctx, i * 2);
4763 	virtnet_fill_stats(vi, i * 2, &ctx, (void *)&rq->stats, true, 0);
4764 }
4765 
4766 static void virtnet_get_queue_stats_tx(struct net_device *dev, int i,
4767 				       struct netdev_queue_stats_tx *stats)
4768 {
4769 	struct virtnet_info *vi = netdev_priv(dev);
4770 	struct send_queue *sq = &vi->sq[i];
4771 	struct virtnet_stats_ctx ctx = {0};
4772 
4773 	virtnet_stats_ctx_init(vi, &ctx, (void *)stats, true);
4774 
4775 	virtnet_get_hw_stats(vi, &ctx, i * 2 + 1);
4776 	virtnet_fill_stats(vi, i * 2 + 1, &ctx, (void *)&sq->stats, true, 0);
4777 }
4778 
4779 static void virtnet_get_base_stats(struct net_device *dev,
4780 				   struct netdev_queue_stats_rx *rx,
4781 				   struct netdev_queue_stats_tx *tx)
4782 {
4783 	struct virtnet_info *vi = netdev_priv(dev);
4784 
4785 	/* The queue stats of the virtio-net will not be reset. So here we
4786 	 * return 0.
4787 	 */
4788 	rx->bytes = 0;
4789 	rx->packets = 0;
4790 
4791 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_BASIC) {
4792 		rx->hw_drops = 0;
4793 		rx->hw_drop_overruns = 0;
4794 	}
4795 
4796 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_CSUM) {
4797 		rx->csum_unnecessary = 0;
4798 		rx->csum_none = 0;
4799 		rx->csum_bad = 0;
4800 	}
4801 
4802 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_GSO) {
4803 		rx->hw_gro_packets = 0;
4804 		rx->hw_gro_bytes = 0;
4805 		rx->hw_gro_wire_packets = 0;
4806 		rx->hw_gro_wire_bytes = 0;
4807 	}
4808 
4809 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_RX_SPEED)
4810 		rx->hw_drop_ratelimits = 0;
4811 
4812 	tx->bytes = 0;
4813 	tx->packets = 0;
4814 	tx->stop = 0;
4815 	tx->wake = 0;
4816 
4817 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_BASIC) {
4818 		tx->hw_drops = 0;
4819 		tx->hw_drop_errors = 0;
4820 	}
4821 
4822 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_CSUM) {
4823 		tx->csum_none = 0;
4824 		tx->needs_csum = 0;
4825 	}
4826 
4827 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_GSO) {
4828 		tx->hw_gso_packets = 0;
4829 		tx->hw_gso_bytes = 0;
4830 		tx->hw_gso_wire_packets = 0;
4831 		tx->hw_gso_wire_bytes = 0;
4832 	}
4833 
4834 	if (vi->device_stats_cap & VIRTIO_NET_STATS_TYPE_TX_SPEED)
4835 		tx->hw_drop_ratelimits = 0;
4836 }
4837 
4838 static const struct netdev_stat_ops virtnet_stat_ops = {
4839 	.get_queue_stats_rx	= virtnet_get_queue_stats_rx,
4840 	.get_queue_stats_tx	= virtnet_get_queue_stats_tx,
4841 	.get_base_stats		= virtnet_get_base_stats,
4842 };
4843 
4844 static void virtnet_freeze_down(struct virtio_device *vdev)
4845 {
4846 	struct virtnet_info *vi = vdev->priv;
4847 
4848 	/* Make sure no work handler is accessing the device */
4849 	flush_work(&vi->config_work);
4850 	disable_rx_mode_work(vi);
4851 	flush_work(&vi->rx_mode_work);
4852 
4853 	netif_tx_lock_bh(vi->dev);
4854 	netif_device_detach(vi->dev);
4855 	netif_tx_unlock_bh(vi->dev);
4856 	if (netif_running(vi->dev))
4857 		virtnet_close(vi->dev);
4858 }
4859 
4860 static int init_vqs(struct virtnet_info *vi);
4861 
4862 static int virtnet_restore_up(struct virtio_device *vdev)
4863 {
4864 	struct virtnet_info *vi = vdev->priv;
4865 	int err;
4866 
4867 	err = init_vqs(vi);
4868 	if (err)
4869 		return err;
4870 
4871 	virtio_device_ready(vdev);
4872 
4873 	enable_delayed_refill(vi);
4874 	enable_rx_mode_work(vi);
4875 
4876 	if (netif_running(vi->dev)) {
4877 		err = virtnet_open(vi->dev);
4878 		if (err)
4879 			return err;
4880 	}
4881 
4882 	netif_tx_lock_bh(vi->dev);
4883 	netif_device_attach(vi->dev);
4884 	netif_tx_unlock_bh(vi->dev);
4885 	return err;
4886 }
4887 
4888 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
4889 {
4890 	__virtio64 *_offloads __free(kfree) = NULL;
4891 	struct scatterlist sg;
4892 
4893 	_offloads = kzalloc(sizeof(*_offloads), GFP_KERNEL);
4894 	if (!_offloads)
4895 		return -ENOMEM;
4896 
4897 	*_offloads = cpu_to_virtio64(vi->vdev, offloads);
4898 
4899 	sg_init_one(&sg, _offloads, sizeof(*_offloads));
4900 
4901 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
4902 				  VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
4903 		dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
4904 		return -EINVAL;
4905 	}
4906 
4907 	return 0;
4908 }
4909 
4910 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
4911 {
4912 	u64 offloads = 0;
4913 
4914 	if (!vi->guest_offloads)
4915 		return 0;
4916 
4917 	return virtnet_set_guest_offloads(vi, offloads);
4918 }
4919 
4920 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
4921 {
4922 	u64 offloads = vi->guest_offloads;
4923 
4924 	if (!vi->guest_offloads)
4925 		return 0;
4926 
4927 	return virtnet_set_guest_offloads(vi, offloads);
4928 }
4929 
4930 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
4931 			   struct netlink_ext_ack *extack)
4932 {
4933 	unsigned int room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
4934 					   sizeof(struct skb_shared_info));
4935 	unsigned int max_sz = PAGE_SIZE - room - ETH_HLEN;
4936 	struct virtnet_info *vi = netdev_priv(dev);
4937 	struct bpf_prog *old_prog;
4938 	u16 xdp_qp = 0, curr_qp;
4939 	int i, err;
4940 
4941 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
4942 	    && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
4943 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
4944 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
4945 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
4946 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM) ||
4947 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) ||
4948 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6))) {
4949 		NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
4950 		return -EOPNOTSUPP;
4951 	}
4952 
4953 	if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
4954 		NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
4955 		return -EINVAL;
4956 	}
4957 
4958 	if (prog && !prog->aux->xdp_has_frags && dev->mtu > max_sz) {
4959 		NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP without frags");
4960 		netdev_warn(dev, "single-buffer XDP requires MTU less than %u\n", max_sz);
4961 		return -EINVAL;
4962 	}
4963 
4964 	curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
4965 	if (prog)
4966 		xdp_qp = nr_cpu_ids;
4967 
4968 	/* XDP requires extra queues for XDP_TX */
4969 	if (curr_qp + xdp_qp > vi->max_queue_pairs) {
4970 		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",
4971 				 curr_qp + xdp_qp, vi->max_queue_pairs);
4972 		xdp_qp = 0;
4973 	}
4974 
4975 	old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
4976 	if (!prog && !old_prog)
4977 		return 0;
4978 
4979 	if (prog)
4980 		bpf_prog_add(prog, vi->max_queue_pairs - 1);
4981 
4982 	/* Make sure NAPI is not using any XDP TX queues for RX. */
4983 	if (netif_running(dev)) {
4984 		for (i = 0; i < vi->max_queue_pairs; i++) {
4985 			napi_disable(&vi->rq[i].napi);
4986 			virtnet_napi_tx_disable(&vi->sq[i].napi);
4987 		}
4988 	}
4989 
4990 	if (!prog) {
4991 		for (i = 0; i < vi->max_queue_pairs; i++) {
4992 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
4993 			if (i == 0)
4994 				virtnet_restore_guest_offloads(vi);
4995 		}
4996 		synchronize_net();
4997 	}
4998 
4999 	err = virtnet_set_queues(vi, curr_qp + xdp_qp);
5000 	if (err)
5001 		goto err;
5002 	netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
5003 	vi->xdp_queue_pairs = xdp_qp;
5004 
5005 	if (prog) {
5006 		vi->xdp_enabled = true;
5007 		for (i = 0; i < vi->max_queue_pairs; i++) {
5008 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
5009 			if (i == 0 && !old_prog)
5010 				virtnet_clear_guest_offloads(vi);
5011 		}
5012 		if (!old_prog)
5013 			xdp_features_set_redirect_target(dev, true);
5014 	} else {
5015 		xdp_features_clear_redirect_target(dev);
5016 		vi->xdp_enabled = false;
5017 	}
5018 
5019 	for (i = 0; i < vi->max_queue_pairs; i++) {
5020 		if (old_prog)
5021 			bpf_prog_put(old_prog);
5022 		if (netif_running(dev)) {
5023 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
5024 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
5025 					       &vi->sq[i].napi);
5026 		}
5027 	}
5028 
5029 	return 0;
5030 
5031 err:
5032 	if (!prog) {
5033 		virtnet_clear_guest_offloads(vi);
5034 		for (i = 0; i < vi->max_queue_pairs; i++)
5035 			rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
5036 	}
5037 
5038 	if (netif_running(dev)) {
5039 		for (i = 0; i < vi->max_queue_pairs; i++) {
5040 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
5041 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
5042 					       &vi->sq[i].napi);
5043 		}
5044 	}
5045 	if (prog)
5046 		bpf_prog_sub(prog, vi->max_queue_pairs - 1);
5047 	return err;
5048 }
5049 
5050 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
5051 {
5052 	switch (xdp->command) {
5053 	case XDP_SETUP_PROG:
5054 		return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
5055 	default:
5056 		return -EINVAL;
5057 	}
5058 }
5059 
5060 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
5061 				      size_t len)
5062 {
5063 	struct virtnet_info *vi = netdev_priv(dev);
5064 	int ret;
5065 
5066 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
5067 		return -EOPNOTSUPP;
5068 
5069 	ret = snprintf(buf, len, "sby");
5070 	if (ret >= len)
5071 		return -EOPNOTSUPP;
5072 
5073 	return 0;
5074 }
5075 
5076 static int virtnet_set_features(struct net_device *dev,
5077 				netdev_features_t features)
5078 {
5079 	struct virtnet_info *vi = netdev_priv(dev);
5080 	u64 offloads;
5081 	int err;
5082 
5083 	if ((dev->features ^ features) & NETIF_F_GRO_HW) {
5084 		if (vi->xdp_enabled)
5085 			return -EBUSY;
5086 
5087 		if (features & NETIF_F_GRO_HW)
5088 			offloads = vi->guest_offloads_capable;
5089 		else
5090 			offloads = vi->guest_offloads_capable &
5091 				   ~GUEST_OFFLOAD_GRO_HW_MASK;
5092 
5093 		err = virtnet_set_guest_offloads(vi, offloads);
5094 		if (err)
5095 			return err;
5096 		vi->guest_offloads = offloads;
5097 	}
5098 
5099 	if ((dev->features ^ features) & NETIF_F_RXHASH) {
5100 		if (features & NETIF_F_RXHASH)
5101 			vi->rss.hash_types = vi->rss_hash_types_saved;
5102 		else
5103 			vi->rss.hash_types = VIRTIO_NET_HASH_REPORT_NONE;
5104 
5105 		if (!virtnet_commit_rss_command(vi))
5106 			return -EINVAL;
5107 	}
5108 
5109 	return 0;
5110 }
5111 
5112 static void virtnet_tx_timeout(struct net_device *dev, unsigned int txqueue)
5113 {
5114 	struct virtnet_info *priv = netdev_priv(dev);
5115 	struct send_queue *sq = &priv->sq[txqueue];
5116 	struct netdev_queue *txq = netdev_get_tx_queue(dev, txqueue);
5117 
5118 	u64_stats_update_begin(&sq->stats.syncp);
5119 	u64_stats_inc(&sq->stats.tx_timeouts);
5120 	u64_stats_update_end(&sq->stats.syncp);
5121 
5122 	netdev_err(dev, "TX timeout on queue: %u, sq: %s, vq: 0x%x, name: %s, %u usecs ago\n",
5123 		   txqueue, sq->name, sq->vq->index, sq->vq->name,
5124 		   jiffies_to_usecs(jiffies - READ_ONCE(txq->trans_start)));
5125 }
5126 
5127 static const struct net_device_ops virtnet_netdev = {
5128 	.ndo_open            = virtnet_open,
5129 	.ndo_stop   	     = virtnet_close,
5130 	.ndo_start_xmit      = start_xmit,
5131 	.ndo_validate_addr   = eth_validate_addr,
5132 	.ndo_set_mac_address = virtnet_set_mac_address,
5133 	.ndo_set_rx_mode     = virtnet_set_rx_mode,
5134 	.ndo_get_stats64     = virtnet_stats,
5135 	.ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
5136 	.ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
5137 	.ndo_bpf		= virtnet_xdp,
5138 	.ndo_xdp_xmit		= virtnet_xdp_xmit,
5139 	.ndo_features_check	= passthru_features_check,
5140 	.ndo_get_phys_port_name	= virtnet_get_phys_port_name,
5141 	.ndo_set_features	= virtnet_set_features,
5142 	.ndo_tx_timeout		= virtnet_tx_timeout,
5143 };
5144 
5145 static void virtnet_config_changed_work(struct work_struct *work)
5146 {
5147 	struct virtnet_info *vi =
5148 		container_of(work, struct virtnet_info, config_work);
5149 	u16 v;
5150 
5151 	if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
5152 				 struct virtio_net_config, status, &v) < 0)
5153 		return;
5154 
5155 	if (v & VIRTIO_NET_S_ANNOUNCE) {
5156 		netdev_notify_peers(vi->dev);
5157 		virtnet_ack_link_announce(vi);
5158 	}
5159 
5160 	/* Ignore unknown (future) status bits */
5161 	v &= VIRTIO_NET_S_LINK_UP;
5162 
5163 	if (vi->status == v)
5164 		return;
5165 
5166 	vi->status = v;
5167 
5168 	if (vi->status & VIRTIO_NET_S_LINK_UP) {
5169 		virtnet_update_settings(vi);
5170 		netif_carrier_on(vi->dev);
5171 		netif_tx_wake_all_queues(vi->dev);
5172 	} else {
5173 		netif_carrier_off(vi->dev);
5174 		netif_tx_stop_all_queues(vi->dev);
5175 	}
5176 }
5177 
5178 static void virtnet_config_changed(struct virtio_device *vdev)
5179 {
5180 	struct virtnet_info *vi = vdev->priv;
5181 
5182 	schedule_work(&vi->config_work);
5183 }
5184 
5185 static void virtnet_free_queues(struct virtnet_info *vi)
5186 {
5187 	int i;
5188 
5189 	for (i = 0; i < vi->max_queue_pairs; i++) {
5190 		__netif_napi_del(&vi->rq[i].napi);
5191 		__netif_napi_del(&vi->sq[i].napi);
5192 	}
5193 
5194 	/* We called __netif_napi_del(),
5195 	 * we need to respect an RCU grace period before freeing vi->rq
5196 	 */
5197 	synchronize_net();
5198 
5199 	kfree(vi->rq);
5200 	kfree(vi->sq);
5201 	kfree(vi->ctrl);
5202 }
5203 
5204 static void _free_receive_bufs(struct virtnet_info *vi)
5205 {
5206 	struct bpf_prog *old_prog;
5207 	int i;
5208 
5209 	for (i = 0; i < vi->max_queue_pairs; i++) {
5210 		while (vi->rq[i].pages)
5211 			__free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
5212 
5213 		old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
5214 		RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
5215 		if (old_prog)
5216 			bpf_prog_put(old_prog);
5217 	}
5218 }
5219 
5220 static void free_receive_bufs(struct virtnet_info *vi)
5221 {
5222 	rtnl_lock();
5223 	_free_receive_bufs(vi);
5224 	rtnl_unlock();
5225 }
5226 
5227 static void free_receive_page_frags(struct virtnet_info *vi)
5228 {
5229 	int i;
5230 	for (i = 0; i < vi->max_queue_pairs; i++)
5231 		if (vi->rq[i].alloc_frag.page) {
5232 			if (vi->rq[i].last_dma)
5233 				virtnet_rq_unmap(&vi->rq[i], vi->rq[i].last_dma, 0);
5234 			put_page(vi->rq[i].alloc_frag.page);
5235 		}
5236 }
5237 
5238 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf)
5239 {
5240 	if (!is_xdp_frame(buf))
5241 		dev_kfree_skb(buf);
5242 	else
5243 		xdp_return_frame(ptr_to_xdp(buf));
5244 }
5245 
5246 static void free_unused_bufs(struct virtnet_info *vi)
5247 {
5248 	void *buf;
5249 	int i;
5250 
5251 	for (i = 0; i < vi->max_queue_pairs; i++) {
5252 		struct virtqueue *vq = vi->sq[i].vq;
5253 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
5254 			virtnet_sq_free_unused_buf(vq, buf);
5255 		cond_resched();
5256 	}
5257 
5258 	for (i = 0; i < vi->max_queue_pairs; i++) {
5259 		struct virtqueue *vq = vi->rq[i].vq;
5260 
5261 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
5262 			virtnet_rq_unmap_free_buf(vq, buf);
5263 		cond_resched();
5264 	}
5265 }
5266 
5267 static void virtnet_del_vqs(struct virtnet_info *vi)
5268 {
5269 	struct virtio_device *vdev = vi->vdev;
5270 
5271 	virtnet_clean_affinity(vi);
5272 
5273 	vdev->config->del_vqs(vdev);
5274 
5275 	virtnet_free_queues(vi);
5276 }
5277 
5278 /* How large should a single buffer be so a queue full of these can fit at
5279  * least one full packet?
5280  * Logic below assumes the mergeable buffer header is used.
5281  */
5282 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
5283 {
5284 	const unsigned int hdr_len = vi->hdr_len;
5285 	unsigned int rq_size = virtqueue_get_vring_size(vq);
5286 	unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
5287 	unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
5288 	unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
5289 
5290 	return max(max(min_buf_len, hdr_len) - hdr_len,
5291 		   (unsigned int)GOOD_PACKET_LEN);
5292 }
5293 
5294 static int virtnet_find_vqs(struct virtnet_info *vi)
5295 {
5296 	vq_callback_t **callbacks;
5297 	struct virtqueue **vqs;
5298 	const char **names;
5299 	int ret = -ENOMEM;
5300 	int total_vqs;
5301 	bool *ctx;
5302 	u16 i;
5303 
5304 	/* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
5305 	 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
5306 	 * possible control vq.
5307 	 */
5308 	total_vqs = vi->max_queue_pairs * 2 +
5309 		    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
5310 
5311 	/* Allocate space for find_vqs parameters */
5312 	vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
5313 	if (!vqs)
5314 		goto err_vq;
5315 	callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
5316 	if (!callbacks)
5317 		goto err_callback;
5318 	names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
5319 	if (!names)
5320 		goto err_names;
5321 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
5322 		ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
5323 		if (!ctx)
5324 			goto err_ctx;
5325 	} else {
5326 		ctx = NULL;
5327 	}
5328 
5329 	/* Parameters for control virtqueue, if any */
5330 	if (vi->has_cvq) {
5331 		callbacks[total_vqs - 1] = NULL;
5332 		names[total_vqs - 1] = "control";
5333 	}
5334 
5335 	/* Allocate/initialize parameters for send/receive virtqueues */
5336 	for (i = 0; i < vi->max_queue_pairs; i++) {
5337 		callbacks[rxq2vq(i)] = skb_recv_done;
5338 		callbacks[txq2vq(i)] = skb_xmit_done;
5339 		sprintf(vi->rq[i].name, "input.%u", i);
5340 		sprintf(vi->sq[i].name, "output.%u", i);
5341 		names[rxq2vq(i)] = vi->rq[i].name;
5342 		names[txq2vq(i)] = vi->sq[i].name;
5343 		if (ctx)
5344 			ctx[rxq2vq(i)] = true;
5345 	}
5346 
5347 	ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
5348 				  names, ctx, NULL);
5349 	if (ret)
5350 		goto err_find;
5351 
5352 	if (vi->has_cvq) {
5353 		vi->cvq = vqs[total_vqs - 1];
5354 		if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
5355 			vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
5356 	}
5357 
5358 	for (i = 0; i < vi->max_queue_pairs; i++) {
5359 		vi->rq[i].vq = vqs[rxq2vq(i)];
5360 		vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
5361 		vi->sq[i].vq = vqs[txq2vq(i)];
5362 	}
5363 
5364 	/* run here: ret == 0. */
5365 
5366 
5367 err_find:
5368 	kfree(ctx);
5369 err_ctx:
5370 	kfree(names);
5371 err_names:
5372 	kfree(callbacks);
5373 err_callback:
5374 	kfree(vqs);
5375 err_vq:
5376 	return ret;
5377 }
5378 
5379 static int virtnet_alloc_queues(struct virtnet_info *vi)
5380 {
5381 	int i;
5382 
5383 	if (vi->has_cvq) {
5384 		vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
5385 		if (!vi->ctrl)
5386 			goto err_ctrl;
5387 	} else {
5388 		vi->ctrl = NULL;
5389 	}
5390 	vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
5391 	if (!vi->sq)
5392 		goto err_sq;
5393 	vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
5394 	if (!vi->rq)
5395 		goto err_rq;
5396 
5397 	INIT_DELAYED_WORK(&vi->refill, refill_work);
5398 	for (i = 0; i < vi->max_queue_pairs; i++) {
5399 		vi->rq[i].pages = NULL;
5400 		netif_napi_add_weight(vi->dev, &vi->rq[i].napi, virtnet_poll,
5401 				      napi_weight);
5402 		netif_napi_add_tx_weight(vi->dev, &vi->sq[i].napi,
5403 					 virtnet_poll_tx,
5404 					 napi_tx ? napi_weight : 0);
5405 
5406 		INIT_WORK(&vi->rq[i].dim.work, virtnet_rx_dim_work);
5407 		vi->rq[i].dim.mode = DIM_CQ_PERIOD_MODE_START_FROM_EQE;
5408 
5409 		sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
5410 		ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
5411 		sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
5412 
5413 		u64_stats_init(&vi->rq[i].stats.syncp);
5414 		u64_stats_init(&vi->sq[i].stats.syncp);
5415 		mutex_init(&vi->rq[i].dim_lock);
5416 	}
5417 
5418 	return 0;
5419 
5420 err_rq:
5421 	kfree(vi->sq);
5422 err_sq:
5423 	kfree(vi->ctrl);
5424 err_ctrl:
5425 	return -ENOMEM;
5426 }
5427 
5428 static int init_vqs(struct virtnet_info *vi)
5429 {
5430 	int ret;
5431 
5432 	/* Allocate send & receive queues */
5433 	ret = virtnet_alloc_queues(vi);
5434 	if (ret)
5435 		goto err;
5436 
5437 	ret = virtnet_find_vqs(vi);
5438 	if (ret)
5439 		goto err_free;
5440 
5441 	virtnet_rq_set_premapped(vi);
5442 
5443 	cpus_read_lock();
5444 	virtnet_set_affinity(vi);
5445 	cpus_read_unlock();
5446 
5447 	return 0;
5448 
5449 err_free:
5450 	virtnet_free_queues(vi);
5451 err:
5452 	return ret;
5453 }
5454 
5455 #ifdef CONFIG_SYSFS
5456 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
5457 		char *buf)
5458 {
5459 	struct virtnet_info *vi = netdev_priv(queue->dev);
5460 	unsigned int queue_index = get_netdev_rx_queue_index(queue);
5461 	unsigned int headroom = virtnet_get_headroom(vi);
5462 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
5463 	struct ewma_pkt_len *avg;
5464 
5465 	BUG_ON(queue_index >= vi->max_queue_pairs);
5466 	avg = &vi->rq[queue_index].mrg_avg_pkt_len;
5467 	return sprintf(buf, "%u\n",
5468 		       get_mergeable_buf_len(&vi->rq[queue_index], avg,
5469 				       SKB_DATA_ALIGN(headroom + tailroom)));
5470 }
5471 
5472 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
5473 	__ATTR_RO(mergeable_rx_buffer_size);
5474 
5475 static struct attribute *virtio_net_mrg_rx_attrs[] = {
5476 	&mergeable_rx_buffer_size_attribute.attr,
5477 	NULL
5478 };
5479 
5480 static const struct attribute_group virtio_net_mrg_rx_group = {
5481 	.name = "virtio_net",
5482 	.attrs = virtio_net_mrg_rx_attrs
5483 };
5484 #endif
5485 
5486 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
5487 				    unsigned int fbit,
5488 				    const char *fname, const char *dname)
5489 {
5490 	if (!virtio_has_feature(vdev, fbit))
5491 		return false;
5492 
5493 	dev_err(&vdev->dev, "device advertises feature %s but not %s",
5494 		fname, dname);
5495 
5496 	return true;
5497 }
5498 
5499 #define VIRTNET_FAIL_ON(vdev, fbit, dbit)			\
5500 	virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
5501 
5502 static bool virtnet_validate_features(struct virtio_device *vdev)
5503 {
5504 	if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
5505 	    (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
5506 			     "VIRTIO_NET_F_CTRL_VQ") ||
5507 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
5508 			     "VIRTIO_NET_F_CTRL_VQ") ||
5509 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
5510 			     "VIRTIO_NET_F_CTRL_VQ") ||
5511 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
5512 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
5513 			     "VIRTIO_NET_F_CTRL_VQ") ||
5514 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_RSS,
5515 			     "VIRTIO_NET_F_CTRL_VQ") ||
5516 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_HASH_REPORT,
5517 			     "VIRTIO_NET_F_CTRL_VQ") ||
5518 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_NOTF_COAL,
5519 			     "VIRTIO_NET_F_CTRL_VQ") ||
5520 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_VQ_NOTF_COAL,
5521 			     "VIRTIO_NET_F_CTRL_VQ"))) {
5522 		return false;
5523 	}
5524 
5525 	return true;
5526 }
5527 
5528 #define MIN_MTU ETH_MIN_MTU
5529 #define MAX_MTU ETH_MAX_MTU
5530 
5531 static int virtnet_validate(struct virtio_device *vdev)
5532 {
5533 	if (!vdev->config->get) {
5534 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
5535 			__func__);
5536 		return -EINVAL;
5537 	}
5538 
5539 	if (!virtnet_validate_features(vdev))
5540 		return -EINVAL;
5541 
5542 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
5543 		int mtu = virtio_cread16(vdev,
5544 					 offsetof(struct virtio_net_config,
5545 						  mtu));
5546 		if (mtu < MIN_MTU)
5547 			__virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
5548 	}
5549 
5550 	if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY) &&
5551 	    !virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
5552 		dev_warn(&vdev->dev, "device advertises feature VIRTIO_NET_F_STANDBY but not VIRTIO_NET_F_MAC, disabling standby");
5553 		__virtio_clear_bit(vdev, VIRTIO_NET_F_STANDBY);
5554 	}
5555 
5556 	return 0;
5557 }
5558 
5559 static bool virtnet_check_guest_gso(const struct virtnet_info *vi)
5560 {
5561 	return virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
5562 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
5563 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
5564 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
5565 		(virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) &&
5566 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6));
5567 }
5568 
5569 static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu)
5570 {
5571 	bool guest_gso = virtnet_check_guest_gso(vi);
5572 
5573 	/* If device can receive ANY guest GSO packets, regardless of mtu,
5574 	 * allocate packets of maximum size, otherwise limit it to only
5575 	 * mtu size worth only.
5576 	 */
5577 	if (mtu > ETH_DATA_LEN || guest_gso) {
5578 		vi->big_packets = true;
5579 		vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE);
5580 	}
5581 }
5582 
5583 #define VIRTIO_NET_HASH_REPORT_MAX_TABLE      10
5584 static enum xdp_rss_hash_type
5585 virtnet_xdp_rss_type[VIRTIO_NET_HASH_REPORT_MAX_TABLE] = {
5586 	[VIRTIO_NET_HASH_REPORT_NONE] = XDP_RSS_TYPE_NONE,
5587 	[VIRTIO_NET_HASH_REPORT_IPv4] = XDP_RSS_TYPE_L3_IPV4,
5588 	[VIRTIO_NET_HASH_REPORT_TCPv4] = XDP_RSS_TYPE_L4_IPV4_TCP,
5589 	[VIRTIO_NET_HASH_REPORT_UDPv4] = XDP_RSS_TYPE_L4_IPV4_UDP,
5590 	[VIRTIO_NET_HASH_REPORT_IPv6] = XDP_RSS_TYPE_L3_IPV6,
5591 	[VIRTIO_NET_HASH_REPORT_TCPv6] = XDP_RSS_TYPE_L4_IPV6_TCP,
5592 	[VIRTIO_NET_HASH_REPORT_UDPv6] = XDP_RSS_TYPE_L4_IPV6_UDP,
5593 	[VIRTIO_NET_HASH_REPORT_IPv6_EX] = XDP_RSS_TYPE_L3_IPV6_EX,
5594 	[VIRTIO_NET_HASH_REPORT_TCPv6_EX] = XDP_RSS_TYPE_L4_IPV6_TCP_EX,
5595 	[VIRTIO_NET_HASH_REPORT_UDPv6_EX] = XDP_RSS_TYPE_L4_IPV6_UDP_EX
5596 };
5597 
5598 static int virtnet_xdp_rx_hash(const struct xdp_md *_ctx, u32 *hash,
5599 			       enum xdp_rss_hash_type *rss_type)
5600 {
5601 	const struct xdp_buff *xdp = (void *)_ctx;
5602 	struct virtio_net_hdr_v1_hash *hdr_hash;
5603 	struct virtnet_info *vi;
5604 	u16 hash_report;
5605 
5606 	if (!(xdp->rxq->dev->features & NETIF_F_RXHASH))
5607 		return -ENODATA;
5608 
5609 	vi = netdev_priv(xdp->rxq->dev);
5610 	hdr_hash = (struct virtio_net_hdr_v1_hash *)(xdp->data - vi->hdr_len);
5611 	hash_report = __le16_to_cpu(hdr_hash->hash_report);
5612 
5613 	if (hash_report >= VIRTIO_NET_HASH_REPORT_MAX_TABLE)
5614 		hash_report = VIRTIO_NET_HASH_REPORT_NONE;
5615 
5616 	*rss_type = virtnet_xdp_rss_type[hash_report];
5617 	*hash = __le32_to_cpu(hdr_hash->hash_value);
5618 	return 0;
5619 }
5620 
5621 static const struct xdp_metadata_ops virtnet_xdp_metadata_ops = {
5622 	.xmo_rx_hash			= virtnet_xdp_rx_hash,
5623 };
5624 
5625 static int virtnet_probe(struct virtio_device *vdev)
5626 {
5627 	int i, err = -ENOMEM;
5628 	struct net_device *dev;
5629 	struct virtnet_info *vi;
5630 	u16 max_queue_pairs;
5631 	int mtu = 0;
5632 
5633 	/* Find if host supports multiqueue/rss virtio_net device */
5634 	max_queue_pairs = 1;
5635 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MQ) || virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
5636 		max_queue_pairs =
5637 		     virtio_cread16(vdev, offsetof(struct virtio_net_config, max_virtqueue_pairs));
5638 
5639 	/* We need at least 2 queue's */
5640 	if (max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
5641 	    max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
5642 	    !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
5643 		max_queue_pairs = 1;
5644 
5645 	/* Allocate ourselves a network device with room for our info */
5646 	dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
5647 	if (!dev)
5648 		return -ENOMEM;
5649 
5650 	/* Set up network device as normal. */
5651 	dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
5652 			   IFF_TX_SKB_NO_LINEAR;
5653 	dev->netdev_ops = &virtnet_netdev;
5654 	dev->stat_ops = &virtnet_stat_ops;
5655 	dev->features = NETIF_F_HIGHDMA;
5656 
5657 	dev->ethtool_ops = &virtnet_ethtool_ops;
5658 	SET_NETDEV_DEV(dev, &vdev->dev);
5659 
5660 	/* Do we support "hardware" checksums? */
5661 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
5662 		/* This opens up the world of extra features. */
5663 		dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
5664 		if (csum)
5665 			dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
5666 
5667 		if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
5668 			dev->hw_features |= NETIF_F_TSO
5669 				| NETIF_F_TSO_ECN | NETIF_F_TSO6;
5670 		}
5671 		/* Individual feature bits: what can host handle? */
5672 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
5673 			dev->hw_features |= NETIF_F_TSO;
5674 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
5675 			dev->hw_features |= NETIF_F_TSO6;
5676 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
5677 			dev->hw_features |= NETIF_F_TSO_ECN;
5678 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_USO))
5679 			dev->hw_features |= NETIF_F_GSO_UDP_L4;
5680 
5681 		dev->features |= NETIF_F_GSO_ROBUST;
5682 
5683 		if (gso)
5684 			dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
5685 		/* (!csum && gso) case will be fixed by register_netdev() */
5686 	}
5687 
5688 	/* 1. With VIRTIO_NET_F_GUEST_CSUM negotiation, the driver doesn't
5689 	 * need to calculate checksums for partially checksummed packets,
5690 	 * as they're considered valid by the upper layer.
5691 	 * 2. Without VIRTIO_NET_F_GUEST_CSUM negotiation, the driver only
5692 	 * receives fully checksummed packets. The device may assist in
5693 	 * validating these packets' checksums, so the driver won't have to.
5694 	 */
5695 	dev->features |= NETIF_F_RXCSUM;
5696 
5697 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
5698 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
5699 		dev->features |= NETIF_F_GRO_HW;
5700 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
5701 		dev->hw_features |= NETIF_F_GRO_HW;
5702 
5703 	dev->vlan_features = dev->features;
5704 	dev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT;
5705 
5706 	/* MTU range: 68 - 65535 */
5707 	dev->min_mtu = MIN_MTU;
5708 	dev->max_mtu = MAX_MTU;
5709 
5710 	/* Configuration may specify what MAC to use.  Otherwise random. */
5711 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
5712 		u8 addr[ETH_ALEN];
5713 
5714 		virtio_cread_bytes(vdev,
5715 				   offsetof(struct virtio_net_config, mac),
5716 				   addr, ETH_ALEN);
5717 		eth_hw_addr_set(dev, addr);
5718 	} else {
5719 		eth_hw_addr_random(dev);
5720 		dev_info(&vdev->dev, "Assigned random MAC address %pM\n",
5721 			 dev->dev_addr);
5722 	}
5723 
5724 	/* Set up our device-specific information */
5725 	vi = netdev_priv(dev);
5726 	vi->dev = dev;
5727 	vi->vdev = vdev;
5728 	vdev->priv = vi;
5729 
5730 	INIT_WORK(&vi->config_work, virtnet_config_changed_work);
5731 	INIT_WORK(&vi->rx_mode_work, virtnet_rx_mode_work);
5732 	spin_lock_init(&vi->refill_lock);
5733 
5734 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) {
5735 		vi->mergeable_rx_bufs = true;
5736 		dev->xdp_features |= NETDEV_XDP_ACT_RX_SG;
5737 	}
5738 
5739 	if (virtio_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT))
5740 		vi->has_rss_hash_report = true;
5741 
5742 	if (virtio_has_feature(vdev, VIRTIO_NET_F_RSS)) {
5743 		vi->has_rss = true;
5744 
5745 		vi->rss_indir_table_size =
5746 			virtio_cread16(vdev, offsetof(struct virtio_net_config,
5747 				rss_max_indirection_table_length));
5748 	}
5749 
5750 	if (vi->has_rss || vi->has_rss_hash_report) {
5751 		vi->rss_key_size =
5752 			virtio_cread8(vdev, offsetof(struct virtio_net_config, rss_max_key_size));
5753 
5754 		vi->rss_hash_types_supported =
5755 		    virtio_cread32(vdev, offsetof(struct virtio_net_config, supported_hash_types));
5756 		vi->rss_hash_types_supported &=
5757 				~(VIRTIO_NET_RSS_HASH_TYPE_IP_EX |
5758 				  VIRTIO_NET_RSS_HASH_TYPE_TCP_EX |
5759 				  VIRTIO_NET_RSS_HASH_TYPE_UDP_EX);
5760 
5761 		dev->hw_features |= NETIF_F_RXHASH;
5762 		dev->xdp_metadata_ops = &virtnet_xdp_metadata_ops;
5763 	}
5764 
5765 	if (vi->has_rss_hash_report)
5766 		vi->hdr_len = sizeof(struct virtio_net_hdr_v1_hash);
5767 	else if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
5768 		 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
5769 		vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
5770 	else
5771 		vi->hdr_len = sizeof(struct virtio_net_hdr);
5772 
5773 	if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
5774 	    virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
5775 		vi->any_header_sg = true;
5776 
5777 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
5778 		vi->has_cvq = true;
5779 
5780 	mutex_init(&vi->cvq_lock);
5781 
5782 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
5783 		mtu = virtio_cread16(vdev,
5784 				     offsetof(struct virtio_net_config,
5785 					      mtu));
5786 		if (mtu < dev->min_mtu) {
5787 			/* Should never trigger: MTU was previously validated
5788 			 * in virtnet_validate.
5789 			 */
5790 			dev_err(&vdev->dev,
5791 				"device MTU appears to have changed it is now %d < %d",
5792 				mtu, dev->min_mtu);
5793 			err = -EINVAL;
5794 			goto free;
5795 		}
5796 
5797 		dev->mtu = mtu;
5798 		dev->max_mtu = mtu;
5799 	}
5800 
5801 	virtnet_set_big_packets(vi, mtu);
5802 
5803 	if (vi->any_header_sg)
5804 		dev->needed_headroom = vi->hdr_len;
5805 
5806 	/* Enable multiqueue by default */
5807 	if (num_online_cpus() >= max_queue_pairs)
5808 		vi->curr_queue_pairs = max_queue_pairs;
5809 	else
5810 		vi->curr_queue_pairs = num_online_cpus();
5811 	vi->max_queue_pairs = max_queue_pairs;
5812 
5813 	/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
5814 	err = init_vqs(vi);
5815 	if (err)
5816 		goto free;
5817 
5818 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
5819 		vi->intr_coal_rx.max_usecs = 0;
5820 		vi->intr_coal_tx.max_usecs = 0;
5821 		vi->intr_coal_rx.max_packets = 0;
5822 
5823 		/* Keep the default values of the coalescing parameters
5824 		 * aligned with the default napi_tx state.
5825 		 */
5826 		if (vi->sq[0].napi.weight)
5827 			vi->intr_coal_tx.max_packets = 1;
5828 		else
5829 			vi->intr_coal_tx.max_packets = 0;
5830 	}
5831 
5832 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_VQ_NOTF_COAL)) {
5833 		/* The reason is the same as VIRTIO_NET_F_NOTF_COAL. */
5834 		for (i = 0; i < vi->max_queue_pairs; i++)
5835 			if (vi->sq[i].napi.weight)
5836 				vi->sq[i].intr_coal.max_packets = 1;
5837 	}
5838 
5839 #ifdef CONFIG_SYSFS
5840 	if (vi->mergeable_rx_bufs)
5841 		dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
5842 #endif
5843 	netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
5844 	netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
5845 
5846 	virtnet_init_settings(dev);
5847 
5848 	if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
5849 		vi->failover = net_failover_create(vi->dev);
5850 		if (IS_ERR(vi->failover)) {
5851 			err = PTR_ERR(vi->failover);
5852 			goto free_vqs;
5853 		}
5854 	}
5855 
5856 	if (vi->has_rss || vi->has_rss_hash_report)
5857 		virtnet_init_default_rss(vi);
5858 
5859 	enable_rx_mode_work(vi);
5860 
5861 	/* serialize netdev register + virtio_device_ready() with ndo_open() */
5862 	rtnl_lock();
5863 
5864 	err = register_netdevice(dev);
5865 	if (err) {
5866 		pr_debug("virtio_net: registering device failed\n");
5867 		rtnl_unlock();
5868 		goto free_failover;
5869 	}
5870 
5871 	virtio_device_ready(vdev);
5872 
5873 	virtnet_set_queues(vi, vi->curr_queue_pairs);
5874 
5875 	/* a random MAC address has been assigned, notify the device.
5876 	 * We don't fail probe if VIRTIO_NET_F_CTRL_MAC_ADDR is not there
5877 	 * because many devices work fine without getting MAC explicitly
5878 	 */
5879 	if (!virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
5880 	    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
5881 		struct scatterlist sg;
5882 
5883 		sg_init_one(&sg, dev->dev_addr, dev->addr_len);
5884 		if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
5885 					  VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
5886 			pr_debug("virtio_net: setting MAC address failed\n");
5887 			rtnl_unlock();
5888 			err = -EINVAL;
5889 			goto free_unregister_netdev;
5890 		}
5891 	}
5892 
5893 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_DEVICE_STATS)) {
5894 		struct virtio_net_stats_capabilities *stats_cap  __free(kfree) = NULL;
5895 		struct scatterlist sg;
5896 		__le64 v;
5897 
5898 		stats_cap = kzalloc(sizeof(*stats_cap), GFP_KERNEL);
5899 		if (!stats_cap) {
5900 			rtnl_unlock();
5901 			err = -ENOMEM;
5902 			goto free_unregister_netdev;
5903 		}
5904 
5905 		sg_init_one(&sg, stats_cap, sizeof(*stats_cap));
5906 
5907 		if (!virtnet_send_command_reply(vi, VIRTIO_NET_CTRL_STATS,
5908 						VIRTIO_NET_CTRL_STATS_QUERY,
5909 						NULL, &sg)) {
5910 			pr_debug("virtio_net: fail to get stats capability\n");
5911 			rtnl_unlock();
5912 			err = -EINVAL;
5913 			goto free_unregister_netdev;
5914 		}
5915 
5916 		v = stats_cap->supported_stats_types[0];
5917 		vi->device_stats_cap = le64_to_cpu(v);
5918 	}
5919 
5920 	rtnl_unlock();
5921 
5922 	err = virtnet_cpu_notif_add(vi);
5923 	if (err) {
5924 		pr_debug("virtio_net: registering cpu notifier failed\n");
5925 		goto free_unregister_netdev;
5926 	}
5927 
5928 	/* Assume link up if device can't report link status,
5929 	   otherwise get link status from config. */
5930 	netif_carrier_off(dev);
5931 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
5932 		schedule_work(&vi->config_work);
5933 	} else {
5934 		vi->status = VIRTIO_NET_S_LINK_UP;
5935 		virtnet_update_settings(vi);
5936 		netif_carrier_on(dev);
5937 	}
5938 
5939 	for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
5940 		if (virtio_has_feature(vi->vdev, guest_offloads[i]))
5941 			set_bit(guest_offloads[i], &vi->guest_offloads);
5942 	vi->guest_offloads_capable = vi->guest_offloads;
5943 
5944 	pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
5945 		 dev->name, max_queue_pairs);
5946 
5947 	return 0;
5948 
5949 free_unregister_netdev:
5950 	unregister_netdev(dev);
5951 free_failover:
5952 	net_failover_destroy(vi->failover);
5953 free_vqs:
5954 	virtio_reset_device(vdev);
5955 	cancel_delayed_work_sync(&vi->refill);
5956 	free_receive_page_frags(vi);
5957 	virtnet_del_vqs(vi);
5958 free:
5959 	free_netdev(dev);
5960 	return err;
5961 }
5962 
5963 static void remove_vq_common(struct virtnet_info *vi)
5964 {
5965 	virtio_reset_device(vi->vdev);
5966 
5967 	/* Free unused buffers in both send and recv, if any. */
5968 	free_unused_bufs(vi);
5969 
5970 	free_receive_bufs(vi);
5971 
5972 	free_receive_page_frags(vi);
5973 
5974 	virtnet_del_vqs(vi);
5975 }
5976 
5977 static void virtnet_remove(struct virtio_device *vdev)
5978 {
5979 	struct virtnet_info *vi = vdev->priv;
5980 
5981 	virtnet_cpu_notif_remove(vi);
5982 
5983 	/* Make sure no work handler is accessing the device. */
5984 	flush_work(&vi->config_work);
5985 	disable_rx_mode_work(vi);
5986 	flush_work(&vi->rx_mode_work);
5987 
5988 	unregister_netdev(vi->dev);
5989 
5990 	net_failover_destroy(vi->failover);
5991 
5992 	remove_vq_common(vi);
5993 
5994 	free_netdev(vi->dev);
5995 }
5996 
5997 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
5998 {
5999 	struct virtnet_info *vi = vdev->priv;
6000 
6001 	virtnet_cpu_notif_remove(vi);
6002 	virtnet_freeze_down(vdev);
6003 	remove_vq_common(vi);
6004 
6005 	return 0;
6006 }
6007 
6008 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
6009 {
6010 	struct virtnet_info *vi = vdev->priv;
6011 	int err;
6012 
6013 	err = virtnet_restore_up(vdev);
6014 	if (err)
6015 		return err;
6016 	virtnet_set_queues(vi, vi->curr_queue_pairs);
6017 
6018 	err = virtnet_cpu_notif_add(vi);
6019 	if (err) {
6020 		virtnet_freeze_down(vdev);
6021 		remove_vq_common(vi);
6022 		return err;
6023 	}
6024 
6025 	return 0;
6026 }
6027 
6028 static struct virtio_device_id id_table[] = {
6029 	{ VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
6030 	{ 0 },
6031 };
6032 
6033 #define VIRTNET_FEATURES \
6034 	VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
6035 	VIRTIO_NET_F_MAC, \
6036 	VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
6037 	VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
6038 	VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
6039 	VIRTIO_NET_F_HOST_USO, VIRTIO_NET_F_GUEST_USO4, VIRTIO_NET_F_GUEST_USO6, \
6040 	VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
6041 	VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
6042 	VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
6043 	VIRTIO_NET_F_CTRL_MAC_ADDR, \
6044 	VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
6045 	VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY, \
6046 	VIRTIO_NET_F_RSS, VIRTIO_NET_F_HASH_REPORT, VIRTIO_NET_F_NOTF_COAL, \
6047 	VIRTIO_NET_F_VQ_NOTF_COAL, \
6048 	VIRTIO_NET_F_GUEST_HDRLEN, VIRTIO_NET_F_DEVICE_STATS
6049 
6050 static unsigned int features[] = {
6051 	VIRTNET_FEATURES,
6052 };
6053 
6054 static unsigned int features_legacy[] = {
6055 	VIRTNET_FEATURES,
6056 	VIRTIO_NET_F_GSO,
6057 	VIRTIO_F_ANY_LAYOUT,
6058 };
6059 
6060 static struct virtio_driver virtio_net_driver = {
6061 	.feature_table = features,
6062 	.feature_table_size = ARRAY_SIZE(features),
6063 	.feature_table_legacy = features_legacy,
6064 	.feature_table_size_legacy = ARRAY_SIZE(features_legacy),
6065 	.driver.name =	KBUILD_MODNAME,
6066 	.id_table =	id_table,
6067 	.validate =	virtnet_validate,
6068 	.probe =	virtnet_probe,
6069 	.remove =	virtnet_remove,
6070 	.config_changed = virtnet_config_changed,
6071 #ifdef CONFIG_PM_SLEEP
6072 	.freeze =	virtnet_freeze,
6073 	.restore =	virtnet_restore,
6074 #endif
6075 };
6076 
6077 static __init int virtio_net_driver_init(void)
6078 {
6079 	int ret;
6080 
6081 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
6082 				      virtnet_cpu_online,
6083 				      virtnet_cpu_down_prep);
6084 	if (ret < 0)
6085 		goto out;
6086 	virtionet_online = ret;
6087 	ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
6088 				      NULL, virtnet_cpu_dead);
6089 	if (ret)
6090 		goto err_dead;
6091 	ret = register_virtio_driver(&virtio_net_driver);
6092 	if (ret)
6093 		goto err_virtio;
6094 	return 0;
6095 err_virtio:
6096 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
6097 err_dead:
6098 	cpuhp_remove_multi_state(virtionet_online);
6099 out:
6100 	return ret;
6101 }
6102 module_init(virtio_net_driver_init);
6103 
6104 static __exit void virtio_net_driver_exit(void)
6105 {
6106 	unregister_virtio_driver(&virtio_net_driver);
6107 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
6108 	cpuhp_remove_multi_state(virtionet_online);
6109 }
6110 module_exit(virtio_net_driver_exit);
6111 
6112 MODULE_DEVICE_TABLE(virtio, id_table);
6113 MODULE_DESCRIPTION("Virtio network driver");
6114 MODULE_LICENSE("GPL");
6115