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