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