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