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