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