xref: /openbmc/linux/drivers/net/virtio_net.c (revision e9e3424d)
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 	/* We passed the address of virtnet header to virtio-core,
1273 	 * so truncate the padding.
1274 	 */
1275 	buf -= VIRTNET_RX_PAD + xdp_headroom;
1276 
1277 	len -= vi->hdr_len;
1278 	u64_stats_add(&stats->bytes, len);
1279 
1280 	if (unlikely(len > GOOD_PACKET_LEN)) {
1281 		pr_debug("%s: rx error: len %u exceeds max size %d\n",
1282 			 dev->name, len, GOOD_PACKET_LEN);
1283 		DEV_STATS_INC(dev, rx_length_errors);
1284 		goto err;
1285 	}
1286 
1287 	if (unlikely(vi->xdp_enabled)) {
1288 		struct bpf_prog *xdp_prog;
1289 
1290 		rcu_read_lock();
1291 		xdp_prog = rcu_dereference(rq->xdp_prog);
1292 		if (xdp_prog) {
1293 			skb = receive_small_xdp(dev, vi, rq, xdp_prog, buf,
1294 						xdp_headroom, len, xdp_xmit,
1295 						stats);
1296 			rcu_read_unlock();
1297 			return skb;
1298 		}
1299 		rcu_read_unlock();
1300 	}
1301 
1302 	skb = receive_small_build_skb(vi, xdp_headroom, buf, len);
1303 	if (likely(skb))
1304 		return skb;
1305 
1306 err:
1307 	u64_stats_inc(&stats->drops);
1308 	put_page(page);
1309 	return NULL;
1310 }
1311 
receive_big(struct net_device * dev,struct virtnet_info * vi,struct receive_queue * rq,void * buf,unsigned int len,struct virtnet_rq_stats * stats)1312 static struct sk_buff *receive_big(struct net_device *dev,
1313 				   struct virtnet_info *vi,
1314 				   struct receive_queue *rq,
1315 				   void *buf,
1316 				   unsigned int len,
1317 				   struct virtnet_rq_stats *stats)
1318 {
1319 	struct page *page = buf;
1320 	struct sk_buff *skb =
1321 		page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, 0);
1322 
1323 	u64_stats_add(&stats->bytes, len - vi->hdr_len);
1324 	if (unlikely(!skb))
1325 		goto err;
1326 
1327 	return skb;
1328 
1329 err:
1330 	u64_stats_inc(&stats->drops);
1331 	give_pages(rq, page);
1332 	return NULL;
1333 }
1334 
mergeable_buf_free(struct receive_queue * rq,int num_buf,struct net_device * dev,struct virtnet_rq_stats * stats)1335 static void mergeable_buf_free(struct receive_queue *rq, int num_buf,
1336 			       struct net_device *dev,
1337 			       struct virtnet_rq_stats *stats)
1338 {
1339 	struct page *page;
1340 	void *buf;
1341 	int len;
1342 
1343 	while (num_buf-- > 1) {
1344 		buf = virtnet_rq_get_buf(rq, &len, NULL);
1345 		if (unlikely(!buf)) {
1346 			pr_debug("%s: rx error: %d buffers missing\n",
1347 				 dev->name, num_buf);
1348 			DEV_STATS_INC(dev, rx_length_errors);
1349 			break;
1350 		}
1351 		u64_stats_add(&stats->bytes, len);
1352 		page = virt_to_head_page(buf);
1353 		put_page(page);
1354 	}
1355 }
1356 
1357 /* Why not use xdp_build_skb_from_frame() ?
1358  * XDP core assumes that xdp frags are PAGE_SIZE in length, while in
1359  * virtio-net there are 2 points that do not match its requirements:
1360  *  1. The size of the prefilled buffer is not fixed before xdp is set.
1361  *  2. xdp_build_skb_from_frame() does more checks that we don't need,
1362  *     like eth_type_trans() (which virtio-net does in receive_buf()).
1363  */
build_skb_from_xdp_buff(struct net_device * dev,struct virtnet_info * vi,struct xdp_buff * xdp,unsigned int xdp_frags_truesz)1364 static struct sk_buff *build_skb_from_xdp_buff(struct net_device *dev,
1365 					       struct virtnet_info *vi,
1366 					       struct xdp_buff *xdp,
1367 					       unsigned int xdp_frags_truesz)
1368 {
1369 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
1370 	unsigned int headroom, data_len;
1371 	struct sk_buff *skb;
1372 	int metasize;
1373 	u8 nr_frags;
1374 
1375 	if (unlikely(xdp->data_end > xdp_data_hard_end(xdp))) {
1376 		pr_debug("Error building skb as missing reserved tailroom for xdp");
1377 		return NULL;
1378 	}
1379 
1380 	if (unlikely(xdp_buff_has_frags(xdp)))
1381 		nr_frags = sinfo->nr_frags;
1382 
1383 	skb = build_skb(xdp->data_hard_start, xdp->frame_sz);
1384 	if (unlikely(!skb))
1385 		return NULL;
1386 
1387 	headroom = xdp->data - xdp->data_hard_start;
1388 	data_len = xdp->data_end - xdp->data;
1389 	skb_reserve(skb, headroom);
1390 	__skb_put(skb, data_len);
1391 
1392 	metasize = xdp->data - xdp->data_meta;
1393 	metasize = metasize > 0 ? metasize : 0;
1394 	if (metasize)
1395 		skb_metadata_set(skb, metasize);
1396 
1397 	if (unlikely(xdp_buff_has_frags(xdp)))
1398 		xdp_update_skb_shared_info(skb, nr_frags,
1399 					   sinfo->xdp_frags_size,
1400 					   xdp_frags_truesz,
1401 					   xdp_buff_is_frag_pfmemalloc(xdp));
1402 
1403 	return skb;
1404 }
1405 
1406 /* 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)1407 static int virtnet_build_xdp_buff_mrg(struct net_device *dev,
1408 				      struct virtnet_info *vi,
1409 				      struct receive_queue *rq,
1410 				      struct xdp_buff *xdp,
1411 				      void *buf,
1412 				      unsigned int len,
1413 				      unsigned int frame_sz,
1414 				      int *num_buf,
1415 				      unsigned int *xdp_frags_truesize,
1416 				      struct virtnet_rq_stats *stats)
1417 {
1418 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1419 	unsigned int headroom, tailroom, room;
1420 	unsigned int truesize, cur_frag_size;
1421 	struct skb_shared_info *shinfo;
1422 	unsigned int xdp_frags_truesz = 0;
1423 	struct page *page;
1424 	skb_frag_t *frag;
1425 	int offset;
1426 	void *ctx;
1427 
1428 	xdp_init_buff(xdp, frame_sz, &rq->xdp_rxq);
1429 	xdp_prepare_buff(xdp, buf - VIRTIO_XDP_HEADROOM,
1430 			 VIRTIO_XDP_HEADROOM + vi->hdr_len, len - vi->hdr_len, true);
1431 
1432 	if (!*num_buf)
1433 		return 0;
1434 
1435 	if (*num_buf > 1) {
1436 		/* If we want to build multi-buffer xdp, we need
1437 		 * to specify that the flags of xdp_buff have the
1438 		 * XDP_FLAGS_HAS_FRAG bit.
1439 		 */
1440 		if (!xdp_buff_has_frags(xdp))
1441 			xdp_buff_set_frags_flag(xdp);
1442 
1443 		shinfo = xdp_get_shared_info_from_buff(xdp);
1444 		shinfo->nr_frags = 0;
1445 		shinfo->xdp_frags_size = 0;
1446 	}
1447 
1448 	if (*num_buf > MAX_SKB_FRAGS + 1)
1449 		return -EINVAL;
1450 
1451 	while (--*num_buf > 0) {
1452 		buf = virtnet_rq_get_buf(rq, &len, &ctx);
1453 		if (unlikely(!buf)) {
1454 			pr_debug("%s: rx error: %d buffers out of %d missing\n",
1455 				 dev->name, *num_buf,
1456 				 virtio16_to_cpu(vi->vdev, hdr->num_buffers));
1457 			DEV_STATS_INC(dev, rx_length_errors);
1458 			goto err;
1459 		}
1460 
1461 		u64_stats_add(&stats->bytes, len);
1462 		page = virt_to_head_page(buf);
1463 		offset = buf - page_address(page);
1464 
1465 		truesize = mergeable_ctx_to_truesize(ctx);
1466 		headroom = mergeable_ctx_to_headroom(ctx);
1467 		tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1468 		room = SKB_DATA_ALIGN(headroom + tailroom);
1469 
1470 		cur_frag_size = truesize;
1471 		xdp_frags_truesz += cur_frag_size;
1472 		if (unlikely(len > truesize - room || cur_frag_size > PAGE_SIZE)) {
1473 			put_page(page);
1474 			pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1475 				 dev->name, len, (unsigned long)(truesize - room));
1476 			DEV_STATS_INC(dev, rx_length_errors);
1477 			goto err;
1478 		}
1479 
1480 		frag = &shinfo->frags[shinfo->nr_frags++];
1481 		skb_frag_fill_page_desc(frag, page, offset, len);
1482 		if (page_is_pfmemalloc(page))
1483 			xdp_buff_set_frag_pfmemalloc(xdp);
1484 
1485 		shinfo->xdp_frags_size += len;
1486 	}
1487 
1488 	*xdp_frags_truesize = xdp_frags_truesz;
1489 	return 0;
1490 
1491 err:
1492 	put_xdp_frags(xdp);
1493 	return -EINVAL;
1494 }
1495 
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)1496 static void *mergeable_xdp_get_buf(struct virtnet_info *vi,
1497 				   struct receive_queue *rq,
1498 				   struct bpf_prog *xdp_prog,
1499 				   void *ctx,
1500 				   unsigned int *frame_sz,
1501 				   int *num_buf,
1502 				   struct page **page,
1503 				   int offset,
1504 				   unsigned int *len,
1505 				   struct virtio_net_hdr_mrg_rxbuf *hdr)
1506 {
1507 	unsigned int truesize = mergeable_ctx_to_truesize(ctx);
1508 	unsigned int headroom = mergeable_ctx_to_headroom(ctx);
1509 	struct page *xdp_page;
1510 	unsigned int xdp_room;
1511 
1512 	/* Transient failure which in theory could occur if
1513 	 * in-flight packets from before XDP was enabled reach
1514 	 * the receive path after XDP is loaded.
1515 	 */
1516 	if (unlikely(hdr->hdr.gso_type))
1517 		return NULL;
1518 
1519 	/* Partially checksummed packets must be dropped. */
1520 	if (unlikely(hdr->hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM))
1521 		return NULL;
1522 
1523 	/* Now XDP core assumes frag size is PAGE_SIZE, but buffers
1524 	 * with headroom may add hole in truesize, which
1525 	 * make their length exceed PAGE_SIZE. So we disabled the
1526 	 * hole mechanism for xdp. See add_recvbuf_mergeable().
1527 	 */
1528 	*frame_sz = truesize;
1529 
1530 	if (likely(headroom >= virtnet_get_headroom(vi) &&
1531 		   (*num_buf == 1 || xdp_prog->aux->xdp_has_frags))) {
1532 		return page_address(*page) + offset;
1533 	}
1534 
1535 	/* This happens when headroom is not enough because
1536 	 * of the buffer was prefilled before XDP is set.
1537 	 * This should only happen for the first several packets.
1538 	 * In fact, vq reset can be used here to help us clean up
1539 	 * the prefilled buffers, but many existing devices do not
1540 	 * support it, and we don't want to bother users who are
1541 	 * using xdp normally.
1542 	 */
1543 	if (!xdp_prog->aux->xdp_has_frags) {
1544 		/* linearize data for XDP */
1545 		xdp_page = xdp_linearize_page(rq, num_buf,
1546 					      *page, offset,
1547 					      VIRTIO_XDP_HEADROOM,
1548 					      len);
1549 		if (!xdp_page)
1550 			return NULL;
1551 	} else {
1552 		xdp_room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
1553 					  sizeof(struct skb_shared_info));
1554 		if (*len + xdp_room > PAGE_SIZE)
1555 			return NULL;
1556 
1557 		xdp_page = alloc_page(GFP_ATOMIC);
1558 		if (!xdp_page)
1559 			return NULL;
1560 
1561 		memcpy(page_address(xdp_page) + VIRTIO_XDP_HEADROOM,
1562 		       page_address(*page) + offset, *len);
1563 	}
1564 
1565 	*frame_sz = PAGE_SIZE;
1566 
1567 	put_page(*page);
1568 
1569 	*page = xdp_page;
1570 
1571 	return page_address(*page) + VIRTIO_XDP_HEADROOM;
1572 }
1573 
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)1574 static struct sk_buff *receive_mergeable_xdp(struct net_device *dev,
1575 					     struct virtnet_info *vi,
1576 					     struct receive_queue *rq,
1577 					     struct bpf_prog *xdp_prog,
1578 					     void *buf,
1579 					     void *ctx,
1580 					     unsigned int len,
1581 					     unsigned int *xdp_xmit,
1582 					     struct virtnet_rq_stats *stats)
1583 {
1584 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1585 	int num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
1586 	struct page *page = virt_to_head_page(buf);
1587 	int offset = buf - page_address(page);
1588 	unsigned int xdp_frags_truesz = 0;
1589 	struct sk_buff *head_skb;
1590 	unsigned int frame_sz;
1591 	struct xdp_buff xdp;
1592 	void *data;
1593 	u32 act;
1594 	int err;
1595 
1596 	data = mergeable_xdp_get_buf(vi, rq, xdp_prog, ctx, &frame_sz, &num_buf, &page,
1597 				     offset, &len, hdr);
1598 	if (unlikely(!data))
1599 		goto err_xdp;
1600 
1601 	err = virtnet_build_xdp_buff_mrg(dev, vi, rq, &xdp, data, len, frame_sz,
1602 					 &num_buf, &xdp_frags_truesz, stats);
1603 	if (unlikely(err))
1604 		goto err_xdp;
1605 
1606 	act = virtnet_xdp_handler(xdp_prog, &xdp, dev, xdp_xmit, stats);
1607 
1608 	switch (act) {
1609 	case XDP_PASS:
1610 		head_skb = build_skb_from_xdp_buff(dev, vi, &xdp, xdp_frags_truesz);
1611 		if (unlikely(!head_skb))
1612 			break;
1613 		return head_skb;
1614 
1615 	case XDP_TX:
1616 	case XDP_REDIRECT:
1617 		return NULL;
1618 
1619 	default:
1620 		break;
1621 	}
1622 
1623 	put_xdp_frags(&xdp);
1624 
1625 err_xdp:
1626 	put_page(page);
1627 	mergeable_buf_free(rq, num_buf, dev, stats);
1628 
1629 	u64_stats_inc(&stats->xdp_drops);
1630 	u64_stats_inc(&stats->drops);
1631 	return NULL;
1632 }
1633 
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)1634 static struct sk_buff *receive_mergeable(struct net_device *dev,
1635 					 struct virtnet_info *vi,
1636 					 struct receive_queue *rq,
1637 					 void *buf,
1638 					 void *ctx,
1639 					 unsigned int len,
1640 					 unsigned int *xdp_xmit,
1641 					 struct virtnet_rq_stats *stats)
1642 {
1643 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1644 	int num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
1645 	struct page *page = virt_to_head_page(buf);
1646 	int offset = buf - page_address(page);
1647 	struct sk_buff *head_skb, *curr_skb;
1648 	unsigned int truesize = mergeable_ctx_to_truesize(ctx);
1649 	unsigned int headroom = mergeable_ctx_to_headroom(ctx);
1650 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1651 	unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1652 
1653 	head_skb = NULL;
1654 	u64_stats_add(&stats->bytes, len - vi->hdr_len);
1655 
1656 	if (unlikely(len > truesize - room)) {
1657 		pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1658 			 dev->name, len, (unsigned long)(truesize - room));
1659 		DEV_STATS_INC(dev, rx_length_errors);
1660 		goto err_skb;
1661 	}
1662 
1663 	if (unlikely(vi->xdp_enabled)) {
1664 		struct bpf_prog *xdp_prog;
1665 
1666 		rcu_read_lock();
1667 		xdp_prog = rcu_dereference(rq->xdp_prog);
1668 		if (xdp_prog) {
1669 			head_skb = receive_mergeable_xdp(dev, vi, rq, xdp_prog, buf, ctx,
1670 							 len, xdp_xmit, stats);
1671 			rcu_read_unlock();
1672 			return head_skb;
1673 		}
1674 		rcu_read_unlock();
1675 	}
1676 
1677 	head_skb = page_to_skb(vi, rq, page, offset, len, truesize, headroom);
1678 	curr_skb = head_skb;
1679 
1680 	if (unlikely(!curr_skb))
1681 		goto err_skb;
1682 	while (--num_buf) {
1683 		int num_skb_frags;
1684 
1685 		buf = virtnet_rq_get_buf(rq, &len, &ctx);
1686 		if (unlikely(!buf)) {
1687 			pr_debug("%s: rx error: %d buffers out of %d missing\n",
1688 				 dev->name, num_buf,
1689 				 virtio16_to_cpu(vi->vdev,
1690 						 hdr->num_buffers));
1691 			DEV_STATS_INC(dev, rx_length_errors);
1692 			goto err_buf;
1693 		}
1694 
1695 		u64_stats_add(&stats->bytes, len);
1696 		page = virt_to_head_page(buf);
1697 
1698 		truesize = mergeable_ctx_to_truesize(ctx);
1699 		headroom = mergeable_ctx_to_headroom(ctx);
1700 		tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1701 		room = SKB_DATA_ALIGN(headroom + tailroom);
1702 		if (unlikely(len > truesize - room)) {
1703 			pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1704 				 dev->name, len, (unsigned long)(truesize - room));
1705 			DEV_STATS_INC(dev, rx_length_errors);
1706 			goto err_skb;
1707 		}
1708 
1709 		num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1710 		if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1711 			struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1712 
1713 			if (unlikely(!nskb))
1714 				goto err_skb;
1715 			if (curr_skb == head_skb)
1716 				skb_shinfo(curr_skb)->frag_list = nskb;
1717 			else
1718 				curr_skb->next = nskb;
1719 			curr_skb = nskb;
1720 			head_skb->truesize += nskb->truesize;
1721 			num_skb_frags = 0;
1722 		}
1723 		if (curr_skb != head_skb) {
1724 			head_skb->data_len += len;
1725 			head_skb->len += len;
1726 			head_skb->truesize += truesize;
1727 		}
1728 		offset = buf - page_address(page);
1729 		if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1730 			put_page(page);
1731 			skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1732 					     len, truesize);
1733 		} else {
1734 			skb_add_rx_frag(curr_skb, num_skb_frags, page,
1735 					offset, len, truesize);
1736 		}
1737 	}
1738 
1739 	ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1740 	return head_skb;
1741 
1742 err_skb:
1743 	put_page(page);
1744 	mergeable_buf_free(rq, num_buf, dev, stats);
1745 
1746 err_buf:
1747 	u64_stats_inc(&stats->drops);
1748 	dev_kfree_skb(head_skb);
1749 	return NULL;
1750 }
1751 
virtio_skb_set_hash(const struct virtio_net_hdr_v1_hash * hdr_hash,struct sk_buff * skb)1752 static void virtio_skb_set_hash(const struct virtio_net_hdr_v1_hash *hdr_hash,
1753 				struct sk_buff *skb)
1754 {
1755 	enum pkt_hash_types rss_hash_type;
1756 
1757 	if (!hdr_hash || !skb)
1758 		return;
1759 
1760 	switch (__le16_to_cpu(hdr_hash->hash_report)) {
1761 	case VIRTIO_NET_HASH_REPORT_TCPv4:
1762 	case VIRTIO_NET_HASH_REPORT_UDPv4:
1763 	case VIRTIO_NET_HASH_REPORT_TCPv6:
1764 	case VIRTIO_NET_HASH_REPORT_UDPv6:
1765 	case VIRTIO_NET_HASH_REPORT_TCPv6_EX:
1766 	case VIRTIO_NET_HASH_REPORT_UDPv6_EX:
1767 		rss_hash_type = PKT_HASH_TYPE_L4;
1768 		break;
1769 	case VIRTIO_NET_HASH_REPORT_IPv4:
1770 	case VIRTIO_NET_HASH_REPORT_IPv6:
1771 	case VIRTIO_NET_HASH_REPORT_IPv6_EX:
1772 		rss_hash_type = PKT_HASH_TYPE_L3;
1773 		break;
1774 	case VIRTIO_NET_HASH_REPORT_NONE:
1775 	default:
1776 		rss_hash_type = PKT_HASH_TYPE_NONE;
1777 	}
1778 	skb_set_hash(skb, __le32_to_cpu(hdr_hash->hash_value), rss_hash_type);
1779 }
1780 
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)1781 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1782 			void *buf, unsigned int len, void **ctx,
1783 			unsigned int *xdp_xmit,
1784 			struct virtnet_rq_stats *stats)
1785 {
1786 	struct net_device *dev = vi->dev;
1787 	struct sk_buff *skb;
1788 	struct virtio_net_common_hdr *hdr;
1789 	u8 flags;
1790 
1791 	if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1792 		pr_debug("%s: short packet %i\n", dev->name, len);
1793 		DEV_STATS_INC(dev, rx_length_errors);
1794 		virtnet_rq_free_buf(vi, rq, buf);
1795 		return;
1796 	}
1797 
1798 	/* 1. Save the flags early, as the XDP program might overwrite them.
1799 	 * These flags ensure packets marked as VIRTIO_NET_HDR_F_DATA_VALID
1800 	 * stay valid after XDP processing.
1801 	 * 2. XDP doesn't work with partially checksummed packets (refer to
1802 	 * virtnet_xdp_set()), so packets marked as
1803 	 * VIRTIO_NET_HDR_F_NEEDS_CSUM get dropped during XDP processing.
1804 	 */
1805 	flags = ((struct virtio_net_common_hdr *)buf)->hdr.flags;
1806 
1807 	if (vi->mergeable_rx_bufs)
1808 		skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1809 					stats);
1810 	else if (vi->big_packets)
1811 		skb = receive_big(dev, vi, rq, buf, len, stats);
1812 	else
1813 		skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1814 
1815 	if (unlikely(!skb))
1816 		return;
1817 
1818 	hdr = skb_vnet_common_hdr(skb);
1819 	if (dev->features & NETIF_F_RXHASH && vi->has_rss_hash_report)
1820 		virtio_skb_set_hash(&hdr->hash_v1_hdr, skb);
1821 
1822 	if (flags & VIRTIO_NET_HDR_F_DATA_VALID)
1823 		skb->ip_summed = CHECKSUM_UNNECESSARY;
1824 
1825 	if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1826 				  virtio_is_little_endian(vi->vdev))) {
1827 		net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1828 				     dev->name, hdr->hdr.gso_type,
1829 				     hdr->hdr.gso_size);
1830 		goto frame_err;
1831 	}
1832 
1833 	skb_record_rx_queue(skb, vq2rxq(rq->vq));
1834 	skb->protocol = eth_type_trans(skb, dev);
1835 	pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1836 		 ntohs(skb->protocol), skb->len, skb->pkt_type);
1837 
1838 	napi_gro_receive(&rq->napi, skb);
1839 	return;
1840 
1841 frame_err:
1842 	DEV_STATS_INC(dev, rx_frame_errors);
1843 	dev_kfree_skb(skb);
1844 }
1845 
1846 /* Unlike mergeable buffers, all buffers are allocated to the
1847  * same size, except for the headroom. For this reason we do
1848  * not need to use  mergeable_len_to_ctx here - it is enough
1849  * to store the headroom as the context ignoring the truesize.
1850  */
add_recvbuf_small(struct virtnet_info * vi,struct receive_queue * rq,gfp_t gfp)1851 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1852 			     gfp_t gfp)
1853 {
1854 	char *buf;
1855 	unsigned int xdp_headroom = virtnet_get_headroom(vi);
1856 	void *ctx = (void *)(unsigned long)xdp_headroom;
1857 	int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1858 	int err;
1859 
1860 	len = SKB_DATA_ALIGN(len) +
1861 	      SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1862 
1863 	buf = virtnet_rq_alloc(rq, len, gfp);
1864 	if (unlikely(!buf))
1865 		return -ENOMEM;
1866 
1867 	buf += VIRTNET_RX_PAD + xdp_headroom;
1868 
1869 	virtnet_rq_init_one_sg(rq, buf, vi->hdr_len + GOOD_PACKET_LEN);
1870 
1871 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1872 	if (err < 0) {
1873 		if (rq->do_dma)
1874 			virtnet_rq_unmap(rq, buf, 0);
1875 		put_page(virt_to_head_page(buf));
1876 	}
1877 
1878 	return err;
1879 }
1880 
add_recvbuf_big(struct virtnet_info * vi,struct receive_queue * rq,gfp_t gfp)1881 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1882 			   gfp_t gfp)
1883 {
1884 	struct page *first, *list = NULL;
1885 	char *p;
1886 	int i, err, offset;
1887 
1888 	sg_init_table(rq->sg, vi->big_packets_num_skbfrags + 2);
1889 
1890 	/* page in rq->sg[vi->big_packets_num_skbfrags + 1] is list tail */
1891 	for (i = vi->big_packets_num_skbfrags + 1; i > 1; --i) {
1892 		first = get_a_page(rq, gfp);
1893 		if (!first) {
1894 			if (list)
1895 				give_pages(rq, list);
1896 			return -ENOMEM;
1897 		}
1898 		sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1899 
1900 		/* chain new page in list head to match sg */
1901 		first->private = (unsigned long)list;
1902 		list = first;
1903 	}
1904 
1905 	first = get_a_page(rq, gfp);
1906 	if (!first) {
1907 		give_pages(rq, list);
1908 		return -ENOMEM;
1909 	}
1910 	p = page_address(first);
1911 
1912 	/* rq->sg[0], rq->sg[1] share the same page */
1913 	/* a separated rq->sg[0] for header - required in case !any_header_sg */
1914 	sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1915 
1916 	/* rq->sg[1] for data packet, from offset */
1917 	offset = sizeof(struct padded_vnet_hdr);
1918 	sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1919 
1920 	/* chain first in list head */
1921 	first->private = (unsigned long)list;
1922 	err = virtqueue_add_inbuf(rq->vq, rq->sg, vi->big_packets_num_skbfrags + 2,
1923 				  first, gfp);
1924 	if (err < 0)
1925 		give_pages(rq, first);
1926 
1927 	return err;
1928 }
1929 
get_mergeable_buf_len(struct receive_queue * rq,struct ewma_pkt_len * avg_pkt_len,unsigned int room)1930 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1931 					  struct ewma_pkt_len *avg_pkt_len,
1932 					  unsigned int room)
1933 {
1934 	struct virtnet_info *vi = rq->vq->vdev->priv;
1935 	const size_t hdr_len = vi->hdr_len;
1936 	unsigned int len;
1937 
1938 	if (room)
1939 		return PAGE_SIZE - room;
1940 
1941 	len = hdr_len +	clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1942 				rq->min_buf_len, PAGE_SIZE - hdr_len);
1943 
1944 	return ALIGN(len, L1_CACHE_BYTES);
1945 }
1946 
add_recvbuf_mergeable(struct virtnet_info * vi,struct receive_queue * rq,gfp_t gfp)1947 static int add_recvbuf_mergeable(struct virtnet_info *vi,
1948 				 struct receive_queue *rq, gfp_t gfp)
1949 {
1950 	struct page_frag *alloc_frag = &rq->alloc_frag;
1951 	unsigned int headroom = virtnet_get_headroom(vi);
1952 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1953 	unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1954 	unsigned int len, hole;
1955 	void *ctx;
1956 	char *buf;
1957 	int err;
1958 
1959 	/* Extra tailroom is needed to satisfy XDP's assumption. This
1960 	 * means rx frags coalescing won't work, but consider we've
1961 	 * disabled GSO for XDP, it won't be a big issue.
1962 	 */
1963 	len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1964 
1965 	buf = virtnet_rq_alloc(rq, len + room, gfp);
1966 	if (unlikely(!buf))
1967 		return -ENOMEM;
1968 
1969 	buf += headroom; /* advance address leaving hole at front of pkt */
1970 	hole = alloc_frag->size - alloc_frag->offset;
1971 	if (hole < len + room) {
1972 		/* To avoid internal fragmentation, if there is very likely not
1973 		 * enough space for another buffer, add the remaining space to
1974 		 * the current buffer.
1975 		 * XDP core assumes that frame_size of xdp_buff and the length
1976 		 * of the frag are PAGE_SIZE, so we disable the hole mechanism.
1977 		 */
1978 		if (!headroom)
1979 			len += hole;
1980 		alloc_frag->offset += hole;
1981 	}
1982 
1983 	virtnet_rq_init_one_sg(rq, buf, len);
1984 
1985 	ctx = mergeable_len_to_ctx(len + room, headroom);
1986 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1987 	if (err < 0) {
1988 		if (rq->do_dma)
1989 			virtnet_rq_unmap(rq, buf, 0);
1990 		put_page(virt_to_head_page(buf));
1991 	}
1992 
1993 	return err;
1994 }
1995 
1996 /*
1997  * Returns false if we couldn't fill entirely (OOM).
1998  *
1999  * Normally run in the receive path, but can also be run from ndo_open
2000  * before we're receiving packets, or from refill_work which is
2001  * careful to disable receiving (using napi_disable).
2002  */
try_fill_recv(struct virtnet_info * vi,struct receive_queue * rq,gfp_t gfp)2003 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
2004 			  gfp_t gfp)
2005 {
2006 	int err;
2007 	bool oom;
2008 
2009 	do {
2010 		if (vi->mergeable_rx_bufs)
2011 			err = add_recvbuf_mergeable(vi, rq, gfp);
2012 		else if (vi->big_packets)
2013 			err = add_recvbuf_big(vi, rq, gfp);
2014 		else
2015 			err = add_recvbuf_small(vi, rq, gfp);
2016 
2017 		oom = err == -ENOMEM;
2018 		if (err)
2019 			break;
2020 	} while (rq->vq->num_free);
2021 	if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
2022 		unsigned long flags;
2023 
2024 		flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
2025 		u64_stats_inc(&rq->stats.kicks);
2026 		u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
2027 	}
2028 
2029 	return !oom;
2030 }
2031 
skb_recv_done(struct virtqueue * rvq)2032 static void skb_recv_done(struct virtqueue *rvq)
2033 {
2034 	struct virtnet_info *vi = rvq->vdev->priv;
2035 	struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
2036 
2037 	virtqueue_napi_schedule(&rq->napi, rvq);
2038 }
2039 
virtnet_napi_enable(struct virtqueue * vq,struct napi_struct * napi)2040 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
2041 {
2042 	napi_enable(napi);
2043 
2044 	/* If all buffers were filled by other side before we napi_enabled, we
2045 	 * won't get another interrupt, so process any outstanding packets now.
2046 	 * Call local_bh_enable after to trigger softIRQ processing.
2047 	 */
2048 	local_bh_disable();
2049 	virtqueue_napi_schedule(napi, vq);
2050 	local_bh_enable();
2051 }
2052 
virtnet_napi_tx_enable(struct virtnet_info * vi,struct virtqueue * vq,struct napi_struct * napi)2053 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
2054 				   struct virtqueue *vq,
2055 				   struct napi_struct *napi)
2056 {
2057 	if (!napi->weight)
2058 		return;
2059 
2060 	/* Tx napi touches cachelines on the cpu handling tx interrupts. Only
2061 	 * enable the feature if this is likely affine with the transmit path.
2062 	 */
2063 	if (!vi->affinity_hint_set) {
2064 		napi->weight = 0;
2065 		return;
2066 	}
2067 
2068 	return virtnet_napi_enable(vq, napi);
2069 }
2070 
virtnet_napi_tx_disable(struct napi_struct * napi)2071 static void virtnet_napi_tx_disable(struct napi_struct *napi)
2072 {
2073 	if (napi->weight)
2074 		napi_disable(napi);
2075 }
2076 
refill_work(struct work_struct * work)2077 static void refill_work(struct work_struct *work)
2078 {
2079 	struct virtnet_info *vi =
2080 		container_of(work, struct virtnet_info, refill.work);
2081 	bool still_empty;
2082 	int i;
2083 
2084 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2085 		struct receive_queue *rq = &vi->rq[i];
2086 
2087 		napi_disable(&rq->napi);
2088 		still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
2089 		virtnet_napi_enable(rq->vq, &rq->napi);
2090 
2091 		/* In theory, this can happen: if we don't get any buffers in
2092 		 * we will *never* try to fill again.
2093 		 */
2094 		if (still_empty)
2095 			schedule_delayed_work(&vi->refill, HZ/2);
2096 	}
2097 }
2098 
virtnet_receive(struct receive_queue * rq,int budget,unsigned int * xdp_xmit)2099 static int virtnet_receive(struct receive_queue *rq, int budget,
2100 			   unsigned int *xdp_xmit)
2101 {
2102 	struct virtnet_info *vi = rq->vq->vdev->priv;
2103 	struct virtnet_rq_stats stats = {};
2104 	unsigned int len;
2105 	int packets = 0;
2106 	void *buf;
2107 	int i;
2108 
2109 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
2110 		void *ctx;
2111 
2112 		while (packets < budget &&
2113 		       (buf = virtnet_rq_get_buf(rq, &len, &ctx))) {
2114 			receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
2115 			packets++;
2116 		}
2117 	} else {
2118 		while (packets < budget &&
2119 		       (buf = virtnet_rq_get_buf(rq, &len, NULL)) != NULL) {
2120 			receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
2121 			packets++;
2122 		}
2123 	}
2124 
2125 	if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
2126 		if (!try_fill_recv(vi, rq, GFP_ATOMIC)) {
2127 			spin_lock(&vi->refill_lock);
2128 			if (vi->refill_enabled)
2129 				schedule_delayed_work(&vi->refill, 0);
2130 			spin_unlock(&vi->refill_lock);
2131 		}
2132 	}
2133 
2134 	u64_stats_set(&stats.packets, packets);
2135 	u64_stats_update_begin(&rq->stats.syncp);
2136 	for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
2137 		size_t offset = virtnet_rq_stats_desc[i].offset;
2138 		u64_stats_t *item, *src;
2139 
2140 		item = (u64_stats_t *)((u8 *)&rq->stats + offset);
2141 		src = (u64_stats_t *)((u8 *)&stats + offset);
2142 		u64_stats_add(item, u64_stats_read(src));
2143 	}
2144 	u64_stats_update_end(&rq->stats.syncp);
2145 
2146 	return packets;
2147 }
2148 
virtnet_poll_cleantx(struct receive_queue * rq,int budget)2149 static void virtnet_poll_cleantx(struct receive_queue *rq, int budget)
2150 {
2151 	struct virtnet_info *vi = rq->vq->vdev->priv;
2152 	unsigned int index = vq2rxq(rq->vq);
2153 	struct send_queue *sq = &vi->sq[index];
2154 	struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
2155 
2156 	if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
2157 		return;
2158 
2159 	if (__netif_tx_trylock(txq)) {
2160 		if (sq->reset) {
2161 			__netif_tx_unlock(txq);
2162 			return;
2163 		}
2164 
2165 		do {
2166 			virtqueue_disable_cb(sq->vq);
2167 			free_old_xmit_skbs(sq, !!budget);
2168 		} while (unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
2169 
2170 		if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
2171 			netif_tx_wake_queue(txq);
2172 
2173 		__netif_tx_unlock(txq);
2174 	}
2175 }
2176 
virtnet_poll(struct napi_struct * napi,int budget)2177 static int virtnet_poll(struct napi_struct *napi, int budget)
2178 {
2179 	struct receive_queue *rq =
2180 		container_of(napi, struct receive_queue, napi);
2181 	struct virtnet_info *vi = rq->vq->vdev->priv;
2182 	struct send_queue *sq;
2183 	unsigned int received;
2184 	unsigned int xdp_xmit = 0;
2185 
2186 	virtnet_poll_cleantx(rq, budget);
2187 
2188 	received = virtnet_receive(rq, budget, &xdp_xmit);
2189 
2190 	if (xdp_xmit & VIRTIO_XDP_REDIR)
2191 		xdp_do_flush();
2192 
2193 	/* Out of packets? */
2194 	if (received < budget)
2195 		virtqueue_napi_complete(napi, rq->vq, received);
2196 
2197 	if (xdp_xmit & VIRTIO_XDP_TX) {
2198 		sq = virtnet_xdp_get_sq(vi);
2199 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
2200 			u64_stats_update_begin(&sq->stats.syncp);
2201 			u64_stats_inc(&sq->stats.kicks);
2202 			u64_stats_update_end(&sq->stats.syncp);
2203 		}
2204 		virtnet_xdp_put_sq(vi, sq);
2205 	}
2206 
2207 	return received;
2208 }
2209 
virtnet_disable_queue_pair(struct virtnet_info * vi,int qp_index)2210 static void virtnet_disable_queue_pair(struct virtnet_info *vi, int qp_index)
2211 {
2212 	virtnet_napi_tx_disable(&vi->sq[qp_index].napi);
2213 	napi_disable(&vi->rq[qp_index].napi);
2214 	xdp_rxq_info_unreg(&vi->rq[qp_index].xdp_rxq);
2215 }
2216 
virtnet_enable_queue_pair(struct virtnet_info * vi,int qp_index)2217 static int virtnet_enable_queue_pair(struct virtnet_info *vi, int qp_index)
2218 {
2219 	struct net_device *dev = vi->dev;
2220 	int err;
2221 
2222 	err = xdp_rxq_info_reg(&vi->rq[qp_index].xdp_rxq, dev, qp_index,
2223 			       vi->rq[qp_index].napi.napi_id);
2224 	if (err < 0)
2225 		return err;
2226 
2227 	err = xdp_rxq_info_reg_mem_model(&vi->rq[qp_index].xdp_rxq,
2228 					 MEM_TYPE_PAGE_SHARED, NULL);
2229 	if (err < 0)
2230 		goto err_xdp_reg_mem_model;
2231 
2232 	virtnet_napi_enable(vi->rq[qp_index].vq, &vi->rq[qp_index].napi);
2233 	virtnet_napi_tx_enable(vi, vi->sq[qp_index].vq, &vi->sq[qp_index].napi);
2234 
2235 	return 0;
2236 
2237 err_xdp_reg_mem_model:
2238 	xdp_rxq_info_unreg(&vi->rq[qp_index].xdp_rxq);
2239 	return err;
2240 }
2241 
virtnet_open(struct net_device * dev)2242 static int virtnet_open(struct net_device *dev)
2243 {
2244 	struct virtnet_info *vi = netdev_priv(dev);
2245 	int i, err;
2246 
2247 	enable_delayed_refill(vi);
2248 
2249 	for (i = 0; i < vi->max_queue_pairs; i++) {
2250 		if (i < vi->curr_queue_pairs)
2251 			/* Make sure we have some buffers: if oom use wq. */
2252 			if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
2253 				schedule_delayed_work(&vi->refill, 0);
2254 
2255 		err = virtnet_enable_queue_pair(vi, i);
2256 		if (err < 0)
2257 			goto err_enable_qp;
2258 	}
2259 
2260 	return 0;
2261 
2262 err_enable_qp:
2263 	disable_delayed_refill(vi);
2264 	cancel_delayed_work_sync(&vi->refill);
2265 
2266 	for (i--; i >= 0; i--)
2267 		virtnet_disable_queue_pair(vi, i);
2268 	return err;
2269 }
2270 
virtnet_poll_tx(struct napi_struct * napi,int budget)2271 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
2272 {
2273 	struct send_queue *sq = container_of(napi, struct send_queue, napi);
2274 	struct virtnet_info *vi = sq->vq->vdev->priv;
2275 	unsigned int index = vq2txq(sq->vq);
2276 	struct netdev_queue *txq;
2277 	int opaque;
2278 	bool done;
2279 
2280 	if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
2281 		/* We don't need to enable cb for XDP */
2282 		napi_complete_done(napi, 0);
2283 		return 0;
2284 	}
2285 
2286 	txq = netdev_get_tx_queue(vi->dev, index);
2287 	__netif_tx_lock(txq, raw_smp_processor_id());
2288 	virtqueue_disable_cb(sq->vq);
2289 	free_old_xmit_skbs(sq, !!budget);
2290 
2291 	if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
2292 		netif_tx_wake_queue(txq);
2293 
2294 	opaque = virtqueue_enable_cb_prepare(sq->vq);
2295 
2296 	done = napi_complete_done(napi, 0);
2297 
2298 	if (!done)
2299 		virtqueue_disable_cb(sq->vq);
2300 
2301 	__netif_tx_unlock(txq);
2302 
2303 	if (done) {
2304 		if (unlikely(virtqueue_poll(sq->vq, opaque))) {
2305 			if (napi_schedule_prep(napi)) {
2306 				__netif_tx_lock(txq, raw_smp_processor_id());
2307 				virtqueue_disable_cb(sq->vq);
2308 				__netif_tx_unlock(txq);
2309 				__napi_schedule(napi);
2310 			}
2311 		}
2312 	}
2313 
2314 	return 0;
2315 }
2316 
xmit_skb(struct send_queue * sq,struct sk_buff * skb)2317 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
2318 {
2319 	struct virtio_net_hdr_mrg_rxbuf *hdr;
2320 	const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
2321 	struct virtnet_info *vi = sq->vq->vdev->priv;
2322 	int num_sg;
2323 	unsigned hdr_len = vi->hdr_len;
2324 	bool can_push;
2325 
2326 	pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
2327 
2328 	can_push = vi->any_header_sg &&
2329 		!((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
2330 		!skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
2331 	/* Even if we can, don't push here yet as this would skew
2332 	 * csum_start offset below. */
2333 	if (can_push)
2334 		hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
2335 	else
2336 		hdr = &skb_vnet_common_hdr(skb)->mrg_hdr;
2337 
2338 	if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
2339 				    virtio_is_little_endian(vi->vdev), false,
2340 				    0))
2341 		return -EPROTO;
2342 
2343 	if (vi->mergeable_rx_bufs)
2344 		hdr->num_buffers = 0;
2345 
2346 	sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
2347 	if (can_push) {
2348 		__skb_push(skb, hdr_len);
2349 		num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
2350 		if (unlikely(num_sg < 0))
2351 			return num_sg;
2352 		/* Pull header back to avoid skew in tx bytes calculations. */
2353 		__skb_pull(skb, hdr_len);
2354 	} else {
2355 		sg_set_buf(sq->sg, hdr, hdr_len);
2356 		num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
2357 		if (unlikely(num_sg < 0))
2358 			return num_sg;
2359 		num_sg++;
2360 	}
2361 	return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
2362 }
2363 
start_xmit(struct sk_buff * skb,struct net_device * dev)2364 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
2365 {
2366 	struct virtnet_info *vi = netdev_priv(dev);
2367 	int qnum = skb_get_queue_mapping(skb);
2368 	struct send_queue *sq = &vi->sq[qnum];
2369 	int err;
2370 	struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
2371 	bool kick = !netdev_xmit_more();
2372 	bool use_napi = sq->napi.weight;
2373 
2374 	/* Free up any pending old buffers before queueing new ones. */
2375 	do {
2376 		if (use_napi)
2377 			virtqueue_disable_cb(sq->vq);
2378 
2379 		free_old_xmit_skbs(sq, false);
2380 
2381 	} while (use_napi && kick &&
2382 	       unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
2383 
2384 	/* timestamp packet in software */
2385 	skb_tx_timestamp(skb);
2386 
2387 	/* Try to transmit */
2388 	err = xmit_skb(sq, skb);
2389 
2390 	/* This should not happen! */
2391 	if (unlikely(err)) {
2392 		DEV_STATS_INC(dev, tx_fifo_errors);
2393 		if (net_ratelimit())
2394 			dev_warn(&dev->dev,
2395 				 "Unexpected TXQ (%d) queue failure: %d\n",
2396 				 qnum, err);
2397 		DEV_STATS_INC(dev, tx_dropped);
2398 		dev_kfree_skb_any(skb);
2399 		return NETDEV_TX_OK;
2400 	}
2401 
2402 	/* Don't wait up for transmitted skbs to be freed. */
2403 	if (!use_napi) {
2404 		skb_orphan(skb);
2405 		nf_reset_ct(skb);
2406 	}
2407 
2408 	check_sq_full_and_disable(vi, dev, sq);
2409 
2410 	if (kick || netif_xmit_stopped(txq)) {
2411 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
2412 			u64_stats_update_begin(&sq->stats.syncp);
2413 			u64_stats_inc(&sq->stats.kicks);
2414 			u64_stats_update_end(&sq->stats.syncp);
2415 		}
2416 	}
2417 
2418 	return NETDEV_TX_OK;
2419 }
2420 
virtnet_rx_resize(struct virtnet_info * vi,struct receive_queue * rq,u32 ring_num)2421 static int virtnet_rx_resize(struct virtnet_info *vi,
2422 			     struct receive_queue *rq, u32 ring_num)
2423 {
2424 	bool running = netif_running(vi->dev);
2425 	int err, qindex;
2426 
2427 	qindex = rq - vi->rq;
2428 
2429 	if (running)
2430 		napi_disable(&rq->napi);
2431 
2432 	err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_unmap_free_buf);
2433 	if (err)
2434 		netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
2435 
2436 	if (!try_fill_recv(vi, rq, GFP_KERNEL))
2437 		schedule_delayed_work(&vi->refill, 0);
2438 
2439 	if (running)
2440 		virtnet_napi_enable(rq->vq, &rq->napi);
2441 	return err;
2442 }
2443 
virtnet_tx_resize(struct virtnet_info * vi,struct send_queue * sq,u32 ring_num)2444 static int virtnet_tx_resize(struct virtnet_info *vi,
2445 			     struct send_queue *sq, u32 ring_num)
2446 {
2447 	bool running = netif_running(vi->dev);
2448 	struct netdev_queue *txq;
2449 	int err, qindex;
2450 
2451 	qindex = sq - vi->sq;
2452 
2453 	if (running)
2454 		virtnet_napi_tx_disable(&sq->napi);
2455 
2456 	txq = netdev_get_tx_queue(vi->dev, qindex);
2457 
2458 	/* 1. wait all ximt complete
2459 	 * 2. fix the race of netif_stop_subqueue() vs netif_start_subqueue()
2460 	 */
2461 	__netif_tx_lock_bh(txq);
2462 
2463 	/* Prevent rx poll from accessing sq. */
2464 	sq->reset = true;
2465 
2466 	/* Prevent the upper layer from trying to send packets. */
2467 	netif_stop_subqueue(vi->dev, qindex);
2468 
2469 	__netif_tx_unlock_bh(txq);
2470 
2471 	err = virtqueue_resize(sq->vq, ring_num, virtnet_sq_free_unused_buf);
2472 	if (err)
2473 		netdev_err(vi->dev, "resize tx fail: tx queue index: %d err: %d\n", qindex, err);
2474 
2475 	__netif_tx_lock_bh(txq);
2476 	sq->reset = false;
2477 	netif_tx_wake_queue(txq);
2478 	__netif_tx_unlock_bh(txq);
2479 
2480 	if (running)
2481 		virtnet_napi_tx_enable(vi, sq->vq, &sq->napi);
2482 	return err;
2483 }
2484 
2485 /*
2486  * Send command via the control virtqueue and check status.  Commands
2487  * supported by the hypervisor, as indicated by feature bits, should
2488  * never fail unless improperly formatted.
2489  */
virtnet_send_command(struct virtnet_info * vi,u8 class,u8 cmd,struct scatterlist * out)2490 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
2491 				 struct scatterlist *out)
2492 {
2493 	struct scatterlist *sgs[4], hdr, stat;
2494 	unsigned out_num = 0, tmp;
2495 	int ret;
2496 
2497 	/* Caller should know better */
2498 	BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
2499 
2500 	vi->ctrl->status = ~0;
2501 	vi->ctrl->hdr.class = class;
2502 	vi->ctrl->hdr.cmd = cmd;
2503 	/* Add header */
2504 	sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
2505 	sgs[out_num++] = &hdr;
2506 
2507 	if (out)
2508 		sgs[out_num++] = out;
2509 
2510 	/* Add return status. */
2511 	sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
2512 	sgs[out_num] = &stat;
2513 
2514 	BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
2515 	ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
2516 	if (ret < 0) {
2517 		dev_warn(&vi->vdev->dev,
2518 			 "Failed to add sgs for command vq: %d\n.", ret);
2519 		return false;
2520 	}
2521 
2522 	if (unlikely(!virtqueue_kick(vi->cvq)))
2523 		return vi->ctrl->status == VIRTIO_NET_OK;
2524 
2525 	/* Spin for a response, the kick causes an ioport write, trapping
2526 	 * into the hypervisor, so the request should be handled immediately.
2527 	 */
2528 	while (!virtqueue_get_buf(vi->cvq, &tmp) &&
2529 	       !virtqueue_is_broken(vi->cvq))
2530 		cpu_relax();
2531 
2532 	return vi->ctrl->status == VIRTIO_NET_OK;
2533 }
2534 
virtnet_set_mac_address(struct net_device * dev,void * p)2535 static int virtnet_set_mac_address(struct net_device *dev, void *p)
2536 {
2537 	struct virtnet_info *vi = netdev_priv(dev);
2538 	struct virtio_device *vdev = vi->vdev;
2539 	int ret;
2540 	struct sockaddr *addr;
2541 	struct scatterlist sg;
2542 
2543 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2544 		return -EOPNOTSUPP;
2545 
2546 	addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
2547 	if (!addr)
2548 		return -ENOMEM;
2549 
2550 	ret = eth_prepare_mac_addr_change(dev, addr);
2551 	if (ret)
2552 		goto out;
2553 
2554 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
2555 		sg_init_one(&sg, addr->sa_data, dev->addr_len);
2556 		if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2557 					  VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
2558 			dev_warn(&vdev->dev,
2559 				 "Failed to set mac address by vq command.\n");
2560 			ret = -EINVAL;
2561 			goto out;
2562 		}
2563 	} else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
2564 		   !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2565 		unsigned int i;
2566 
2567 		/* Naturally, this has an atomicity problem. */
2568 		for (i = 0; i < dev->addr_len; i++)
2569 			virtio_cwrite8(vdev,
2570 				       offsetof(struct virtio_net_config, mac) +
2571 				       i, addr->sa_data[i]);
2572 	}
2573 
2574 	eth_commit_mac_addr_change(dev, p);
2575 	ret = 0;
2576 
2577 out:
2578 	kfree(addr);
2579 	return ret;
2580 }
2581 
virtnet_stats(struct net_device * dev,struct rtnl_link_stats64 * tot)2582 static void virtnet_stats(struct net_device *dev,
2583 			  struct rtnl_link_stats64 *tot)
2584 {
2585 	struct virtnet_info *vi = netdev_priv(dev);
2586 	unsigned int start;
2587 	int i;
2588 
2589 	for (i = 0; i < vi->max_queue_pairs; i++) {
2590 		u64 tpackets, tbytes, terrors, rpackets, rbytes, rdrops;
2591 		struct receive_queue *rq = &vi->rq[i];
2592 		struct send_queue *sq = &vi->sq[i];
2593 
2594 		do {
2595 			start = u64_stats_fetch_begin(&sq->stats.syncp);
2596 			tpackets = u64_stats_read(&sq->stats.packets);
2597 			tbytes   = u64_stats_read(&sq->stats.bytes);
2598 			terrors  = u64_stats_read(&sq->stats.tx_timeouts);
2599 		} while (u64_stats_fetch_retry(&sq->stats.syncp, start));
2600 
2601 		do {
2602 			start = u64_stats_fetch_begin(&rq->stats.syncp);
2603 			rpackets = u64_stats_read(&rq->stats.packets);
2604 			rbytes   = u64_stats_read(&rq->stats.bytes);
2605 			rdrops   = u64_stats_read(&rq->stats.drops);
2606 		} while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2607 
2608 		tot->rx_packets += rpackets;
2609 		tot->tx_packets += tpackets;
2610 		tot->rx_bytes   += rbytes;
2611 		tot->tx_bytes   += tbytes;
2612 		tot->rx_dropped += rdrops;
2613 		tot->tx_errors  += terrors;
2614 	}
2615 
2616 	tot->tx_dropped = DEV_STATS_READ(dev, tx_dropped);
2617 	tot->tx_fifo_errors = DEV_STATS_READ(dev, tx_fifo_errors);
2618 	tot->rx_length_errors = DEV_STATS_READ(dev, rx_length_errors);
2619 	tot->rx_frame_errors = DEV_STATS_READ(dev, rx_frame_errors);
2620 }
2621 
virtnet_ack_link_announce(struct virtnet_info * vi)2622 static void virtnet_ack_link_announce(struct virtnet_info *vi)
2623 {
2624 	rtnl_lock();
2625 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
2626 				  VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
2627 		dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
2628 	rtnl_unlock();
2629 }
2630 
_virtnet_set_queues(struct virtnet_info * vi,u16 queue_pairs)2631 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2632 {
2633 	struct scatterlist sg;
2634 	struct net_device *dev = vi->dev;
2635 
2636 	if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
2637 		return 0;
2638 
2639 	vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
2640 	sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
2641 
2642 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2643 				  VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
2644 		dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
2645 			 queue_pairs);
2646 		return -EINVAL;
2647 	} else {
2648 		vi->curr_queue_pairs = queue_pairs;
2649 		/* virtnet_open() will refill when device is going to up. */
2650 		if (dev->flags & IFF_UP)
2651 			schedule_delayed_work(&vi->refill, 0);
2652 	}
2653 
2654 	return 0;
2655 }
2656 
virtnet_set_queues(struct virtnet_info * vi,u16 queue_pairs)2657 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2658 {
2659 	int err;
2660 
2661 	rtnl_lock();
2662 	err = _virtnet_set_queues(vi, queue_pairs);
2663 	rtnl_unlock();
2664 	return err;
2665 }
2666 
virtnet_close(struct net_device * dev)2667 static int virtnet_close(struct net_device *dev)
2668 {
2669 	struct virtnet_info *vi = netdev_priv(dev);
2670 	int i;
2671 
2672 	/* Make sure NAPI doesn't schedule refill work */
2673 	disable_delayed_refill(vi);
2674 	/* Make sure refill_work doesn't re-enable napi! */
2675 	cancel_delayed_work_sync(&vi->refill);
2676 
2677 	for (i = 0; i < vi->max_queue_pairs; i++)
2678 		virtnet_disable_queue_pair(vi, i);
2679 
2680 	return 0;
2681 }
2682 
virtnet_set_rx_mode(struct net_device * dev)2683 static void virtnet_set_rx_mode(struct net_device *dev)
2684 {
2685 	struct virtnet_info *vi = netdev_priv(dev);
2686 	struct scatterlist sg[2];
2687 	struct virtio_net_ctrl_mac *mac_data;
2688 	struct netdev_hw_addr *ha;
2689 	int uc_count;
2690 	int mc_count;
2691 	void *buf;
2692 	int i;
2693 
2694 	/* We can't dynamically set ndo_set_rx_mode, so return gracefully */
2695 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
2696 		return;
2697 
2698 	vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
2699 	vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
2700 
2701 	sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
2702 
2703 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2704 				  VIRTIO_NET_CTRL_RX_PROMISC, sg))
2705 		dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
2706 			 vi->ctrl->promisc ? "en" : "dis");
2707 
2708 	sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
2709 
2710 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2711 				  VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
2712 		dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
2713 			 vi->ctrl->allmulti ? "en" : "dis");
2714 
2715 	uc_count = netdev_uc_count(dev);
2716 	mc_count = netdev_mc_count(dev);
2717 	/* MAC filter - use one buffer for both lists */
2718 	buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
2719 		      (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
2720 	mac_data = buf;
2721 	if (!buf)
2722 		return;
2723 
2724 	sg_init_table(sg, 2);
2725 
2726 	/* Store the unicast list and count in the front of the buffer */
2727 	mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2728 	i = 0;
2729 	netdev_for_each_uc_addr(ha, dev)
2730 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2731 
2732 	sg_set_buf(&sg[0], mac_data,
2733 		   sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2734 
2735 	/* multicast list and count fill the end */
2736 	mac_data = (void *)&mac_data->macs[uc_count][0];
2737 
2738 	mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2739 	i = 0;
2740 	netdev_for_each_mc_addr(ha, dev)
2741 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2742 
2743 	sg_set_buf(&sg[1], mac_data,
2744 		   sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2745 
2746 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2747 				  VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2748 		dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2749 
2750 	kfree(buf);
2751 }
2752 
virtnet_vlan_rx_add_vid(struct net_device * dev,__be16 proto,u16 vid)2753 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
2754 				   __be16 proto, u16 vid)
2755 {
2756 	struct virtnet_info *vi = netdev_priv(dev);
2757 	struct scatterlist sg;
2758 
2759 	vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2760 	sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2761 
2762 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2763 				  VIRTIO_NET_CTRL_VLAN_ADD, &sg))
2764 		dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
2765 	return 0;
2766 }
2767 
virtnet_vlan_rx_kill_vid(struct net_device * dev,__be16 proto,u16 vid)2768 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
2769 				    __be16 proto, u16 vid)
2770 {
2771 	struct virtnet_info *vi = netdev_priv(dev);
2772 	struct scatterlist sg;
2773 
2774 	vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2775 	sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2776 
2777 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2778 				  VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2779 		dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2780 	return 0;
2781 }
2782 
virtnet_clean_affinity(struct virtnet_info * vi)2783 static void virtnet_clean_affinity(struct virtnet_info *vi)
2784 {
2785 	int i;
2786 
2787 	if (vi->affinity_hint_set) {
2788 		for (i = 0; i < vi->max_queue_pairs; i++) {
2789 			virtqueue_set_affinity(vi->rq[i].vq, NULL);
2790 			virtqueue_set_affinity(vi->sq[i].vq, NULL);
2791 		}
2792 
2793 		vi->affinity_hint_set = false;
2794 	}
2795 }
2796 
virtnet_set_affinity(struct virtnet_info * vi)2797 static void virtnet_set_affinity(struct virtnet_info *vi)
2798 {
2799 	cpumask_var_t mask;
2800 	int stragglers;
2801 	int group_size;
2802 	int i, j, cpu;
2803 	int num_cpu;
2804 	int stride;
2805 
2806 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2807 		virtnet_clean_affinity(vi);
2808 		return;
2809 	}
2810 
2811 	num_cpu = num_online_cpus();
2812 	stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2813 	stragglers = num_cpu >= vi->curr_queue_pairs ?
2814 			num_cpu % vi->curr_queue_pairs :
2815 			0;
2816 	cpu = cpumask_first(cpu_online_mask);
2817 
2818 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2819 		group_size = stride + (i < stragglers ? 1 : 0);
2820 
2821 		for (j = 0; j < group_size; j++) {
2822 			cpumask_set_cpu(cpu, mask);
2823 			cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2824 						nr_cpu_ids, false);
2825 		}
2826 		virtqueue_set_affinity(vi->rq[i].vq, mask);
2827 		virtqueue_set_affinity(vi->sq[i].vq, mask);
2828 		__netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2829 		cpumask_clear(mask);
2830 	}
2831 
2832 	vi->affinity_hint_set = true;
2833 	free_cpumask_var(mask);
2834 }
2835 
virtnet_cpu_online(unsigned int cpu,struct hlist_node * node)2836 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2837 {
2838 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2839 						   node);
2840 	virtnet_set_affinity(vi);
2841 	return 0;
2842 }
2843 
virtnet_cpu_dead(unsigned int cpu,struct hlist_node * node)2844 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2845 {
2846 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2847 						   node_dead);
2848 	virtnet_set_affinity(vi);
2849 	return 0;
2850 }
2851 
virtnet_cpu_down_prep(unsigned int cpu,struct hlist_node * node)2852 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2853 {
2854 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2855 						   node);
2856 
2857 	virtnet_clean_affinity(vi);
2858 	return 0;
2859 }
2860 
2861 static enum cpuhp_state virtionet_online;
2862 
virtnet_cpu_notif_add(struct virtnet_info * vi)2863 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2864 {
2865 	int ret;
2866 
2867 	ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2868 	if (ret)
2869 		return ret;
2870 	ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2871 					       &vi->node_dead);
2872 	if (!ret)
2873 		return ret;
2874 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2875 	return ret;
2876 }
2877 
virtnet_cpu_notif_remove(struct virtnet_info * vi)2878 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2879 {
2880 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2881 	cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2882 					    &vi->node_dead);
2883 }
2884 
virtnet_get_ringparam(struct net_device * dev,struct ethtool_ringparam * ring,struct kernel_ethtool_ringparam * kernel_ring,struct netlink_ext_ack * extack)2885 static void virtnet_get_ringparam(struct net_device *dev,
2886 				  struct ethtool_ringparam *ring,
2887 				  struct kernel_ethtool_ringparam *kernel_ring,
2888 				  struct netlink_ext_ack *extack)
2889 {
2890 	struct virtnet_info *vi = netdev_priv(dev);
2891 
2892 	ring->rx_max_pending = vi->rq[0].vq->num_max;
2893 	ring->tx_max_pending = vi->sq[0].vq->num_max;
2894 	ring->rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2895 	ring->tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2896 }
2897 
2898 static int virtnet_send_ctrl_coal_vq_cmd(struct virtnet_info *vi,
2899 					 u16 vqn, u32 max_usecs, u32 max_packets);
2900 
virtnet_set_ringparam(struct net_device * dev,struct ethtool_ringparam * ring,struct kernel_ethtool_ringparam * kernel_ring,struct netlink_ext_ack * extack)2901 static int virtnet_set_ringparam(struct net_device *dev,
2902 				 struct ethtool_ringparam *ring,
2903 				 struct kernel_ethtool_ringparam *kernel_ring,
2904 				 struct netlink_ext_ack *extack)
2905 {
2906 	struct virtnet_info *vi = netdev_priv(dev);
2907 	u32 rx_pending, tx_pending;
2908 	struct receive_queue *rq;
2909 	struct send_queue *sq;
2910 	int i, err;
2911 
2912 	if (ring->rx_mini_pending || ring->rx_jumbo_pending)
2913 		return -EINVAL;
2914 
2915 	rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2916 	tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2917 
2918 	if (ring->rx_pending == rx_pending &&
2919 	    ring->tx_pending == tx_pending)
2920 		return 0;
2921 
2922 	if (ring->rx_pending > vi->rq[0].vq->num_max)
2923 		return -EINVAL;
2924 
2925 	if (ring->tx_pending > vi->sq[0].vq->num_max)
2926 		return -EINVAL;
2927 
2928 	for (i = 0; i < vi->max_queue_pairs; i++) {
2929 		rq = vi->rq + i;
2930 		sq = vi->sq + i;
2931 
2932 		if (ring->tx_pending != tx_pending) {
2933 			err = virtnet_tx_resize(vi, sq, ring->tx_pending);
2934 			if (err)
2935 				return err;
2936 
2937 			/* Upon disabling and re-enabling a transmit virtqueue, the device must
2938 			 * set the coalescing parameters of the virtqueue to those configured
2939 			 * through the VIRTIO_NET_CTRL_NOTF_COAL_TX_SET command, or, if the driver
2940 			 * did not set any TX coalescing parameters, to 0.
2941 			 */
2942 			err = virtnet_send_ctrl_coal_vq_cmd(vi, txq2vq(i),
2943 							    vi->intr_coal_tx.max_usecs,
2944 							    vi->intr_coal_tx.max_packets);
2945 			if (err)
2946 				return err;
2947 
2948 			vi->sq[i].intr_coal.max_usecs = vi->intr_coal_tx.max_usecs;
2949 			vi->sq[i].intr_coal.max_packets = vi->intr_coal_tx.max_packets;
2950 		}
2951 
2952 		if (ring->rx_pending != rx_pending) {
2953 			err = virtnet_rx_resize(vi, rq, ring->rx_pending);
2954 			if (err)
2955 				return err;
2956 
2957 			/* The reason is same as the transmit virtqueue reset */
2958 			err = virtnet_send_ctrl_coal_vq_cmd(vi, rxq2vq(i),
2959 							    vi->intr_coal_rx.max_usecs,
2960 							    vi->intr_coal_rx.max_packets);
2961 			if (err)
2962 				return err;
2963 
2964 			vi->rq[i].intr_coal.max_usecs = vi->intr_coal_rx.max_usecs;
2965 			vi->rq[i].intr_coal.max_packets = vi->intr_coal_rx.max_packets;
2966 		}
2967 	}
2968 
2969 	return 0;
2970 }
2971 
virtnet_commit_rss_command(struct virtnet_info * vi)2972 static bool virtnet_commit_rss_command(struct virtnet_info *vi)
2973 {
2974 	struct net_device *dev = vi->dev;
2975 	struct scatterlist sgs[4];
2976 	unsigned int sg_buf_size;
2977 
2978 	/* prepare sgs */
2979 	sg_init_table(sgs, 4);
2980 
2981 	sg_buf_size = offsetof(struct virtio_net_ctrl_rss, indirection_table);
2982 	sg_set_buf(&sgs[0], &vi->ctrl->rss, sg_buf_size);
2983 
2984 	sg_buf_size = sizeof(uint16_t) * (vi->ctrl->rss.indirection_table_mask + 1);
2985 	sg_set_buf(&sgs[1], vi->ctrl->rss.indirection_table, sg_buf_size);
2986 
2987 	sg_buf_size = offsetof(struct virtio_net_ctrl_rss, key)
2988 			- offsetof(struct virtio_net_ctrl_rss, max_tx_vq);
2989 	sg_set_buf(&sgs[2], &vi->ctrl->rss.max_tx_vq, sg_buf_size);
2990 
2991 	sg_buf_size = vi->rss_key_size;
2992 	sg_set_buf(&sgs[3], vi->ctrl->rss.key, sg_buf_size);
2993 
2994 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2995 				  vi->has_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG
2996 				  : VIRTIO_NET_CTRL_MQ_HASH_CONFIG, sgs)) {
2997 		dev_warn(&dev->dev, "VIRTIONET issue with committing RSS sgs\n");
2998 		return false;
2999 	}
3000 	return true;
3001 }
3002 
virtnet_init_default_rss(struct virtnet_info * vi)3003 static void virtnet_init_default_rss(struct virtnet_info *vi)
3004 {
3005 	u32 indir_val = 0;
3006 	int i = 0;
3007 
3008 	vi->ctrl->rss.hash_types = vi->rss_hash_types_supported;
3009 	vi->rss_hash_types_saved = vi->rss_hash_types_supported;
3010 	vi->ctrl->rss.indirection_table_mask = vi->rss_indir_table_size
3011 						? vi->rss_indir_table_size - 1 : 0;
3012 	vi->ctrl->rss.unclassified_queue = 0;
3013 
3014 	for (; i < vi->rss_indir_table_size; ++i) {
3015 		indir_val = ethtool_rxfh_indir_default(i, vi->curr_queue_pairs);
3016 		vi->ctrl->rss.indirection_table[i] = indir_val;
3017 	}
3018 
3019 	vi->ctrl->rss.max_tx_vq = vi->has_rss ? vi->curr_queue_pairs : 0;
3020 	vi->ctrl->rss.hash_key_length = vi->rss_key_size;
3021 
3022 	netdev_rss_key_fill(vi->ctrl->rss.key, vi->rss_key_size);
3023 }
3024 
virtnet_get_hashflow(const struct virtnet_info * vi,struct ethtool_rxnfc * info)3025 static void virtnet_get_hashflow(const struct virtnet_info *vi, struct ethtool_rxnfc *info)
3026 {
3027 	info->data = 0;
3028 	switch (info->flow_type) {
3029 	case TCP_V4_FLOW:
3030 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
3031 			info->data = RXH_IP_SRC | RXH_IP_DST |
3032 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
3033 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
3034 			info->data = RXH_IP_SRC | RXH_IP_DST;
3035 		}
3036 		break;
3037 	case TCP_V6_FLOW:
3038 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
3039 			info->data = RXH_IP_SRC | RXH_IP_DST |
3040 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
3041 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
3042 			info->data = RXH_IP_SRC | RXH_IP_DST;
3043 		}
3044 		break;
3045 	case UDP_V4_FLOW:
3046 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
3047 			info->data = RXH_IP_SRC | RXH_IP_DST |
3048 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
3049 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
3050 			info->data = RXH_IP_SRC | RXH_IP_DST;
3051 		}
3052 		break;
3053 	case UDP_V6_FLOW:
3054 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
3055 			info->data = RXH_IP_SRC | RXH_IP_DST |
3056 						 RXH_L4_B_0_1 | RXH_L4_B_2_3;
3057 		} else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
3058 			info->data = RXH_IP_SRC | RXH_IP_DST;
3059 		}
3060 		break;
3061 	case IPV4_FLOW:
3062 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4)
3063 			info->data = RXH_IP_SRC | RXH_IP_DST;
3064 
3065 		break;
3066 	case IPV6_FLOW:
3067 		if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6)
3068 			info->data = RXH_IP_SRC | RXH_IP_DST;
3069 
3070 		break;
3071 	default:
3072 		info->data = 0;
3073 		break;
3074 	}
3075 }
3076 
virtnet_set_hashflow(struct virtnet_info * vi,struct ethtool_rxnfc * info)3077 static bool virtnet_set_hashflow(struct virtnet_info *vi, struct ethtool_rxnfc *info)
3078 {
3079 	u32 new_hashtypes = vi->rss_hash_types_saved;
3080 	bool is_disable = info->data & RXH_DISCARD;
3081 	bool is_l4 = info->data == (RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3);
3082 
3083 	/* supports only 'sd', 'sdfn' and 'r' */
3084 	if (!((info->data == (RXH_IP_SRC | RXH_IP_DST)) | is_l4 | is_disable))
3085 		return false;
3086 
3087 	switch (info->flow_type) {
3088 	case TCP_V4_FLOW:
3089 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_TCPv4);
3090 		if (!is_disable)
3091 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
3092 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0);
3093 		break;
3094 	case UDP_V4_FLOW:
3095 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_UDPv4);
3096 		if (!is_disable)
3097 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
3098 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0);
3099 		break;
3100 	case IPV4_FLOW:
3101 		new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv4;
3102 		if (!is_disable)
3103 			new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv4;
3104 		break;
3105 	case TCP_V6_FLOW:
3106 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_TCPv6);
3107 		if (!is_disable)
3108 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
3109 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0);
3110 		break;
3111 	case UDP_V6_FLOW:
3112 		new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_UDPv6);
3113 		if (!is_disable)
3114 			new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
3115 				| (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0);
3116 		break;
3117 	case IPV6_FLOW:
3118 		new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv6;
3119 		if (!is_disable)
3120 			new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv6;
3121 		break;
3122 	default:
3123 		/* unsupported flow */
3124 		return false;
3125 	}
3126 
3127 	/* if unsupported hashtype was set */
3128 	if (new_hashtypes != (new_hashtypes & vi->rss_hash_types_supported))
3129 		return false;
3130 
3131 	if (new_hashtypes != vi->rss_hash_types_saved) {
3132 		vi->rss_hash_types_saved = new_hashtypes;
3133 		vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
3134 		if (vi->dev->features & NETIF_F_RXHASH)
3135 			return virtnet_commit_rss_command(vi);
3136 	}
3137 
3138 	return true;
3139 }
3140 
virtnet_get_drvinfo(struct net_device * dev,struct ethtool_drvinfo * info)3141 static void virtnet_get_drvinfo(struct net_device *dev,
3142 				struct ethtool_drvinfo *info)
3143 {
3144 	struct virtnet_info *vi = netdev_priv(dev);
3145 	struct virtio_device *vdev = vi->vdev;
3146 
3147 	strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
3148 	strscpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
3149 	strscpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
3150 
3151 }
3152 
3153 /* TODO: Eliminate OOO packets during switching */
virtnet_set_channels(struct net_device * dev,struct ethtool_channels * channels)3154 static int virtnet_set_channels(struct net_device *dev,
3155 				struct ethtool_channels *channels)
3156 {
3157 	struct virtnet_info *vi = netdev_priv(dev);
3158 	u16 queue_pairs = channels->combined_count;
3159 	int err;
3160 
3161 	/* We don't support separate rx/tx channels.
3162 	 * We don't allow setting 'other' channels.
3163 	 */
3164 	if (channels->rx_count || channels->tx_count || channels->other_count)
3165 		return -EINVAL;
3166 
3167 	if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
3168 		return -EINVAL;
3169 
3170 	/* For now we don't support modifying channels while XDP is loaded
3171 	 * also when XDP is loaded all RX queues have XDP programs so we only
3172 	 * need to check a single RX queue.
3173 	 */
3174 	if (vi->rq[0].xdp_prog)
3175 		return -EINVAL;
3176 
3177 	cpus_read_lock();
3178 	err = _virtnet_set_queues(vi, queue_pairs);
3179 	if (err) {
3180 		cpus_read_unlock();
3181 		goto err;
3182 	}
3183 	virtnet_set_affinity(vi);
3184 	cpus_read_unlock();
3185 
3186 	netif_set_real_num_tx_queues(dev, queue_pairs);
3187 	netif_set_real_num_rx_queues(dev, queue_pairs);
3188  err:
3189 	return err;
3190 }
3191 
virtnet_get_strings(struct net_device * dev,u32 stringset,u8 * data)3192 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
3193 {
3194 	struct virtnet_info *vi = netdev_priv(dev);
3195 	unsigned int i, j;
3196 	u8 *p = data;
3197 
3198 	switch (stringset) {
3199 	case ETH_SS_STATS:
3200 		for (i = 0; i < vi->curr_queue_pairs; i++) {
3201 			for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
3202 				ethtool_sprintf(&p, "rx_queue_%u_%s", i,
3203 						virtnet_rq_stats_desc[j].desc);
3204 		}
3205 
3206 		for (i = 0; i < vi->curr_queue_pairs; i++) {
3207 			for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
3208 				ethtool_sprintf(&p, "tx_queue_%u_%s", i,
3209 						virtnet_sq_stats_desc[j].desc);
3210 		}
3211 		break;
3212 	}
3213 }
3214 
virtnet_get_sset_count(struct net_device * dev,int sset)3215 static int virtnet_get_sset_count(struct net_device *dev, int sset)
3216 {
3217 	struct virtnet_info *vi = netdev_priv(dev);
3218 
3219 	switch (sset) {
3220 	case ETH_SS_STATS:
3221 		return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
3222 					       VIRTNET_SQ_STATS_LEN);
3223 	default:
3224 		return -EOPNOTSUPP;
3225 	}
3226 }
3227 
virtnet_get_ethtool_stats(struct net_device * dev,struct ethtool_stats * stats,u64 * data)3228 static void virtnet_get_ethtool_stats(struct net_device *dev,
3229 				      struct ethtool_stats *stats, u64 *data)
3230 {
3231 	struct virtnet_info *vi = netdev_priv(dev);
3232 	unsigned int idx = 0, start, i, j;
3233 	const u8 *stats_base;
3234 	const u64_stats_t *p;
3235 	size_t offset;
3236 
3237 	for (i = 0; i < vi->curr_queue_pairs; i++) {
3238 		struct receive_queue *rq = &vi->rq[i];
3239 
3240 		stats_base = (const u8 *)&rq->stats;
3241 		do {
3242 			start = u64_stats_fetch_begin(&rq->stats.syncp);
3243 			for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
3244 				offset = virtnet_rq_stats_desc[j].offset;
3245 				p = (const u64_stats_t *)(stats_base + offset);
3246 				data[idx + j] = u64_stats_read(p);
3247 			}
3248 		} while (u64_stats_fetch_retry(&rq->stats.syncp, start));
3249 		idx += VIRTNET_RQ_STATS_LEN;
3250 	}
3251 
3252 	for (i = 0; i < vi->curr_queue_pairs; i++) {
3253 		struct send_queue *sq = &vi->sq[i];
3254 
3255 		stats_base = (const u8 *)&sq->stats;
3256 		do {
3257 			start = u64_stats_fetch_begin(&sq->stats.syncp);
3258 			for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
3259 				offset = virtnet_sq_stats_desc[j].offset;
3260 				p = (const u64_stats_t *)(stats_base + offset);
3261 				data[idx + j] = u64_stats_read(p);
3262 			}
3263 		} while (u64_stats_fetch_retry(&sq->stats.syncp, start));
3264 		idx += VIRTNET_SQ_STATS_LEN;
3265 	}
3266 }
3267 
virtnet_get_channels(struct net_device * dev,struct ethtool_channels * channels)3268 static void virtnet_get_channels(struct net_device *dev,
3269 				 struct ethtool_channels *channels)
3270 {
3271 	struct virtnet_info *vi = netdev_priv(dev);
3272 
3273 	channels->combined_count = vi->curr_queue_pairs;
3274 	channels->max_combined = vi->max_queue_pairs;
3275 	channels->max_other = 0;
3276 	channels->rx_count = 0;
3277 	channels->tx_count = 0;
3278 	channels->other_count = 0;
3279 }
3280 
virtnet_set_link_ksettings(struct net_device * dev,const struct ethtool_link_ksettings * cmd)3281 static int virtnet_set_link_ksettings(struct net_device *dev,
3282 				      const struct ethtool_link_ksettings *cmd)
3283 {
3284 	struct virtnet_info *vi = netdev_priv(dev);
3285 
3286 	return ethtool_virtdev_set_link_ksettings(dev, cmd,
3287 						  &vi->speed, &vi->duplex);
3288 }
3289 
virtnet_get_link_ksettings(struct net_device * dev,struct ethtool_link_ksettings * cmd)3290 static int virtnet_get_link_ksettings(struct net_device *dev,
3291 				      struct ethtool_link_ksettings *cmd)
3292 {
3293 	struct virtnet_info *vi = netdev_priv(dev);
3294 
3295 	cmd->base.speed = vi->speed;
3296 	cmd->base.duplex = vi->duplex;
3297 	cmd->base.port = PORT_OTHER;
3298 
3299 	return 0;
3300 }
3301 
virtnet_send_notf_coal_cmds(struct virtnet_info * vi,struct ethtool_coalesce * ec)3302 static int virtnet_send_notf_coal_cmds(struct virtnet_info *vi,
3303 				       struct ethtool_coalesce *ec)
3304 {
3305 	struct scatterlist sgs_tx, sgs_rx;
3306 	int i;
3307 
3308 	vi->ctrl->coal_tx.tx_usecs = cpu_to_le32(ec->tx_coalesce_usecs);
3309 	vi->ctrl->coal_tx.tx_max_packets = cpu_to_le32(ec->tx_max_coalesced_frames);
3310 	sg_init_one(&sgs_tx, &vi->ctrl->coal_tx, sizeof(vi->ctrl->coal_tx));
3311 
3312 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
3313 				  VIRTIO_NET_CTRL_NOTF_COAL_TX_SET,
3314 				  &sgs_tx))
3315 		return -EINVAL;
3316 
3317 	/* Save parameters */
3318 	vi->intr_coal_tx.max_usecs = ec->tx_coalesce_usecs;
3319 	vi->intr_coal_tx.max_packets = ec->tx_max_coalesced_frames;
3320 	for (i = 0; i < vi->max_queue_pairs; i++) {
3321 		vi->sq[i].intr_coal.max_usecs = ec->tx_coalesce_usecs;
3322 		vi->sq[i].intr_coal.max_packets = ec->tx_max_coalesced_frames;
3323 	}
3324 
3325 	vi->ctrl->coal_rx.rx_usecs = cpu_to_le32(ec->rx_coalesce_usecs);
3326 	vi->ctrl->coal_rx.rx_max_packets = cpu_to_le32(ec->rx_max_coalesced_frames);
3327 	sg_init_one(&sgs_rx, &vi->ctrl->coal_rx, sizeof(vi->ctrl->coal_rx));
3328 
3329 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
3330 				  VIRTIO_NET_CTRL_NOTF_COAL_RX_SET,
3331 				  &sgs_rx))
3332 		return -EINVAL;
3333 
3334 	/* Save parameters */
3335 	vi->intr_coal_rx.max_usecs = ec->rx_coalesce_usecs;
3336 	vi->intr_coal_rx.max_packets = ec->rx_max_coalesced_frames;
3337 	for (i = 0; i < vi->max_queue_pairs; i++) {
3338 		vi->rq[i].intr_coal.max_usecs = ec->rx_coalesce_usecs;
3339 		vi->rq[i].intr_coal.max_packets = ec->rx_max_coalesced_frames;
3340 	}
3341 
3342 	return 0;
3343 }
3344 
virtnet_send_ctrl_coal_vq_cmd(struct virtnet_info * vi,u16 vqn,u32 max_usecs,u32 max_packets)3345 static int virtnet_send_ctrl_coal_vq_cmd(struct virtnet_info *vi,
3346 					 u16 vqn, u32 max_usecs, u32 max_packets)
3347 {
3348 	struct scatterlist sgs;
3349 
3350 	vi->ctrl->coal_vq.vqn = cpu_to_le16(vqn);
3351 	vi->ctrl->coal_vq.coal.max_usecs = cpu_to_le32(max_usecs);
3352 	vi->ctrl->coal_vq.coal.max_packets = cpu_to_le32(max_packets);
3353 	sg_init_one(&sgs, &vi->ctrl->coal_vq, sizeof(vi->ctrl->coal_vq));
3354 
3355 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
3356 				  VIRTIO_NET_CTRL_NOTF_COAL_VQ_SET,
3357 				  &sgs))
3358 		return -EINVAL;
3359 
3360 	return 0;
3361 }
3362 
virtnet_send_notf_coal_vq_cmds(struct virtnet_info * vi,struct ethtool_coalesce * ec,u16 queue)3363 static int virtnet_send_notf_coal_vq_cmds(struct virtnet_info *vi,
3364 					  struct ethtool_coalesce *ec,
3365 					  u16 queue)
3366 {
3367 	int err;
3368 
3369 	err = virtnet_send_ctrl_coal_vq_cmd(vi, rxq2vq(queue),
3370 					    ec->rx_coalesce_usecs,
3371 					    ec->rx_max_coalesced_frames);
3372 	if (err)
3373 		return err;
3374 
3375 	vi->rq[queue].intr_coal.max_usecs = ec->rx_coalesce_usecs;
3376 	vi->rq[queue].intr_coal.max_packets = ec->rx_max_coalesced_frames;
3377 
3378 	err = virtnet_send_ctrl_coal_vq_cmd(vi, txq2vq(queue),
3379 					    ec->tx_coalesce_usecs,
3380 					    ec->tx_max_coalesced_frames);
3381 	if (err)
3382 		return err;
3383 
3384 	vi->sq[queue].intr_coal.max_usecs = ec->tx_coalesce_usecs;
3385 	vi->sq[queue].intr_coal.max_packets = ec->tx_max_coalesced_frames;
3386 
3387 	return 0;
3388 }
3389 
virtnet_coal_params_supported(struct ethtool_coalesce * ec)3390 static int virtnet_coal_params_supported(struct ethtool_coalesce *ec)
3391 {
3392 	/* usecs coalescing is supported only if VIRTIO_NET_F_NOTF_COAL
3393 	 * feature is negotiated.
3394 	 */
3395 	if (ec->rx_coalesce_usecs || ec->tx_coalesce_usecs)
3396 		return -EOPNOTSUPP;
3397 
3398 	if (ec->tx_max_coalesced_frames > 1 ||
3399 	    ec->rx_max_coalesced_frames != 1)
3400 		return -EINVAL;
3401 
3402 	return 0;
3403 }
3404 
virtnet_should_update_vq_weight(int dev_flags,int weight,int vq_weight,bool * should_update)3405 static int virtnet_should_update_vq_weight(int dev_flags, int weight,
3406 					   int vq_weight, bool *should_update)
3407 {
3408 	if (weight ^ vq_weight) {
3409 		if (dev_flags & IFF_UP)
3410 			return -EBUSY;
3411 		*should_update = true;
3412 	}
3413 
3414 	return 0;
3415 }
3416 
virtnet_set_coalesce(struct net_device * dev,struct ethtool_coalesce * ec,struct kernel_ethtool_coalesce * kernel_coal,struct netlink_ext_ack * extack)3417 static int virtnet_set_coalesce(struct net_device *dev,
3418 				struct ethtool_coalesce *ec,
3419 				struct kernel_ethtool_coalesce *kernel_coal,
3420 				struct netlink_ext_ack *extack)
3421 {
3422 	struct virtnet_info *vi = netdev_priv(dev);
3423 	int ret, queue_number, napi_weight;
3424 	bool update_napi = false;
3425 
3426 	/* Can't change NAPI weight if the link is up */
3427 	napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
3428 	for (queue_number = 0; queue_number < vi->max_queue_pairs; queue_number++) {
3429 		ret = virtnet_should_update_vq_weight(dev->flags, napi_weight,
3430 						      vi->sq[queue_number].napi.weight,
3431 						      &update_napi);
3432 		if (ret)
3433 			return ret;
3434 
3435 		if (update_napi) {
3436 			/* All queues that belong to [queue_number, vi->max_queue_pairs] will be
3437 			 * updated for the sake of simplicity, which might not be necessary
3438 			 */
3439 			break;
3440 		}
3441 	}
3442 
3443 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL))
3444 		ret = virtnet_send_notf_coal_cmds(vi, ec);
3445 	else
3446 		ret = virtnet_coal_params_supported(ec);
3447 
3448 	if (ret)
3449 		return ret;
3450 
3451 	if (update_napi) {
3452 		for (; queue_number < vi->max_queue_pairs; queue_number++)
3453 			vi->sq[queue_number].napi.weight = napi_weight;
3454 	}
3455 
3456 	return ret;
3457 }
3458 
virtnet_get_coalesce(struct net_device * dev,struct ethtool_coalesce * ec,struct kernel_ethtool_coalesce * kernel_coal,struct netlink_ext_ack * extack)3459 static int virtnet_get_coalesce(struct net_device *dev,
3460 				struct ethtool_coalesce *ec,
3461 				struct kernel_ethtool_coalesce *kernel_coal,
3462 				struct netlink_ext_ack *extack)
3463 {
3464 	struct virtnet_info *vi = netdev_priv(dev);
3465 
3466 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
3467 		ec->rx_coalesce_usecs = vi->intr_coal_rx.max_usecs;
3468 		ec->tx_coalesce_usecs = vi->intr_coal_tx.max_usecs;
3469 		ec->tx_max_coalesced_frames = vi->intr_coal_tx.max_packets;
3470 		ec->rx_max_coalesced_frames = vi->intr_coal_rx.max_packets;
3471 	} else {
3472 		ec->rx_max_coalesced_frames = 1;
3473 
3474 		if (vi->sq[0].napi.weight)
3475 			ec->tx_max_coalesced_frames = 1;
3476 	}
3477 
3478 	return 0;
3479 }
3480 
virtnet_set_per_queue_coalesce(struct net_device * dev,u32 queue,struct ethtool_coalesce * ec)3481 static int virtnet_set_per_queue_coalesce(struct net_device *dev,
3482 					  u32 queue,
3483 					  struct ethtool_coalesce *ec)
3484 {
3485 	struct virtnet_info *vi = netdev_priv(dev);
3486 	int ret, napi_weight;
3487 	bool update_napi = false;
3488 
3489 	if (queue >= vi->max_queue_pairs)
3490 		return -EINVAL;
3491 
3492 	/* Can't change NAPI weight if the link is up */
3493 	napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
3494 	ret = virtnet_should_update_vq_weight(dev->flags, napi_weight,
3495 					      vi->sq[queue].napi.weight,
3496 					      &update_napi);
3497 	if (ret)
3498 		return ret;
3499 
3500 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_VQ_NOTF_COAL))
3501 		ret = virtnet_send_notf_coal_vq_cmds(vi, ec, queue);
3502 	else
3503 		ret = virtnet_coal_params_supported(ec);
3504 
3505 	if (ret)
3506 		return ret;
3507 
3508 	if (update_napi)
3509 		vi->sq[queue].napi.weight = napi_weight;
3510 
3511 	return 0;
3512 }
3513 
virtnet_get_per_queue_coalesce(struct net_device * dev,u32 queue,struct ethtool_coalesce * ec)3514 static int virtnet_get_per_queue_coalesce(struct net_device *dev,
3515 					  u32 queue,
3516 					  struct ethtool_coalesce *ec)
3517 {
3518 	struct virtnet_info *vi = netdev_priv(dev);
3519 
3520 	if (queue >= vi->max_queue_pairs)
3521 		return -EINVAL;
3522 
3523 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_VQ_NOTF_COAL)) {
3524 		ec->rx_coalesce_usecs = vi->rq[queue].intr_coal.max_usecs;
3525 		ec->tx_coalesce_usecs = vi->sq[queue].intr_coal.max_usecs;
3526 		ec->tx_max_coalesced_frames = vi->sq[queue].intr_coal.max_packets;
3527 		ec->rx_max_coalesced_frames = vi->rq[queue].intr_coal.max_packets;
3528 	} else {
3529 		ec->rx_max_coalesced_frames = 1;
3530 
3531 		if (vi->sq[queue].napi.weight)
3532 			ec->tx_max_coalesced_frames = 1;
3533 	}
3534 
3535 	return 0;
3536 }
3537 
virtnet_init_settings(struct net_device * dev)3538 static void virtnet_init_settings(struct net_device *dev)
3539 {
3540 	struct virtnet_info *vi = netdev_priv(dev);
3541 
3542 	vi->speed = SPEED_UNKNOWN;
3543 	vi->duplex = DUPLEX_UNKNOWN;
3544 }
3545 
virtnet_update_settings(struct virtnet_info * vi)3546 static void virtnet_update_settings(struct virtnet_info *vi)
3547 {
3548 	u32 speed;
3549 	u8 duplex;
3550 
3551 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
3552 		return;
3553 
3554 	virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
3555 
3556 	if (ethtool_validate_speed(speed))
3557 		vi->speed = speed;
3558 
3559 	virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
3560 
3561 	if (ethtool_validate_duplex(duplex))
3562 		vi->duplex = duplex;
3563 }
3564 
virtnet_get_rxfh_key_size(struct net_device * dev)3565 static u32 virtnet_get_rxfh_key_size(struct net_device *dev)
3566 {
3567 	return ((struct virtnet_info *)netdev_priv(dev))->rss_key_size;
3568 }
3569 
virtnet_get_rxfh_indir_size(struct net_device * dev)3570 static u32 virtnet_get_rxfh_indir_size(struct net_device *dev)
3571 {
3572 	return ((struct virtnet_info *)netdev_priv(dev))->rss_indir_table_size;
3573 }
3574 
virtnet_get_rxfh(struct net_device * dev,u32 * indir,u8 * key,u8 * hfunc)3575 static int virtnet_get_rxfh(struct net_device *dev, u32 *indir, u8 *key, u8 *hfunc)
3576 {
3577 	struct virtnet_info *vi = netdev_priv(dev);
3578 	int i;
3579 
3580 	if (indir) {
3581 		for (i = 0; i < vi->rss_indir_table_size; ++i)
3582 			indir[i] = vi->ctrl->rss.indirection_table[i];
3583 	}
3584 
3585 	if (key)
3586 		memcpy(key, vi->ctrl->rss.key, vi->rss_key_size);
3587 
3588 	if (hfunc)
3589 		*hfunc = ETH_RSS_HASH_TOP;
3590 
3591 	return 0;
3592 }
3593 
virtnet_set_rxfh(struct net_device * dev,const u32 * indir,const u8 * key,const u8 hfunc)3594 static int virtnet_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key, const u8 hfunc)
3595 {
3596 	struct virtnet_info *vi = netdev_priv(dev);
3597 	bool update = false;
3598 	int i;
3599 
3600 	if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
3601 		return -EOPNOTSUPP;
3602 
3603 	if (indir) {
3604 		if (!vi->has_rss)
3605 			return -EOPNOTSUPP;
3606 
3607 		for (i = 0; i < vi->rss_indir_table_size; ++i)
3608 			vi->ctrl->rss.indirection_table[i] = indir[i];
3609 		update = true;
3610 	}
3611 	if (key) {
3612 		/* If either _F_HASH_REPORT or _F_RSS are negotiated, the
3613 		 * device provides hash calculation capabilities, that is,
3614 		 * hash_key is configured.
3615 		 */
3616 		if (!vi->has_rss && !vi->has_rss_hash_report)
3617 			return -EOPNOTSUPP;
3618 
3619 		memcpy(vi->ctrl->rss.key, key, vi->rss_key_size);
3620 		update = true;
3621 	}
3622 
3623 	if (update)
3624 		virtnet_commit_rss_command(vi);
3625 
3626 	return 0;
3627 }
3628 
virtnet_get_rxnfc(struct net_device * dev,struct ethtool_rxnfc * info,u32 * rule_locs)3629 static int virtnet_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rule_locs)
3630 {
3631 	struct virtnet_info *vi = netdev_priv(dev);
3632 	int rc = 0;
3633 
3634 	switch (info->cmd) {
3635 	case ETHTOOL_GRXRINGS:
3636 		info->data = vi->curr_queue_pairs;
3637 		break;
3638 	case ETHTOOL_GRXFH:
3639 		virtnet_get_hashflow(vi, info);
3640 		break;
3641 	default:
3642 		rc = -EOPNOTSUPP;
3643 	}
3644 
3645 	return rc;
3646 }
3647 
virtnet_set_rxnfc(struct net_device * dev,struct ethtool_rxnfc * info)3648 static int virtnet_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info)
3649 {
3650 	struct virtnet_info *vi = netdev_priv(dev);
3651 	int rc = 0;
3652 
3653 	switch (info->cmd) {
3654 	case ETHTOOL_SRXFH:
3655 		if (!virtnet_set_hashflow(vi, info))
3656 			rc = -EINVAL;
3657 
3658 		break;
3659 	default:
3660 		rc = -EOPNOTSUPP;
3661 	}
3662 
3663 	return rc;
3664 }
3665 
3666 static const struct ethtool_ops virtnet_ethtool_ops = {
3667 	.supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES |
3668 		ETHTOOL_COALESCE_USECS,
3669 	.get_drvinfo = virtnet_get_drvinfo,
3670 	.get_link = ethtool_op_get_link,
3671 	.get_ringparam = virtnet_get_ringparam,
3672 	.set_ringparam = virtnet_set_ringparam,
3673 	.get_strings = virtnet_get_strings,
3674 	.get_sset_count = virtnet_get_sset_count,
3675 	.get_ethtool_stats = virtnet_get_ethtool_stats,
3676 	.set_channels = virtnet_set_channels,
3677 	.get_channels = virtnet_get_channels,
3678 	.get_ts_info = ethtool_op_get_ts_info,
3679 	.get_link_ksettings = virtnet_get_link_ksettings,
3680 	.set_link_ksettings = virtnet_set_link_ksettings,
3681 	.set_coalesce = virtnet_set_coalesce,
3682 	.get_coalesce = virtnet_get_coalesce,
3683 	.set_per_queue_coalesce = virtnet_set_per_queue_coalesce,
3684 	.get_per_queue_coalesce = virtnet_get_per_queue_coalesce,
3685 	.get_rxfh_key_size = virtnet_get_rxfh_key_size,
3686 	.get_rxfh_indir_size = virtnet_get_rxfh_indir_size,
3687 	.get_rxfh = virtnet_get_rxfh,
3688 	.set_rxfh = virtnet_set_rxfh,
3689 	.get_rxnfc = virtnet_get_rxnfc,
3690 	.set_rxnfc = virtnet_set_rxnfc,
3691 };
3692 
virtnet_freeze_down(struct virtio_device * vdev)3693 static void virtnet_freeze_down(struct virtio_device *vdev)
3694 {
3695 	struct virtnet_info *vi = vdev->priv;
3696 
3697 	/* Make sure no work handler is accessing the device */
3698 	flush_work(&vi->config_work);
3699 
3700 	netif_tx_lock_bh(vi->dev);
3701 	netif_device_detach(vi->dev);
3702 	netif_tx_unlock_bh(vi->dev);
3703 	if (netif_running(vi->dev))
3704 		virtnet_close(vi->dev);
3705 }
3706 
3707 static int init_vqs(struct virtnet_info *vi);
3708 
virtnet_restore_up(struct virtio_device * vdev)3709 static int virtnet_restore_up(struct virtio_device *vdev)
3710 {
3711 	struct virtnet_info *vi = vdev->priv;
3712 	int err;
3713 
3714 	err = init_vqs(vi);
3715 	if (err)
3716 		return err;
3717 
3718 	virtio_device_ready(vdev);
3719 
3720 	enable_delayed_refill(vi);
3721 
3722 	if (netif_running(vi->dev)) {
3723 		err = virtnet_open(vi->dev);
3724 		if (err)
3725 			return err;
3726 	}
3727 
3728 	netif_tx_lock_bh(vi->dev);
3729 	netif_device_attach(vi->dev);
3730 	netif_tx_unlock_bh(vi->dev);
3731 	return err;
3732 }
3733 
virtnet_set_guest_offloads(struct virtnet_info * vi,u64 offloads)3734 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
3735 {
3736 	struct scatterlist sg;
3737 	vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
3738 
3739 	sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
3740 
3741 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
3742 				  VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
3743 		dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
3744 		return -EINVAL;
3745 	}
3746 
3747 	return 0;
3748 }
3749 
virtnet_clear_guest_offloads(struct virtnet_info * vi)3750 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
3751 {
3752 	u64 offloads = 0;
3753 
3754 	if (!vi->guest_offloads)
3755 		return 0;
3756 
3757 	return virtnet_set_guest_offloads(vi, offloads);
3758 }
3759 
virtnet_restore_guest_offloads(struct virtnet_info * vi)3760 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
3761 {
3762 	u64 offloads = vi->guest_offloads;
3763 
3764 	if (!vi->guest_offloads)
3765 		return 0;
3766 
3767 	return virtnet_set_guest_offloads(vi, offloads);
3768 }
3769 
virtnet_xdp_set(struct net_device * dev,struct bpf_prog * prog,struct netlink_ext_ack * extack)3770 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
3771 			   struct netlink_ext_ack *extack)
3772 {
3773 	unsigned int room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
3774 					   sizeof(struct skb_shared_info));
3775 	unsigned int max_sz = PAGE_SIZE - room - ETH_HLEN;
3776 	struct virtnet_info *vi = netdev_priv(dev);
3777 	struct bpf_prog *old_prog;
3778 	u16 xdp_qp = 0, curr_qp;
3779 	int i, err;
3780 
3781 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
3782 	    && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3783 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3784 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3785 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3786 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM) ||
3787 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) ||
3788 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6))) {
3789 		NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
3790 		return -EOPNOTSUPP;
3791 	}
3792 
3793 	if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
3794 		NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
3795 		return -EINVAL;
3796 	}
3797 
3798 	if (prog && !prog->aux->xdp_has_frags && dev->mtu > max_sz) {
3799 		NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP without frags");
3800 		netdev_warn(dev, "single-buffer XDP requires MTU less than %u\n", max_sz);
3801 		return -EINVAL;
3802 	}
3803 
3804 	curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
3805 	if (prog)
3806 		xdp_qp = nr_cpu_ids;
3807 
3808 	/* XDP requires extra queues for XDP_TX */
3809 	if (curr_qp + xdp_qp > vi->max_queue_pairs) {
3810 		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",
3811 				 curr_qp + xdp_qp, vi->max_queue_pairs);
3812 		xdp_qp = 0;
3813 	}
3814 
3815 	old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
3816 	if (!prog && !old_prog)
3817 		return 0;
3818 
3819 	if (prog)
3820 		bpf_prog_add(prog, vi->max_queue_pairs - 1);
3821 
3822 	/* Make sure NAPI is not using any XDP TX queues for RX. */
3823 	if (netif_running(dev)) {
3824 		for (i = 0; i < vi->max_queue_pairs; i++) {
3825 			napi_disable(&vi->rq[i].napi);
3826 			virtnet_napi_tx_disable(&vi->sq[i].napi);
3827 		}
3828 	}
3829 
3830 	if (!prog) {
3831 		for (i = 0; i < vi->max_queue_pairs; i++) {
3832 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3833 			if (i == 0)
3834 				virtnet_restore_guest_offloads(vi);
3835 		}
3836 		synchronize_net();
3837 	}
3838 
3839 	err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
3840 	if (err)
3841 		goto err;
3842 	netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
3843 	vi->xdp_queue_pairs = xdp_qp;
3844 
3845 	if (prog) {
3846 		vi->xdp_enabled = true;
3847 		for (i = 0; i < vi->max_queue_pairs; i++) {
3848 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3849 			if (i == 0 && !old_prog)
3850 				virtnet_clear_guest_offloads(vi);
3851 		}
3852 		if (!old_prog)
3853 			xdp_features_set_redirect_target(dev, true);
3854 	} else {
3855 		xdp_features_clear_redirect_target(dev);
3856 		vi->xdp_enabled = false;
3857 	}
3858 
3859 	for (i = 0; i < vi->max_queue_pairs; i++) {
3860 		if (old_prog)
3861 			bpf_prog_put(old_prog);
3862 		if (netif_running(dev)) {
3863 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3864 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3865 					       &vi->sq[i].napi);
3866 		}
3867 	}
3868 
3869 	return 0;
3870 
3871 err:
3872 	if (!prog) {
3873 		virtnet_clear_guest_offloads(vi);
3874 		for (i = 0; i < vi->max_queue_pairs; i++)
3875 			rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
3876 	}
3877 
3878 	if (netif_running(dev)) {
3879 		for (i = 0; i < vi->max_queue_pairs; i++) {
3880 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3881 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3882 					       &vi->sq[i].napi);
3883 		}
3884 	}
3885 	if (prog)
3886 		bpf_prog_sub(prog, vi->max_queue_pairs - 1);
3887 	return err;
3888 }
3889 
virtnet_xdp(struct net_device * dev,struct netdev_bpf * xdp)3890 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
3891 {
3892 	switch (xdp->command) {
3893 	case XDP_SETUP_PROG:
3894 		return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
3895 	default:
3896 		return -EINVAL;
3897 	}
3898 }
3899 
virtnet_get_phys_port_name(struct net_device * dev,char * buf,size_t len)3900 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
3901 				      size_t len)
3902 {
3903 	struct virtnet_info *vi = netdev_priv(dev);
3904 	int ret;
3905 
3906 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
3907 		return -EOPNOTSUPP;
3908 
3909 	ret = snprintf(buf, len, "sby");
3910 	if (ret >= len)
3911 		return -EOPNOTSUPP;
3912 
3913 	return 0;
3914 }
3915 
virtnet_set_features(struct net_device * dev,netdev_features_t features)3916 static int virtnet_set_features(struct net_device *dev,
3917 				netdev_features_t features)
3918 {
3919 	struct virtnet_info *vi = netdev_priv(dev);
3920 	u64 offloads;
3921 	int err;
3922 
3923 	if ((dev->features ^ features) & NETIF_F_GRO_HW) {
3924 		if (vi->xdp_enabled)
3925 			return -EBUSY;
3926 
3927 		if (features & NETIF_F_GRO_HW)
3928 			offloads = vi->guest_offloads_capable;
3929 		else
3930 			offloads = vi->guest_offloads_capable &
3931 				   ~GUEST_OFFLOAD_GRO_HW_MASK;
3932 
3933 		err = virtnet_set_guest_offloads(vi, offloads);
3934 		if (err)
3935 			return err;
3936 		vi->guest_offloads = offloads;
3937 	}
3938 
3939 	if ((dev->features ^ features) & NETIF_F_RXHASH) {
3940 		if (features & NETIF_F_RXHASH)
3941 			vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
3942 		else
3943 			vi->ctrl->rss.hash_types = VIRTIO_NET_HASH_REPORT_NONE;
3944 
3945 		if (!virtnet_commit_rss_command(vi))
3946 			return -EINVAL;
3947 	}
3948 
3949 	return 0;
3950 }
3951 
virtnet_tx_timeout(struct net_device * dev,unsigned int txqueue)3952 static void virtnet_tx_timeout(struct net_device *dev, unsigned int txqueue)
3953 {
3954 	struct virtnet_info *priv = netdev_priv(dev);
3955 	struct send_queue *sq = &priv->sq[txqueue];
3956 	struct netdev_queue *txq = netdev_get_tx_queue(dev, txqueue);
3957 
3958 	u64_stats_update_begin(&sq->stats.syncp);
3959 	u64_stats_inc(&sq->stats.tx_timeouts);
3960 	u64_stats_update_end(&sq->stats.syncp);
3961 
3962 	netdev_err(dev, "TX timeout on queue: %u, sq: %s, vq: 0x%x, name: %s, %u usecs ago\n",
3963 		   txqueue, sq->name, sq->vq->index, sq->vq->name,
3964 		   jiffies_to_usecs(jiffies - READ_ONCE(txq->trans_start)));
3965 }
3966 
3967 static const struct net_device_ops virtnet_netdev = {
3968 	.ndo_open            = virtnet_open,
3969 	.ndo_stop   	     = virtnet_close,
3970 	.ndo_start_xmit      = start_xmit,
3971 	.ndo_validate_addr   = eth_validate_addr,
3972 	.ndo_set_mac_address = virtnet_set_mac_address,
3973 	.ndo_set_rx_mode     = virtnet_set_rx_mode,
3974 	.ndo_get_stats64     = virtnet_stats,
3975 	.ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
3976 	.ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
3977 	.ndo_bpf		= virtnet_xdp,
3978 	.ndo_xdp_xmit		= virtnet_xdp_xmit,
3979 	.ndo_features_check	= passthru_features_check,
3980 	.ndo_get_phys_port_name	= virtnet_get_phys_port_name,
3981 	.ndo_set_features	= virtnet_set_features,
3982 	.ndo_tx_timeout		= virtnet_tx_timeout,
3983 };
3984 
virtnet_config_changed_work(struct work_struct * work)3985 static void virtnet_config_changed_work(struct work_struct *work)
3986 {
3987 	struct virtnet_info *vi =
3988 		container_of(work, struct virtnet_info, config_work);
3989 	u16 v;
3990 
3991 	if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
3992 				 struct virtio_net_config, status, &v) < 0)
3993 		return;
3994 
3995 	if (v & VIRTIO_NET_S_ANNOUNCE) {
3996 		netdev_notify_peers(vi->dev);
3997 		virtnet_ack_link_announce(vi);
3998 	}
3999 
4000 	/* Ignore unknown (future) status bits */
4001 	v &= VIRTIO_NET_S_LINK_UP;
4002 
4003 	if (vi->status == v)
4004 		return;
4005 
4006 	vi->status = v;
4007 
4008 	if (vi->status & VIRTIO_NET_S_LINK_UP) {
4009 		virtnet_update_settings(vi);
4010 		netif_carrier_on(vi->dev);
4011 		netif_tx_wake_all_queues(vi->dev);
4012 	} else {
4013 		netif_carrier_off(vi->dev);
4014 		netif_tx_stop_all_queues(vi->dev);
4015 	}
4016 }
4017 
virtnet_config_changed(struct virtio_device * vdev)4018 static void virtnet_config_changed(struct virtio_device *vdev)
4019 {
4020 	struct virtnet_info *vi = vdev->priv;
4021 
4022 	schedule_work(&vi->config_work);
4023 }
4024 
virtnet_free_queues(struct virtnet_info * vi)4025 static void virtnet_free_queues(struct virtnet_info *vi)
4026 {
4027 	int i;
4028 
4029 	for (i = 0; i < vi->max_queue_pairs; i++) {
4030 		__netif_napi_del(&vi->rq[i].napi);
4031 		__netif_napi_del(&vi->sq[i].napi);
4032 	}
4033 
4034 	/* We called __netif_napi_del(),
4035 	 * we need to respect an RCU grace period before freeing vi->rq
4036 	 */
4037 	synchronize_net();
4038 
4039 	kfree(vi->rq);
4040 	kfree(vi->sq);
4041 	kfree(vi->ctrl);
4042 }
4043 
_free_receive_bufs(struct virtnet_info * vi)4044 static void _free_receive_bufs(struct virtnet_info *vi)
4045 {
4046 	struct bpf_prog *old_prog;
4047 	int i;
4048 
4049 	for (i = 0; i < vi->max_queue_pairs; i++) {
4050 		while (vi->rq[i].pages)
4051 			__free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
4052 
4053 		old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
4054 		RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
4055 		if (old_prog)
4056 			bpf_prog_put(old_prog);
4057 	}
4058 }
4059 
free_receive_bufs(struct virtnet_info * vi)4060 static void free_receive_bufs(struct virtnet_info *vi)
4061 {
4062 	rtnl_lock();
4063 	_free_receive_bufs(vi);
4064 	rtnl_unlock();
4065 }
4066 
free_receive_page_frags(struct virtnet_info * vi)4067 static void free_receive_page_frags(struct virtnet_info *vi)
4068 {
4069 	int i;
4070 	for (i = 0; i < vi->max_queue_pairs; i++)
4071 		if (vi->rq[i].alloc_frag.page) {
4072 			if (vi->rq[i].do_dma && vi->rq[i].last_dma)
4073 				virtnet_rq_unmap(&vi->rq[i], vi->rq[i].last_dma, 0);
4074 			put_page(vi->rq[i].alloc_frag.page);
4075 		}
4076 }
4077 
virtnet_sq_free_unused_buf(struct virtqueue * vq,void * buf)4078 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf)
4079 {
4080 	if (!is_xdp_frame(buf))
4081 		dev_kfree_skb(buf);
4082 	else
4083 		xdp_return_frame(ptr_to_xdp(buf));
4084 }
4085 
free_unused_bufs(struct virtnet_info * vi)4086 static void free_unused_bufs(struct virtnet_info *vi)
4087 {
4088 	void *buf;
4089 	int i;
4090 
4091 	for (i = 0; i < vi->max_queue_pairs; i++) {
4092 		struct virtqueue *vq = vi->sq[i].vq;
4093 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
4094 			virtnet_sq_free_unused_buf(vq, buf);
4095 		cond_resched();
4096 	}
4097 
4098 	for (i = 0; i < vi->max_queue_pairs; i++) {
4099 		struct virtqueue *vq = vi->rq[i].vq;
4100 
4101 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
4102 			virtnet_rq_unmap_free_buf(vq, buf);
4103 		cond_resched();
4104 	}
4105 }
4106 
virtnet_del_vqs(struct virtnet_info * vi)4107 static void virtnet_del_vqs(struct virtnet_info *vi)
4108 {
4109 	struct virtio_device *vdev = vi->vdev;
4110 
4111 	virtnet_clean_affinity(vi);
4112 
4113 	vdev->config->del_vqs(vdev);
4114 
4115 	virtnet_free_queues(vi);
4116 }
4117 
4118 /* How large should a single buffer be so a queue full of these can fit at
4119  * least one full packet?
4120  * Logic below assumes the mergeable buffer header is used.
4121  */
mergeable_min_buf_len(struct virtnet_info * vi,struct virtqueue * vq)4122 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
4123 {
4124 	const unsigned int hdr_len = vi->hdr_len;
4125 	unsigned int rq_size = virtqueue_get_vring_size(vq);
4126 	unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
4127 	unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
4128 	unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
4129 
4130 	return max(max(min_buf_len, hdr_len) - hdr_len,
4131 		   (unsigned int)GOOD_PACKET_LEN);
4132 }
4133 
virtnet_find_vqs(struct virtnet_info * vi)4134 static int virtnet_find_vqs(struct virtnet_info *vi)
4135 {
4136 	vq_callback_t **callbacks;
4137 	struct virtqueue **vqs;
4138 	const char **names;
4139 	int ret = -ENOMEM;
4140 	int total_vqs;
4141 	bool *ctx;
4142 	u16 i;
4143 
4144 	/* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
4145 	 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
4146 	 * possible control vq.
4147 	 */
4148 	total_vqs = vi->max_queue_pairs * 2 +
4149 		    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
4150 
4151 	/* Allocate space for find_vqs parameters */
4152 	vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
4153 	if (!vqs)
4154 		goto err_vq;
4155 	callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
4156 	if (!callbacks)
4157 		goto err_callback;
4158 	names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
4159 	if (!names)
4160 		goto err_names;
4161 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
4162 		ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
4163 		if (!ctx)
4164 			goto err_ctx;
4165 	} else {
4166 		ctx = NULL;
4167 	}
4168 
4169 	/* Parameters for control virtqueue, if any */
4170 	if (vi->has_cvq) {
4171 		callbacks[total_vqs - 1] = NULL;
4172 		names[total_vqs - 1] = "control";
4173 	}
4174 
4175 	/* Allocate/initialize parameters for send/receive virtqueues */
4176 	for (i = 0; i < vi->max_queue_pairs; i++) {
4177 		callbacks[rxq2vq(i)] = skb_recv_done;
4178 		callbacks[txq2vq(i)] = skb_xmit_done;
4179 		sprintf(vi->rq[i].name, "input.%u", i);
4180 		sprintf(vi->sq[i].name, "output.%u", i);
4181 		names[rxq2vq(i)] = vi->rq[i].name;
4182 		names[txq2vq(i)] = vi->sq[i].name;
4183 		if (ctx)
4184 			ctx[rxq2vq(i)] = true;
4185 	}
4186 
4187 	ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
4188 				  names, ctx, NULL);
4189 	if (ret)
4190 		goto err_find;
4191 
4192 	if (vi->has_cvq) {
4193 		vi->cvq = vqs[total_vqs - 1];
4194 		if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
4195 			vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
4196 	}
4197 
4198 	for (i = 0; i < vi->max_queue_pairs; i++) {
4199 		vi->rq[i].vq = vqs[rxq2vq(i)];
4200 		vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
4201 		vi->sq[i].vq = vqs[txq2vq(i)];
4202 	}
4203 
4204 	/* run here: ret == 0. */
4205 
4206 
4207 err_find:
4208 	kfree(ctx);
4209 err_ctx:
4210 	kfree(names);
4211 err_names:
4212 	kfree(callbacks);
4213 err_callback:
4214 	kfree(vqs);
4215 err_vq:
4216 	return ret;
4217 }
4218 
virtnet_alloc_queues(struct virtnet_info * vi)4219 static int virtnet_alloc_queues(struct virtnet_info *vi)
4220 {
4221 	int i;
4222 
4223 	if (vi->has_cvq) {
4224 		vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
4225 		if (!vi->ctrl)
4226 			goto err_ctrl;
4227 	} else {
4228 		vi->ctrl = NULL;
4229 	}
4230 	vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
4231 	if (!vi->sq)
4232 		goto err_sq;
4233 	vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
4234 	if (!vi->rq)
4235 		goto err_rq;
4236 
4237 	INIT_DELAYED_WORK(&vi->refill, refill_work);
4238 	for (i = 0; i < vi->max_queue_pairs; i++) {
4239 		vi->rq[i].pages = NULL;
4240 		netif_napi_add_weight(vi->dev, &vi->rq[i].napi, virtnet_poll,
4241 				      napi_weight);
4242 		netif_napi_add_tx_weight(vi->dev, &vi->sq[i].napi,
4243 					 virtnet_poll_tx,
4244 					 napi_tx ? napi_weight : 0);
4245 
4246 		sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
4247 		ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
4248 		sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
4249 
4250 		u64_stats_init(&vi->rq[i].stats.syncp);
4251 		u64_stats_init(&vi->sq[i].stats.syncp);
4252 	}
4253 
4254 	return 0;
4255 
4256 err_rq:
4257 	kfree(vi->sq);
4258 err_sq:
4259 	kfree(vi->ctrl);
4260 err_ctrl:
4261 	return -ENOMEM;
4262 }
4263 
init_vqs(struct virtnet_info * vi)4264 static int init_vqs(struct virtnet_info *vi)
4265 {
4266 	int ret;
4267 
4268 	/* Allocate send & receive queues */
4269 	ret = virtnet_alloc_queues(vi);
4270 	if (ret)
4271 		goto err;
4272 
4273 	ret = virtnet_find_vqs(vi);
4274 	if (ret)
4275 		goto err_free;
4276 
4277 	virtnet_rq_set_premapped(vi);
4278 
4279 	cpus_read_lock();
4280 	virtnet_set_affinity(vi);
4281 	cpus_read_unlock();
4282 
4283 	return 0;
4284 
4285 err_free:
4286 	virtnet_free_queues(vi);
4287 err:
4288 	return ret;
4289 }
4290 
4291 #ifdef CONFIG_SYSFS
mergeable_rx_buffer_size_show(struct netdev_rx_queue * queue,char * buf)4292 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
4293 		char *buf)
4294 {
4295 	struct virtnet_info *vi = netdev_priv(queue->dev);
4296 	unsigned int queue_index = get_netdev_rx_queue_index(queue);
4297 	unsigned int headroom = virtnet_get_headroom(vi);
4298 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
4299 	struct ewma_pkt_len *avg;
4300 
4301 	BUG_ON(queue_index >= vi->max_queue_pairs);
4302 	avg = &vi->rq[queue_index].mrg_avg_pkt_len;
4303 	return sprintf(buf, "%u\n",
4304 		       get_mergeable_buf_len(&vi->rq[queue_index], avg,
4305 				       SKB_DATA_ALIGN(headroom + tailroom)));
4306 }
4307 
4308 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
4309 	__ATTR_RO(mergeable_rx_buffer_size);
4310 
4311 static struct attribute *virtio_net_mrg_rx_attrs[] = {
4312 	&mergeable_rx_buffer_size_attribute.attr,
4313 	NULL
4314 };
4315 
4316 static const struct attribute_group virtio_net_mrg_rx_group = {
4317 	.name = "virtio_net",
4318 	.attrs = virtio_net_mrg_rx_attrs
4319 };
4320 #endif
4321 
virtnet_fail_on_feature(struct virtio_device * vdev,unsigned int fbit,const char * fname,const char * dname)4322 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
4323 				    unsigned int fbit,
4324 				    const char *fname, const char *dname)
4325 {
4326 	if (!virtio_has_feature(vdev, fbit))
4327 		return false;
4328 
4329 	dev_err(&vdev->dev, "device advertises feature %s but not %s",
4330 		fname, dname);
4331 
4332 	return true;
4333 }
4334 
4335 #define VIRTNET_FAIL_ON(vdev, fbit, dbit)			\
4336 	virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
4337 
virtnet_validate_features(struct virtio_device * vdev)4338 static bool virtnet_validate_features(struct virtio_device *vdev)
4339 {
4340 	if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
4341 	    (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
4342 			     "VIRTIO_NET_F_CTRL_VQ") ||
4343 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
4344 			     "VIRTIO_NET_F_CTRL_VQ") ||
4345 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
4346 			     "VIRTIO_NET_F_CTRL_VQ") ||
4347 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
4348 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
4349 			     "VIRTIO_NET_F_CTRL_VQ") ||
4350 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_RSS,
4351 			     "VIRTIO_NET_F_CTRL_VQ") ||
4352 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_HASH_REPORT,
4353 			     "VIRTIO_NET_F_CTRL_VQ") ||
4354 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_NOTF_COAL,
4355 			     "VIRTIO_NET_F_CTRL_VQ") ||
4356 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_VQ_NOTF_COAL,
4357 			     "VIRTIO_NET_F_CTRL_VQ"))) {
4358 		return false;
4359 	}
4360 
4361 	return true;
4362 }
4363 
4364 #define MIN_MTU ETH_MIN_MTU
4365 #define MAX_MTU ETH_MAX_MTU
4366 
virtnet_validate(struct virtio_device * vdev)4367 static int virtnet_validate(struct virtio_device *vdev)
4368 {
4369 	if (!vdev->config->get) {
4370 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
4371 			__func__);
4372 		return -EINVAL;
4373 	}
4374 
4375 	if (!virtnet_validate_features(vdev))
4376 		return -EINVAL;
4377 
4378 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
4379 		int mtu = virtio_cread16(vdev,
4380 					 offsetof(struct virtio_net_config,
4381 						  mtu));
4382 		if (mtu < MIN_MTU)
4383 			__virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
4384 	}
4385 
4386 	if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY) &&
4387 	    !virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
4388 		dev_warn(&vdev->dev, "device advertises feature VIRTIO_NET_F_STANDBY but not VIRTIO_NET_F_MAC, disabling standby");
4389 		__virtio_clear_bit(vdev, VIRTIO_NET_F_STANDBY);
4390 	}
4391 
4392 	return 0;
4393 }
4394 
virtnet_check_guest_gso(const struct virtnet_info * vi)4395 static bool virtnet_check_guest_gso(const struct virtnet_info *vi)
4396 {
4397 	return virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
4398 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
4399 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
4400 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
4401 		(virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) &&
4402 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6));
4403 }
4404 
virtnet_set_big_packets(struct virtnet_info * vi,const int mtu)4405 static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu)
4406 {
4407 	bool guest_gso = virtnet_check_guest_gso(vi);
4408 
4409 	/* If device can receive ANY guest GSO packets, regardless of mtu,
4410 	 * allocate packets of maximum size, otherwise limit it to only
4411 	 * mtu size worth only.
4412 	 */
4413 	if (mtu > ETH_DATA_LEN || guest_gso) {
4414 		vi->big_packets = true;
4415 		vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE);
4416 	}
4417 }
4418 
virtnet_probe(struct virtio_device * vdev)4419 static int virtnet_probe(struct virtio_device *vdev)
4420 {
4421 	int i, err = -ENOMEM;
4422 	struct net_device *dev;
4423 	struct virtnet_info *vi;
4424 	u16 max_queue_pairs;
4425 	int mtu = 0;
4426 
4427 	/* Find if host supports multiqueue/rss virtio_net device */
4428 	max_queue_pairs = 1;
4429 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MQ) || virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
4430 		max_queue_pairs =
4431 		     virtio_cread16(vdev, offsetof(struct virtio_net_config, max_virtqueue_pairs));
4432 
4433 	/* We need at least 2 queue's */
4434 	if (max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
4435 	    max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
4436 	    !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
4437 		max_queue_pairs = 1;
4438 
4439 	/* Allocate ourselves a network device with room for our info */
4440 	dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
4441 	if (!dev)
4442 		return -ENOMEM;
4443 
4444 	/* Set up network device as normal. */
4445 	dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
4446 			   IFF_TX_SKB_NO_LINEAR;
4447 	dev->netdev_ops = &virtnet_netdev;
4448 	dev->features = NETIF_F_HIGHDMA;
4449 
4450 	dev->ethtool_ops = &virtnet_ethtool_ops;
4451 	SET_NETDEV_DEV(dev, &vdev->dev);
4452 
4453 	/* Do we support "hardware" checksums? */
4454 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
4455 		/* This opens up the world of extra features. */
4456 		dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
4457 		if (csum)
4458 			dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
4459 
4460 		if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
4461 			dev->hw_features |= NETIF_F_TSO
4462 				| NETIF_F_TSO_ECN | NETIF_F_TSO6;
4463 		}
4464 		/* Individual feature bits: what can host handle? */
4465 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
4466 			dev->hw_features |= NETIF_F_TSO;
4467 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
4468 			dev->hw_features |= NETIF_F_TSO6;
4469 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
4470 			dev->hw_features |= NETIF_F_TSO_ECN;
4471 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_USO))
4472 			dev->hw_features |= NETIF_F_GSO_UDP_L4;
4473 
4474 		dev->features |= NETIF_F_GSO_ROBUST;
4475 
4476 		if (gso)
4477 			dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
4478 		/* (!csum && gso) case will be fixed by register_netdev() */
4479 	}
4480 
4481 	/* 1. With VIRTIO_NET_F_GUEST_CSUM negotiation, the driver doesn't
4482 	 * need to calculate checksums for partially checksummed packets,
4483 	 * as they're considered valid by the upper layer.
4484 	 * 2. Without VIRTIO_NET_F_GUEST_CSUM negotiation, the driver only
4485 	 * receives fully checksummed packets. The device may assist in
4486 	 * validating these packets' checksums, so the driver won't have to.
4487 	 */
4488 	dev->features |= NETIF_F_RXCSUM;
4489 
4490 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
4491 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
4492 		dev->features |= NETIF_F_GRO_HW;
4493 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
4494 		dev->hw_features |= NETIF_F_GRO_HW;
4495 
4496 	dev->vlan_features = dev->features;
4497 	dev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT;
4498 
4499 	/* MTU range: 68 - 65535 */
4500 	dev->min_mtu = MIN_MTU;
4501 	dev->max_mtu = MAX_MTU;
4502 
4503 	/* Configuration may specify what MAC to use.  Otherwise random. */
4504 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
4505 		u8 addr[ETH_ALEN];
4506 
4507 		virtio_cread_bytes(vdev,
4508 				   offsetof(struct virtio_net_config, mac),
4509 				   addr, ETH_ALEN);
4510 		eth_hw_addr_set(dev, addr);
4511 	} else {
4512 		eth_hw_addr_random(dev);
4513 		dev_info(&vdev->dev, "Assigned random MAC address %pM\n",
4514 			 dev->dev_addr);
4515 	}
4516 
4517 	/* Set up our device-specific information */
4518 	vi = netdev_priv(dev);
4519 	vi->dev = dev;
4520 	vi->vdev = vdev;
4521 	vdev->priv = vi;
4522 
4523 	INIT_WORK(&vi->config_work, virtnet_config_changed_work);
4524 	spin_lock_init(&vi->refill_lock);
4525 
4526 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) {
4527 		vi->mergeable_rx_bufs = true;
4528 		dev->xdp_features |= NETDEV_XDP_ACT_RX_SG;
4529 	}
4530 
4531 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
4532 		vi->intr_coal_rx.max_usecs = 0;
4533 		vi->intr_coal_tx.max_usecs = 0;
4534 		vi->intr_coal_tx.max_packets = 0;
4535 		vi->intr_coal_rx.max_packets = 0;
4536 	}
4537 
4538 	if (virtio_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT))
4539 		vi->has_rss_hash_report = true;
4540 
4541 	if (virtio_has_feature(vdev, VIRTIO_NET_F_RSS)) {
4542 		vi->has_rss = true;
4543 
4544 		vi->rss_indir_table_size =
4545 			virtio_cread16(vdev, offsetof(struct virtio_net_config,
4546 				rss_max_indirection_table_length));
4547 	}
4548 
4549 	if (vi->has_rss || vi->has_rss_hash_report) {
4550 		vi->rss_key_size =
4551 			virtio_cread8(vdev, offsetof(struct virtio_net_config, rss_max_key_size));
4552 
4553 		vi->rss_hash_types_supported =
4554 		    virtio_cread32(vdev, offsetof(struct virtio_net_config, supported_hash_types));
4555 		vi->rss_hash_types_supported &=
4556 				~(VIRTIO_NET_RSS_HASH_TYPE_IP_EX |
4557 				  VIRTIO_NET_RSS_HASH_TYPE_TCP_EX |
4558 				  VIRTIO_NET_RSS_HASH_TYPE_UDP_EX);
4559 
4560 		dev->hw_features |= NETIF_F_RXHASH;
4561 	}
4562 
4563 	if (vi->has_rss_hash_report)
4564 		vi->hdr_len = sizeof(struct virtio_net_hdr_v1_hash);
4565 	else if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
4566 		 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4567 		vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
4568 	else
4569 		vi->hdr_len = sizeof(struct virtio_net_hdr);
4570 
4571 	if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
4572 	    virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4573 		vi->any_header_sg = true;
4574 
4575 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
4576 		vi->has_cvq = true;
4577 
4578 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
4579 		mtu = virtio_cread16(vdev,
4580 				     offsetof(struct virtio_net_config,
4581 					      mtu));
4582 		if (mtu < dev->min_mtu) {
4583 			/* Should never trigger: MTU was previously validated
4584 			 * in virtnet_validate.
4585 			 */
4586 			dev_err(&vdev->dev,
4587 				"device MTU appears to have changed it is now %d < %d",
4588 				mtu, dev->min_mtu);
4589 			err = -EINVAL;
4590 			goto free;
4591 		}
4592 
4593 		dev->mtu = mtu;
4594 		dev->max_mtu = mtu;
4595 	}
4596 
4597 	virtnet_set_big_packets(vi, mtu);
4598 
4599 	if (vi->any_header_sg)
4600 		dev->needed_headroom = vi->hdr_len;
4601 
4602 	/* Enable multiqueue by default */
4603 	if (num_online_cpus() >= max_queue_pairs)
4604 		vi->curr_queue_pairs = max_queue_pairs;
4605 	else
4606 		vi->curr_queue_pairs = num_online_cpus();
4607 	vi->max_queue_pairs = max_queue_pairs;
4608 
4609 	/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
4610 	err = init_vqs(vi);
4611 	if (err)
4612 		goto free;
4613 
4614 #ifdef CONFIG_SYSFS
4615 	if (vi->mergeable_rx_bufs)
4616 		dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
4617 #endif
4618 	netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
4619 	netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
4620 
4621 	virtnet_init_settings(dev);
4622 
4623 	if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
4624 		vi->failover = net_failover_create(vi->dev);
4625 		if (IS_ERR(vi->failover)) {
4626 			err = PTR_ERR(vi->failover);
4627 			goto free_vqs;
4628 		}
4629 	}
4630 
4631 	if (vi->has_rss || vi->has_rss_hash_report)
4632 		virtnet_init_default_rss(vi);
4633 
4634 	/* serialize netdev register + virtio_device_ready() with ndo_open() */
4635 	rtnl_lock();
4636 
4637 	err = register_netdevice(dev);
4638 	if (err) {
4639 		pr_debug("virtio_net: registering device failed\n");
4640 		rtnl_unlock();
4641 		goto free_failover;
4642 	}
4643 
4644 	virtio_device_ready(vdev);
4645 
4646 	_virtnet_set_queues(vi, vi->curr_queue_pairs);
4647 
4648 	/* a random MAC address has been assigned, notify the device.
4649 	 * We don't fail probe if VIRTIO_NET_F_CTRL_MAC_ADDR is not there
4650 	 * because many devices work fine without getting MAC explicitly
4651 	 */
4652 	if (!virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
4653 	    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
4654 		struct scatterlist sg;
4655 
4656 		sg_init_one(&sg, dev->dev_addr, dev->addr_len);
4657 		if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
4658 					  VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
4659 			pr_debug("virtio_net: setting MAC address failed\n");
4660 			rtnl_unlock();
4661 			err = -EINVAL;
4662 			goto free_unregister_netdev;
4663 		}
4664 	}
4665 
4666 	rtnl_unlock();
4667 
4668 	err = virtnet_cpu_notif_add(vi);
4669 	if (err) {
4670 		pr_debug("virtio_net: registering cpu notifier failed\n");
4671 		goto free_unregister_netdev;
4672 	}
4673 
4674 	/* Assume link up if device can't report link status,
4675 	   otherwise get link status from config. */
4676 	netif_carrier_off(dev);
4677 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
4678 		schedule_work(&vi->config_work);
4679 	} else {
4680 		vi->status = VIRTIO_NET_S_LINK_UP;
4681 		virtnet_update_settings(vi);
4682 		netif_carrier_on(dev);
4683 	}
4684 
4685 	for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
4686 		if (virtio_has_feature(vi->vdev, guest_offloads[i]))
4687 			set_bit(guest_offloads[i], &vi->guest_offloads);
4688 	vi->guest_offloads_capable = vi->guest_offloads;
4689 
4690 	pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
4691 		 dev->name, max_queue_pairs);
4692 
4693 	return 0;
4694 
4695 free_unregister_netdev:
4696 	unregister_netdev(dev);
4697 free_failover:
4698 	net_failover_destroy(vi->failover);
4699 free_vqs:
4700 	virtio_reset_device(vdev);
4701 	cancel_delayed_work_sync(&vi->refill);
4702 	free_receive_page_frags(vi);
4703 	virtnet_del_vqs(vi);
4704 free:
4705 	free_netdev(dev);
4706 	return err;
4707 }
4708 
remove_vq_common(struct virtnet_info * vi)4709 static void remove_vq_common(struct virtnet_info *vi)
4710 {
4711 	virtio_reset_device(vi->vdev);
4712 
4713 	/* Free unused buffers in both send and recv, if any. */
4714 	free_unused_bufs(vi);
4715 
4716 	free_receive_bufs(vi);
4717 
4718 	free_receive_page_frags(vi);
4719 
4720 	virtnet_del_vqs(vi);
4721 }
4722 
virtnet_remove(struct virtio_device * vdev)4723 static void virtnet_remove(struct virtio_device *vdev)
4724 {
4725 	struct virtnet_info *vi = vdev->priv;
4726 
4727 	virtnet_cpu_notif_remove(vi);
4728 
4729 	/* Make sure no work handler is accessing the device. */
4730 	flush_work(&vi->config_work);
4731 
4732 	unregister_netdev(vi->dev);
4733 
4734 	net_failover_destroy(vi->failover);
4735 
4736 	remove_vq_common(vi);
4737 
4738 	free_netdev(vi->dev);
4739 }
4740 
virtnet_freeze(struct virtio_device * vdev)4741 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
4742 {
4743 	struct virtnet_info *vi = vdev->priv;
4744 
4745 	virtnet_cpu_notif_remove(vi);
4746 	virtnet_freeze_down(vdev);
4747 	remove_vq_common(vi);
4748 
4749 	return 0;
4750 }
4751 
virtnet_restore(struct virtio_device * vdev)4752 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
4753 {
4754 	struct virtnet_info *vi = vdev->priv;
4755 	int err;
4756 
4757 	err = virtnet_restore_up(vdev);
4758 	if (err)
4759 		return err;
4760 	virtnet_set_queues(vi, vi->curr_queue_pairs);
4761 
4762 	err = virtnet_cpu_notif_add(vi);
4763 	if (err) {
4764 		virtnet_freeze_down(vdev);
4765 		remove_vq_common(vi);
4766 		return err;
4767 	}
4768 
4769 	return 0;
4770 }
4771 
4772 static struct virtio_device_id id_table[] = {
4773 	{ VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
4774 	{ 0 },
4775 };
4776 
4777 #define VIRTNET_FEATURES \
4778 	VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
4779 	VIRTIO_NET_F_MAC, \
4780 	VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
4781 	VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
4782 	VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
4783 	VIRTIO_NET_F_HOST_USO, VIRTIO_NET_F_GUEST_USO4, VIRTIO_NET_F_GUEST_USO6, \
4784 	VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
4785 	VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
4786 	VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
4787 	VIRTIO_NET_F_CTRL_MAC_ADDR, \
4788 	VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
4789 	VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY, \
4790 	VIRTIO_NET_F_RSS, VIRTIO_NET_F_HASH_REPORT, VIRTIO_NET_F_NOTF_COAL, \
4791 	VIRTIO_NET_F_VQ_NOTF_COAL, \
4792 	VIRTIO_NET_F_GUEST_HDRLEN
4793 
4794 static unsigned int features[] = {
4795 	VIRTNET_FEATURES,
4796 };
4797 
4798 static unsigned int features_legacy[] = {
4799 	VIRTNET_FEATURES,
4800 	VIRTIO_NET_F_GSO,
4801 	VIRTIO_F_ANY_LAYOUT,
4802 };
4803 
4804 static struct virtio_driver virtio_net_driver = {
4805 	.feature_table = features,
4806 	.feature_table_size = ARRAY_SIZE(features),
4807 	.feature_table_legacy = features_legacy,
4808 	.feature_table_size_legacy = ARRAY_SIZE(features_legacy),
4809 	.driver.name =	KBUILD_MODNAME,
4810 	.driver.owner =	THIS_MODULE,
4811 	.id_table =	id_table,
4812 	.validate =	virtnet_validate,
4813 	.probe =	virtnet_probe,
4814 	.remove =	virtnet_remove,
4815 	.config_changed = virtnet_config_changed,
4816 #ifdef CONFIG_PM_SLEEP
4817 	.freeze =	virtnet_freeze,
4818 	.restore =	virtnet_restore,
4819 #endif
4820 };
4821 
virtio_net_driver_init(void)4822 static __init int virtio_net_driver_init(void)
4823 {
4824 	int ret;
4825 
4826 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
4827 				      virtnet_cpu_online,
4828 				      virtnet_cpu_down_prep);
4829 	if (ret < 0)
4830 		goto out;
4831 	virtionet_online = ret;
4832 	ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
4833 				      NULL, virtnet_cpu_dead);
4834 	if (ret)
4835 		goto err_dead;
4836 	ret = register_virtio_driver(&virtio_net_driver);
4837 	if (ret)
4838 		goto err_virtio;
4839 	return 0;
4840 err_virtio:
4841 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4842 err_dead:
4843 	cpuhp_remove_multi_state(virtionet_online);
4844 out:
4845 	return ret;
4846 }
4847 module_init(virtio_net_driver_init);
4848 
virtio_net_driver_exit(void)4849 static __exit void virtio_net_driver_exit(void)
4850 {
4851 	unregister_virtio_driver(&virtio_net_driver);
4852 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4853 	cpuhp_remove_multi_state(virtionet_online);
4854 }
4855 module_exit(virtio_net_driver_exit);
4856 
4857 MODULE_DEVICE_TABLE(virtio, id_table);
4858 MODULE_DESCRIPTION("Virtio network driver");
4859 MODULE_LICENSE("GPL");
4860