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