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