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