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