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