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