• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* A network driver using virtio.
3  *
4  * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
5  */
6 //#define DEBUG
7 #include <linux/netdevice.h>
8 #include <linux/etherdevice.h>
9 #include <linux/ethtool.h>
10 #include <linux/module.h>
11 #include <linux/virtio.h>
12 #include <linux/virtio_net.h>
13 #include <linux/bpf.h>
14 #include <linux/bpf_trace.h>
15 #include <linux/scatterlist.h>
16 #include <linux/if_vlan.h>
17 #include <linux/slab.h>
18 #include <linux/cpu.h>
19 #include <linux/average.h>
20 #include <linux/filter.h>
21 #include <linux/kernel.h>
22 #include <net/route.h>
23 #include <net/xdp.h>
24 #include <net/net_failover.h>
25 
26 static int napi_weight = NAPI_POLL_WEIGHT;
27 module_param(napi_weight, int, 0444);
28 
29 static bool csum = true, gso = true, napi_tx = true;
30 module_param(csum, bool, 0444);
31 module_param(gso, bool, 0444);
32 module_param(napi_tx, bool, 0644);
33 
34 /* FIXME: MTU in config. */
35 #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
36 #define GOOD_COPY_LEN	128
37 
38 #define VIRTNET_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
39 
40 /* Amount of XDP headroom to prepend to packets for use by xdp_adjust_head */
41 #define VIRTIO_XDP_HEADROOM 256
42 
43 /* Separating two types of XDP xmit */
44 #define VIRTIO_XDP_TX		BIT(0)
45 #define VIRTIO_XDP_REDIR	BIT(1)
46 
47 #define VIRTIO_XDP_FLAG	BIT(0)
48 
49 /* RX packet size EWMA. The average packet size is used to determine the packet
50  * buffer size when refilling RX rings. As the entire RX ring may be refilled
51  * at once, the weight is chosen so that the EWMA will be insensitive to short-
52  * term, transient changes in packet size.
53  */
54 DECLARE_EWMA(pkt_len, 0, 64)
55 
56 #define VIRTNET_DRIVER_VERSION "1.0.0"
57 
58 static const unsigned long guest_offloads[] = {
59 	VIRTIO_NET_F_GUEST_TSO4,
60 	VIRTIO_NET_F_GUEST_TSO6,
61 	VIRTIO_NET_F_GUEST_ECN,
62 	VIRTIO_NET_F_GUEST_UFO,
63 	VIRTIO_NET_F_GUEST_CSUM
64 };
65 
66 #define GUEST_OFFLOAD_GRO_HW_MASK ((1ULL << VIRTIO_NET_F_GUEST_TSO4) | \
67 				(1ULL << VIRTIO_NET_F_GUEST_TSO6) | \
68 				(1ULL << VIRTIO_NET_F_GUEST_ECN)  | \
69 				(1ULL << VIRTIO_NET_F_GUEST_UFO))
70 
71 struct virtnet_stat_desc {
72 	char desc[ETH_GSTRING_LEN];
73 	size_t offset;
74 };
75 
76 struct virtnet_sq_stats {
77 	struct u64_stats_sync syncp;
78 	u64 packets;
79 	u64 bytes;
80 	u64 xdp_tx;
81 	u64 xdp_tx_drops;
82 	u64 kicks;
83 };
84 
85 struct virtnet_rq_stats {
86 	struct u64_stats_sync syncp;
87 	u64 packets;
88 	u64 bytes;
89 	u64 drops;
90 	u64 xdp_packets;
91 	u64 xdp_tx;
92 	u64 xdp_redirects;
93 	u64 xdp_drops;
94 	u64 kicks;
95 };
96 
97 #define VIRTNET_SQ_STAT(m)	offsetof(struct virtnet_sq_stats, m)
98 #define VIRTNET_RQ_STAT(m)	offsetof(struct virtnet_rq_stats, m)
99 
100 static const struct virtnet_stat_desc virtnet_sq_stats_desc[] = {
101 	{ "packets",		VIRTNET_SQ_STAT(packets) },
102 	{ "bytes",		VIRTNET_SQ_STAT(bytes) },
103 	{ "xdp_tx",		VIRTNET_SQ_STAT(xdp_tx) },
104 	{ "xdp_tx_drops",	VIRTNET_SQ_STAT(xdp_tx_drops) },
105 	{ "kicks",		VIRTNET_SQ_STAT(kicks) },
106 };
107 
108 static const struct virtnet_stat_desc virtnet_rq_stats_desc[] = {
109 	{ "packets",		VIRTNET_RQ_STAT(packets) },
110 	{ "bytes",		VIRTNET_RQ_STAT(bytes) },
111 	{ "drops",		VIRTNET_RQ_STAT(drops) },
112 	{ "xdp_packets",	VIRTNET_RQ_STAT(xdp_packets) },
113 	{ "xdp_tx",		VIRTNET_RQ_STAT(xdp_tx) },
114 	{ "xdp_redirects",	VIRTNET_RQ_STAT(xdp_redirects) },
115 	{ "xdp_drops",		VIRTNET_RQ_STAT(xdp_drops) },
116 	{ "kicks",		VIRTNET_RQ_STAT(kicks) },
117 };
118 
119 #define VIRTNET_SQ_STATS_LEN	ARRAY_SIZE(virtnet_sq_stats_desc)
120 #define VIRTNET_RQ_STATS_LEN	ARRAY_SIZE(virtnet_rq_stats_desc)
121 
122 /* Internal representation of a send virtqueue */
123 struct send_queue {
124 	/* Virtqueue associated with this send _queue */
125 	struct virtqueue *vq;
126 
127 	/* TX: fragments + linear part + virtio header */
128 	struct scatterlist sg[MAX_SKB_FRAGS + 2];
129 
130 	/* Name of the send queue: output.$index */
131 	char name[40];
132 
133 	struct virtnet_sq_stats stats;
134 
135 	struct napi_struct napi;
136 };
137 
138 /* Internal representation of a receive virtqueue */
139 struct receive_queue {
140 	/* Virtqueue associated with this receive_queue */
141 	struct virtqueue *vq;
142 
143 	struct napi_struct napi;
144 
145 	struct bpf_prog __rcu *xdp_prog;
146 
147 	struct virtnet_rq_stats stats;
148 
149 	/* Chain pages by the private ptr. */
150 	struct page *pages;
151 
152 	/* Average packet length for mergeable receive buffers. */
153 	struct ewma_pkt_len mrg_avg_pkt_len;
154 
155 	/* Page frag for packet buffer allocation. */
156 	struct page_frag alloc_frag;
157 
158 	/* RX: fragments + linear part + virtio header */
159 	struct scatterlist sg[MAX_SKB_FRAGS + 2];
160 
161 	/* Min single buffer size for mergeable buffers case. */
162 	unsigned int min_buf_len;
163 
164 	/* Name of this receive queue: input.$index */
165 	char name[40];
166 
167 	struct xdp_rxq_info xdp_rxq;
168 };
169 
170 /* Control VQ buffers: protected by the rtnl lock */
171 struct control_buf {
172 	struct virtio_net_ctrl_hdr hdr;
173 	virtio_net_ctrl_ack status;
174 	struct virtio_net_ctrl_mq mq;
175 	u8 promisc;
176 	u8 allmulti;
177 	__virtio16 vid;
178 	__virtio64 offloads;
179 };
180 
181 struct virtnet_info {
182 	struct virtio_device *vdev;
183 	struct virtqueue *cvq;
184 	struct net_device *dev;
185 	struct send_queue *sq;
186 	struct receive_queue *rq;
187 	unsigned int status;
188 
189 	/* Max # of queue pairs supported by the device */
190 	u16 max_queue_pairs;
191 
192 	/* # of queue pairs currently used by the driver */
193 	u16 curr_queue_pairs;
194 
195 	/* # of XDP queue pairs currently used by the driver */
196 	u16 xdp_queue_pairs;
197 
198 	/* xdp_queue_pairs may be 0, when xdp is already loaded. So add this. */
199 	bool xdp_enabled;
200 
201 	/* I like... big packets and I cannot lie! */
202 	bool big_packets;
203 
204 	/* Host will merge rx buffers for big packets (shake it! shake it!) */
205 	bool mergeable_rx_bufs;
206 
207 	/* Has control virtqueue */
208 	bool has_cvq;
209 
210 	/* Host can handle any s/g split between our header and packet data */
211 	bool any_header_sg;
212 
213 	/* Packet virtio header size */
214 	u8 hdr_len;
215 
216 	/* Work struct for refilling if we run low on memory. */
217 	struct delayed_work refill;
218 
219 	/* Work struct for config space updates */
220 	struct work_struct config_work;
221 
222 	/* Does the affinity hint is set for virtqueues? */
223 	bool affinity_hint_set;
224 
225 	/* CPU hotplug instances for online & dead */
226 	struct hlist_node node;
227 	struct hlist_node node_dead;
228 
229 	struct control_buf *ctrl;
230 
231 	/* Ethtool settings */
232 	u8 duplex;
233 	u32 speed;
234 
235 	unsigned long guest_offloads;
236 	unsigned long guest_offloads_capable;
237 
238 	/* failover when STANDBY feature enabled */
239 	struct failover *failover;
240 };
241 
242 struct padded_vnet_hdr {
243 	struct virtio_net_hdr_mrg_rxbuf hdr;
244 	/*
245 	 * hdr is in a separate sg buffer, and data sg buffer shares same page
246 	 * with this header sg. This padding makes next sg 16 byte aligned
247 	 * after the header.
248 	 */
249 	char padding[4];
250 };
251 
is_xdp_frame(void * ptr)252 static bool is_xdp_frame(void *ptr)
253 {
254 	return (unsigned long)ptr & VIRTIO_XDP_FLAG;
255 }
256 
xdp_to_ptr(struct xdp_frame * ptr)257 static void *xdp_to_ptr(struct xdp_frame *ptr)
258 {
259 	return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
260 }
261 
ptr_to_xdp(void * ptr)262 static struct xdp_frame *ptr_to_xdp(void *ptr)
263 {
264 	return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
265 }
266 
267 /* Converting between virtqueue no. and kernel tx/rx queue no.
268  * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
269  */
vq2txq(struct virtqueue * vq)270 static int vq2txq(struct virtqueue *vq)
271 {
272 	return (vq->index - 1) / 2;
273 }
274 
txq2vq(int txq)275 static int txq2vq(int txq)
276 {
277 	return txq * 2 + 1;
278 }
279 
vq2rxq(struct virtqueue * vq)280 static int vq2rxq(struct virtqueue *vq)
281 {
282 	return vq->index / 2;
283 }
284 
rxq2vq(int rxq)285 static int rxq2vq(int rxq)
286 {
287 	return rxq * 2;
288 }
289 
skb_vnet_hdr(struct sk_buff * skb)290 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
291 {
292 	return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
293 }
294 
295 /*
296  * private is used to chain pages for big packets, put the whole
297  * most recent used list in the beginning for reuse
298  */
give_pages(struct receive_queue * rq,struct page * page)299 static void give_pages(struct receive_queue *rq, struct page *page)
300 {
301 	struct page *end;
302 
303 	/* Find end of list, sew whole thing into vi->rq.pages. */
304 	for (end = page; end->private; end = (struct page *)end->private);
305 	end->private = (unsigned long)rq->pages;
306 	rq->pages = page;
307 }
308 
get_a_page(struct receive_queue * rq,gfp_t gfp_mask)309 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
310 {
311 	struct page *p = rq->pages;
312 
313 	if (p) {
314 		rq->pages = (struct page *)p->private;
315 		/* clear private here, it is used to chain pages */
316 		p->private = 0;
317 	} else
318 		p = alloc_page(gfp_mask);
319 	return p;
320 }
321 
virtqueue_napi_schedule(struct napi_struct * napi,struct virtqueue * vq)322 static void virtqueue_napi_schedule(struct napi_struct *napi,
323 				    struct virtqueue *vq)
324 {
325 	if (napi_schedule_prep(napi)) {
326 		virtqueue_disable_cb(vq);
327 		__napi_schedule(napi);
328 	}
329 }
330 
virtqueue_napi_complete(struct napi_struct * napi,struct virtqueue * vq,int processed)331 static void virtqueue_napi_complete(struct napi_struct *napi,
332 				    struct virtqueue *vq, int processed)
333 {
334 	int opaque;
335 
336 	opaque = virtqueue_enable_cb_prepare(vq);
337 	if (napi_complete_done(napi, processed)) {
338 		if (unlikely(virtqueue_poll(vq, opaque)))
339 			virtqueue_napi_schedule(napi, vq);
340 	} else {
341 		virtqueue_disable_cb(vq);
342 	}
343 }
344 
skb_xmit_done(struct virtqueue * vq)345 static void skb_xmit_done(struct virtqueue *vq)
346 {
347 	struct virtnet_info *vi = vq->vdev->priv;
348 	struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
349 
350 	/* Suppress further interrupts. */
351 	virtqueue_disable_cb(vq);
352 
353 	if (napi->weight)
354 		virtqueue_napi_schedule(napi, vq);
355 	else
356 		/* We were probably waiting for more output buffers. */
357 		netif_wake_subqueue(vi->dev, vq2txq(vq));
358 }
359 
360 #define MRG_CTX_HEADER_SHIFT 22
mergeable_len_to_ctx(unsigned int truesize,unsigned int headroom)361 static void *mergeable_len_to_ctx(unsigned int truesize,
362 				  unsigned int headroom)
363 {
364 	return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
365 }
366 
mergeable_ctx_to_headroom(void * mrg_ctx)367 static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
368 {
369 	return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
370 }
371 
mergeable_ctx_to_truesize(void * mrg_ctx)372 static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
373 {
374 	return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
375 }
376 
377 /* 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,bool hdr_valid,unsigned int metasize)378 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
379 				   struct receive_queue *rq,
380 				   struct page *page, unsigned int offset,
381 				   unsigned int len, unsigned int truesize,
382 				   bool hdr_valid, unsigned int metasize)
383 {
384 	struct sk_buff *skb;
385 	struct virtio_net_hdr_mrg_rxbuf *hdr;
386 	unsigned int copy, hdr_len, hdr_padded_len;
387 	char *p;
388 
389 	p = page_address(page) + offset;
390 
391 	/* copy small packet so we can reuse these pages for small data */
392 	skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
393 	if (unlikely(!skb))
394 		return NULL;
395 
396 	hdr = skb_vnet_hdr(skb);
397 
398 	hdr_len = vi->hdr_len;
399 	if (vi->mergeable_rx_bufs)
400 		hdr_padded_len = sizeof(*hdr);
401 	else
402 		hdr_padded_len = sizeof(struct padded_vnet_hdr);
403 
404 	/* hdr_valid means no XDP, so we can copy the vnet header */
405 	if (hdr_valid)
406 		memcpy(hdr, p, hdr_len);
407 
408 	len -= hdr_len;
409 	offset += hdr_padded_len;
410 	p += hdr_padded_len;
411 
412 	/* Copy all frame if it fits skb->head, otherwise
413 	 * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
414 	 */
415 	if (len <= skb_tailroom(skb))
416 		copy = len;
417 	else
418 		copy = ETH_HLEN + metasize;
419 	skb_put_data(skb, p, copy);
420 
421 	if (metasize) {
422 		__skb_pull(skb, metasize);
423 		skb_metadata_set(skb, metasize);
424 	}
425 
426 	len -= copy;
427 	offset += copy;
428 
429 	if (vi->mergeable_rx_bufs) {
430 		if (len)
431 			skb_add_rx_frag(skb, 0, page, offset, len, truesize);
432 		else
433 			put_page(page);
434 		return skb;
435 	}
436 
437 	/*
438 	 * Verify that we can indeed put this data into a skb.
439 	 * This is here to handle cases when the device erroneously
440 	 * tries to receive more than is possible. This is usually
441 	 * the case of a broken device.
442 	 */
443 	if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
444 		net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
445 		dev_kfree_skb(skb);
446 		return NULL;
447 	}
448 	BUG_ON(offset >= PAGE_SIZE);
449 	while (len) {
450 		unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
451 		skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
452 				frag_size, truesize);
453 		len -= frag_size;
454 		page = (struct page *)page->private;
455 		offset = 0;
456 	}
457 
458 	if (page)
459 		give_pages(rq, page);
460 
461 	return skb;
462 }
463 
__virtnet_xdp_xmit_one(struct virtnet_info * vi,struct send_queue * sq,struct xdp_frame * xdpf)464 static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
465 				   struct send_queue *sq,
466 				   struct xdp_frame *xdpf)
467 {
468 	struct virtio_net_hdr_mrg_rxbuf *hdr;
469 	int err;
470 
471 	if (unlikely(xdpf->headroom < vi->hdr_len))
472 		return -EOVERFLOW;
473 
474 	/* Make room for virtqueue hdr (also change xdpf->headroom?) */
475 	xdpf->data -= vi->hdr_len;
476 	/* Zero header and leave csum up to XDP layers */
477 	hdr = xdpf->data;
478 	memset(hdr, 0, vi->hdr_len);
479 	xdpf->len   += vi->hdr_len;
480 
481 	sg_init_one(sq->sg, xdpf->data, xdpf->len);
482 
483 	err = virtqueue_add_outbuf(sq->vq, sq->sg, 1, xdp_to_ptr(xdpf),
484 				   GFP_ATOMIC);
485 	if (unlikely(err))
486 		return -ENOSPC; /* Caller handle free/refcnt */
487 
488 	return 0;
489 }
490 
491 /* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
492  * the current cpu, so it does not need to be locked.
493  *
494  * Here we use marco instead of inline functions because we have to deal with
495  * three issues at the same time: 1. the choice of sq. 2. judge and execute the
496  * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
497  * functions to perfectly solve these three problems at the same time.
498  */
499 #define virtnet_xdp_get_sq(vi) ({                                       \
500 	struct netdev_queue *txq;                                       \
501 	typeof(vi) v = (vi);                                            \
502 	unsigned int qp;                                                \
503 									\
504 	if (v->curr_queue_pairs > nr_cpu_ids) {                         \
505 		qp = v->curr_queue_pairs - v->xdp_queue_pairs;          \
506 		qp += smp_processor_id();                               \
507 		txq = netdev_get_tx_queue(v->dev, qp);                  \
508 		__netif_tx_acquire(txq);                                \
509 	} else {                                                        \
510 		qp = smp_processor_id() % v->curr_queue_pairs;          \
511 		txq = netdev_get_tx_queue(v->dev, qp);                  \
512 		__netif_tx_lock(txq, raw_smp_processor_id());           \
513 	}                                                               \
514 	v->sq + qp;                                                     \
515 })
516 
517 #define virtnet_xdp_put_sq(vi, q) {                                     \
518 	struct netdev_queue *txq;                                       \
519 	typeof(vi) v = (vi);                                            \
520 									\
521 	txq = netdev_get_tx_queue(v->dev, (q) - v->sq);                 \
522 	if (v->curr_queue_pairs > nr_cpu_ids)                           \
523 		__netif_tx_release(txq);                                \
524 	else                                                            \
525 		__netif_tx_unlock(txq);                                 \
526 }
527 
virtnet_xdp_xmit(struct net_device * dev,int n,struct xdp_frame ** frames,u32 flags)528 static int virtnet_xdp_xmit(struct net_device *dev,
529 			    int n, struct xdp_frame **frames, u32 flags)
530 {
531 	struct virtnet_info *vi = netdev_priv(dev);
532 	struct receive_queue *rq = vi->rq;
533 	struct bpf_prog *xdp_prog;
534 	struct send_queue *sq;
535 	unsigned int len;
536 	int packets = 0;
537 	int bytes = 0;
538 	int drops = 0;
539 	int kicks = 0;
540 	int ret, err;
541 	void *ptr;
542 	int i;
543 
544 	/* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
545 	 * indicate XDP resources have been successfully allocated.
546 	 */
547 	xdp_prog = rcu_access_pointer(rq->xdp_prog);
548 	if (!xdp_prog)
549 		return -ENXIO;
550 
551 	sq = virtnet_xdp_get_sq(vi);
552 
553 	if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
554 		ret = -EINVAL;
555 		drops = n;
556 		goto out;
557 	}
558 
559 	/* Free up any pending old buffers before queueing new ones. */
560 	while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
561 		if (likely(is_xdp_frame(ptr))) {
562 			struct xdp_frame *frame = ptr_to_xdp(ptr);
563 
564 			bytes += frame->len;
565 			xdp_return_frame(frame);
566 		} else {
567 			struct sk_buff *skb = ptr;
568 
569 			bytes += skb->len;
570 			napi_consume_skb(skb, false);
571 		}
572 		packets++;
573 	}
574 
575 	for (i = 0; i < n; i++) {
576 		struct xdp_frame *xdpf = frames[i];
577 
578 		err = __virtnet_xdp_xmit_one(vi, sq, xdpf);
579 		if (err) {
580 			xdp_return_frame_rx_napi(xdpf);
581 			drops++;
582 		}
583 	}
584 	ret = n - drops;
585 
586 	if (flags & XDP_XMIT_FLUSH) {
587 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
588 			kicks = 1;
589 	}
590 out:
591 	u64_stats_update_begin(&sq->stats.syncp);
592 	sq->stats.bytes += bytes;
593 	sq->stats.packets += packets;
594 	sq->stats.xdp_tx += n;
595 	sq->stats.xdp_tx_drops += drops;
596 	sq->stats.kicks += kicks;
597 	u64_stats_update_end(&sq->stats.syncp);
598 
599 	virtnet_xdp_put_sq(vi, sq);
600 	return ret;
601 }
602 
virtnet_get_headroom(struct virtnet_info * vi)603 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
604 {
605 	return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
606 }
607 
608 /* We copy the packet for XDP in the following cases:
609  *
610  * 1) Packet is scattered across multiple rx buffers.
611  * 2) Headroom space is insufficient.
612  *
613  * This is inefficient but it's a temporary condition that
614  * we hit right after XDP is enabled and until queue is refilled
615  * with large buffers with sufficient headroom - so it should affect
616  * at most queue size packets.
617  * Afterwards, the conditions to enable
618  * XDP should preclude the underlying device from sending packets
619  * across multiple buffers (num_buf > 1), and we make sure buffers
620  * have enough headroom.
621  */
xdp_linearize_page(struct receive_queue * rq,u16 * num_buf,struct page * p,int offset,int page_off,unsigned int * len)622 static struct page *xdp_linearize_page(struct receive_queue *rq,
623 				       u16 *num_buf,
624 				       struct page *p,
625 				       int offset,
626 				       int page_off,
627 				       unsigned int *len)
628 {
629 	struct page *page = alloc_page(GFP_ATOMIC);
630 
631 	if (!page)
632 		return NULL;
633 
634 	memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
635 	page_off += *len;
636 
637 	while (--*num_buf) {
638 		int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
639 		unsigned int buflen;
640 		void *buf;
641 		int off;
642 
643 		buf = virtqueue_get_buf(rq->vq, &buflen);
644 		if (unlikely(!buf))
645 			goto err_buf;
646 
647 		p = virt_to_head_page(buf);
648 		off = buf - page_address(p);
649 
650 		/* guard against a misconfigured or uncooperative backend that
651 		 * is sending packet larger than the MTU.
652 		 */
653 		if ((page_off + buflen + tailroom) > PAGE_SIZE) {
654 			put_page(p);
655 			goto err_buf;
656 		}
657 
658 		memcpy(page_address(page) + page_off,
659 		       page_address(p) + off, buflen);
660 		page_off += buflen;
661 		put_page(p);
662 	}
663 
664 	/* Headroom does not contribute to packet length */
665 	*len = page_off - VIRTIO_XDP_HEADROOM;
666 	return page;
667 err_buf:
668 	__free_pages(page, 0);
669 	return NULL;
670 }
671 
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)672 static struct sk_buff *receive_small(struct net_device *dev,
673 				     struct virtnet_info *vi,
674 				     struct receive_queue *rq,
675 				     void *buf, void *ctx,
676 				     unsigned int len,
677 				     unsigned int *xdp_xmit,
678 				     struct virtnet_rq_stats *stats)
679 {
680 	struct sk_buff *skb;
681 	struct bpf_prog *xdp_prog;
682 	unsigned int xdp_headroom = (unsigned long)ctx;
683 	unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
684 	unsigned int headroom = vi->hdr_len + header_offset;
685 	unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
686 			      SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
687 	struct page *page = virt_to_head_page(buf);
688 	unsigned int delta = 0;
689 	struct page *xdp_page;
690 	int err;
691 	unsigned int metasize = 0;
692 
693 	len -= vi->hdr_len;
694 	stats->bytes += len;
695 
696 	if (unlikely(len > GOOD_PACKET_LEN)) {
697 		pr_debug("%s: rx error: len %u exceeds max size %d\n",
698 			 dev->name, len, GOOD_PACKET_LEN);
699 		dev->stats.rx_length_errors++;
700 		goto err_len;
701 	}
702 	rcu_read_lock();
703 	xdp_prog = rcu_dereference(rq->xdp_prog);
704 	if (xdp_prog) {
705 		struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
706 		struct xdp_frame *xdpf;
707 		struct xdp_buff xdp;
708 		void *orig_data;
709 		u32 act;
710 
711 		if (unlikely(hdr->hdr.gso_type))
712 			goto err_xdp;
713 
714 		if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
715 			int offset = buf - page_address(page) + header_offset;
716 			unsigned int tlen = len + vi->hdr_len;
717 			u16 num_buf = 1;
718 
719 			xdp_headroom = virtnet_get_headroom(vi);
720 			header_offset = VIRTNET_RX_PAD + xdp_headroom;
721 			headroom = vi->hdr_len + header_offset;
722 			buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
723 				 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
724 			xdp_page = xdp_linearize_page(rq, &num_buf, page,
725 						      offset, header_offset,
726 						      &tlen);
727 			if (!xdp_page)
728 				goto err_xdp;
729 
730 			buf = page_address(xdp_page);
731 			put_page(page);
732 			page = xdp_page;
733 		}
734 
735 		xdp.data_hard_start = buf + VIRTNET_RX_PAD + vi->hdr_len;
736 		xdp.data = xdp.data_hard_start + xdp_headroom;
737 		xdp.data_end = xdp.data + len;
738 		xdp.data_meta = xdp.data;
739 		xdp.rxq = &rq->xdp_rxq;
740 		xdp.frame_sz = buflen;
741 		orig_data = xdp.data;
742 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
743 		stats->xdp_packets++;
744 
745 		switch (act) {
746 		case XDP_PASS:
747 			/* Recalculate length in case bpf program changed it */
748 			delta = orig_data - xdp.data;
749 			len = xdp.data_end - xdp.data;
750 			metasize = xdp.data - xdp.data_meta;
751 			break;
752 		case XDP_TX:
753 			stats->xdp_tx++;
754 			xdpf = xdp_convert_buff_to_frame(&xdp);
755 			if (unlikely(!xdpf))
756 				goto err_xdp;
757 			err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
758 			if (unlikely(err < 0)) {
759 				trace_xdp_exception(vi->dev, xdp_prog, act);
760 				goto err_xdp;
761 			}
762 			*xdp_xmit |= VIRTIO_XDP_TX;
763 			rcu_read_unlock();
764 			goto xdp_xmit;
765 		case XDP_REDIRECT:
766 			stats->xdp_redirects++;
767 			err = xdp_do_redirect(dev, &xdp, xdp_prog);
768 			if (err)
769 				goto err_xdp;
770 			*xdp_xmit |= VIRTIO_XDP_REDIR;
771 			rcu_read_unlock();
772 			goto xdp_xmit;
773 		default:
774 			bpf_warn_invalid_xdp_action(act);
775 			fallthrough;
776 		case XDP_ABORTED:
777 			trace_xdp_exception(vi->dev, xdp_prog, act);
778 		case XDP_DROP:
779 			goto err_xdp;
780 		}
781 	}
782 	rcu_read_unlock();
783 
784 	skb = build_skb(buf, buflen);
785 	if (!skb) {
786 		put_page(page);
787 		goto err;
788 	}
789 	skb_reserve(skb, headroom - delta);
790 	skb_put(skb, len);
791 	if (!xdp_prog) {
792 		buf += header_offset;
793 		memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
794 	} /* keep zeroed vnet hdr since XDP is loaded */
795 
796 	if (metasize)
797 		skb_metadata_set(skb, metasize);
798 
799 err:
800 	return skb;
801 
802 err_xdp:
803 	rcu_read_unlock();
804 	stats->xdp_drops++;
805 err_len:
806 	stats->drops++;
807 	put_page(page);
808 xdp_xmit:
809 	return NULL;
810 }
811 
receive_big(struct net_device * dev,struct virtnet_info * vi,struct receive_queue * rq,void * buf,unsigned int len,struct virtnet_rq_stats * stats)812 static struct sk_buff *receive_big(struct net_device *dev,
813 				   struct virtnet_info *vi,
814 				   struct receive_queue *rq,
815 				   void *buf,
816 				   unsigned int len,
817 				   struct virtnet_rq_stats *stats)
818 {
819 	struct page *page = buf;
820 	struct sk_buff *skb =
821 		page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, true, 0);
822 
823 	stats->bytes += len - vi->hdr_len;
824 	if (unlikely(!skb))
825 		goto err;
826 
827 	return skb;
828 
829 err:
830 	stats->drops++;
831 	give_pages(rq, page);
832 	return NULL;
833 }
834 
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)835 static struct sk_buff *receive_mergeable(struct net_device *dev,
836 					 struct virtnet_info *vi,
837 					 struct receive_queue *rq,
838 					 void *buf,
839 					 void *ctx,
840 					 unsigned int len,
841 					 unsigned int *xdp_xmit,
842 					 struct virtnet_rq_stats *stats)
843 {
844 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
845 	u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
846 	struct page *page = virt_to_head_page(buf);
847 	int offset = buf - page_address(page);
848 	struct sk_buff *head_skb, *curr_skb;
849 	struct bpf_prog *xdp_prog;
850 	unsigned int truesize = mergeable_ctx_to_truesize(ctx);
851 	unsigned int headroom = mergeable_ctx_to_headroom(ctx);
852 	unsigned int metasize = 0;
853 	unsigned int frame_sz;
854 	int err;
855 
856 	head_skb = NULL;
857 	stats->bytes += len - vi->hdr_len;
858 
859 	if (unlikely(len > truesize)) {
860 		pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
861 			 dev->name, len, (unsigned long)ctx);
862 		dev->stats.rx_length_errors++;
863 		goto err_skb;
864 	}
865 	rcu_read_lock();
866 	xdp_prog = rcu_dereference(rq->xdp_prog);
867 	if (xdp_prog) {
868 		struct xdp_frame *xdpf;
869 		struct page *xdp_page;
870 		struct xdp_buff xdp;
871 		void *data;
872 		u32 act;
873 
874 		/* Transient failure which in theory could occur if
875 		 * in-flight packets from before XDP was enabled reach
876 		 * the receive path after XDP is loaded.
877 		 */
878 		if (unlikely(hdr->hdr.gso_type))
879 			goto err_xdp;
880 
881 		/* Buffers with headroom use PAGE_SIZE as alloc size,
882 		 * see add_recvbuf_mergeable() + get_mergeable_buf_len()
883 		 */
884 		frame_sz = headroom ? PAGE_SIZE : truesize;
885 
886 		/* This happens when rx buffer size is underestimated
887 		 * or headroom is not enough because of the buffer
888 		 * was refilled before XDP is set. This should only
889 		 * happen for the first several packets, so we don't
890 		 * care much about its performance.
891 		 */
892 		if (unlikely(num_buf > 1 ||
893 			     headroom < virtnet_get_headroom(vi))) {
894 			/* linearize data for XDP */
895 			xdp_page = xdp_linearize_page(rq, &num_buf,
896 						      page, offset,
897 						      VIRTIO_XDP_HEADROOM,
898 						      &len);
899 			frame_sz = PAGE_SIZE;
900 
901 			if (!xdp_page)
902 				goto err_xdp;
903 			offset = VIRTIO_XDP_HEADROOM;
904 		} else {
905 			xdp_page = page;
906 		}
907 
908 		/* Allow consuming headroom but reserve enough space to push
909 		 * the descriptor on if we get an XDP_TX return code.
910 		 */
911 		data = page_address(xdp_page) + offset;
912 		xdp.data_hard_start = data - VIRTIO_XDP_HEADROOM + vi->hdr_len;
913 		xdp.data = data + vi->hdr_len;
914 		xdp.data_end = xdp.data + (len - vi->hdr_len);
915 		xdp.data_meta = xdp.data;
916 		xdp.rxq = &rq->xdp_rxq;
917 		xdp.frame_sz = frame_sz - vi->hdr_len;
918 
919 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
920 		stats->xdp_packets++;
921 
922 		switch (act) {
923 		case XDP_PASS:
924 			metasize = xdp.data - xdp.data_meta;
925 
926 			/* recalculate offset to account for any header
927 			 * adjustments and minus the metasize to copy the
928 			 * metadata in page_to_skb(). Note other cases do not
929 			 * build an skb and avoid using offset
930 			 */
931 			offset = xdp.data - page_address(xdp_page) -
932 				 vi->hdr_len - metasize;
933 
934 			/* recalculate len if xdp.data, xdp.data_end or
935 			 * xdp.data_meta were adjusted
936 			 */
937 			len = xdp.data_end - xdp.data + vi->hdr_len + metasize;
938 			/* We can only create skb based on xdp_page. */
939 			if (unlikely(xdp_page != page)) {
940 				rcu_read_unlock();
941 				put_page(page);
942 				head_skb = page_to_skb(vi, rq, xdp_page, offset,
943 						       len, PAGE_SIZE, false,
944 						       metasize);
945 				return head_skb;
946 			}
947 			break;
948 		case XDP_TX:
949 			stats->xdp_tx++;
950 			xdpf = xdp_convert_buff_to_frame(&xdp);
951 			if (unlikely(!xdpf))
952 				goto err_xdp;
953 			err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
954 			if (unlikely(err < 0)) {
955 				trace_xdp_exception(vi->dev, xdp_prog, act);
956 				if (unlikely(xdp_page != page))
957 					put_page(xdp_page);
958 				goto err_xdp;
959 			}
960 			*xdp_xmit |= VIRTIO_XDP_TX;
961 			if (unlikely(xdp_page != page))
962 				put_page(page);
963 			rcu_read_unlock();
964 			goto xdp_xmit;
965 		case XDP_REDIRECT:
966 			stats->xdp_redirects++;
967 			err = xdp_do_redirect(dev, &xdp, xdp_prog);
968 			if (err) {
969 				if (unlikely(xdp_page != page))
970 					put_page(xdp_page);
971 				goto err_xdp;
972 			}
973 			*xdp_xmit |= VIRTIO_XDP_REDIR;
974 			if (unlikely(xdp_page != page))
975 				put_page(page);
976 			rcu_read_unlock();
977 			goto xdp_xmit;
978 		default:
979 			bpf_warn_invalid_xdp_action(act);
980 			fallthrough;
981 		case XDP_ABORTED:
982 			trace_xdp_exception(vi->dev, xdp_prog, act);
983 			fallthrough;
984 		case XDP_DROP:
985 			if (unlikely(xdp_page != page))
986 				__free_pages(xdp_page, 0);
987 			goto err_xdp;
988 		}
989 	}
990 	rcu_read_unlock();
991 
992 	head_skb = page_to_skb(vi, rq, page, offset, len, truesize, !xdp_prog,
993 			       metasize);
994 	curr_skb = head_skb;
995 
996 	if (unlikely(!curr_skb))
997 		goto err_skb;
998 	while (--num_buf) {
999 		int num_skb_frags;
1000 
1001 		buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1002 		if (unlikely(!buf)) {
1003 			pr_debug("%s: rx error: %d buffers out of %d missing\n",
1004 				 dev->name, num_buf,
1005 				 virtio16_to_cpu(vi->vdev,
1006 						 hdr->num_buffers));
1007 			dev->stats.rx_length_errors++;
1008 			goto err_buf;
1009 		}
1010 
1011 		stats->bytes += len;
1012 		page = virt_to_head_page(buf);
1013 
1014 		truesize = mergeable_ctx_to_truesize(ctx);
1015 		if (unlikely(len > truesize)) {
1016 			pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1017 				 dev->name, len, (unsigned long)ctx);
1018 			dev->stats.rx_length_errors++;
1019 			goto err_skb;
1020 		}
1021 
1022 		num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1023 		if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1024 			struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1025 
1026 			if (unlikely(!nskb))
1027 				goto err_skb;
1028 			if (curr_skb == head_skb)
1029 				skb_shinfo(curr_skb)->frag_list = nskb;
1030 			else
1031 				curr_skb->next = nskb;
1032 			curr_skb = nskb;
1033 			head_skb->truesize += nskb->truesize;
1034 			num_skb_frags = 0;
1035 		}
1036 		if (curr_skb != head_skb) {
1037 			head_skb->data_len += len;
1038 			head_skb->len += len;
1039 			head_skb->truesize += truesize;
1040 		}
1041 		offset = buf - page_address(page);
1042 		if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1043 			put_page(page);
1044 			skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1045 					     len, truesize);
1046 		} else {
1047 			skb_add_rx_frag(curr_skb, num_skb_frags, page,
1048 					offset, len, truesize);
1049 		}
1050 	}
1051 
1052 	ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1053 	return head_skb;
1054 
1055 err_xdp:
1056 	rcu_read_unlock();
1057 	stats->xdp_drops++;
1058 err_skb:
1059 	put_page(page);
1060 	while (num_buf-- > 1) {
1061 		buf = virtqueue_get_buf(rq->vq, &len);
1062 		if (unlikely(!buf)) {
1063 			pr_debug("%s: rx error: %d buffers missing\n",
1064 				 dev->name, num_buf);
1065 			dev->stats.rx_length_errors++;
1066 			break;
1067 		}
1068 		stats->bytes += len;
1069 		page = virt_to_head_page(buf);
1070 		put_page(page);
1071 	}
1072 err_buf:
1073 	stats->drops++;
1074 	dev_kfree_skb(head_skb);
1075 xdp_xmit:
1076 	return NULL;
1077 }
1078 
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)1079 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1080 			void *buf, unsigned int len, void **ctx,
1081 			unsigned int *xdp_xmit,
1082 			struct virtnet_rq_stats *stats)
1083 {
1084 	struct net_device *dev = vi->dev;
1085 	struct sk_buff *skb;
1086 	struct virtio_net_hdr_mrg_rxbuf *hdr;
1087 
1088 	if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1089 		pr_debug("%s: short packet %i\n", dev->name, len);
1090 		dev->stats.rx_length_errors++;
1091 		if (vi->mergeable_rx_bufs) {
1092 			put_page(virt_to_head_page(buf));
1093 		} else if (vi->big_packets) {
1094 			give_pages(rq, buf);
1095 		} else {
1096 			put_page(virt_to_head_page(buf));
1097 		}
1098 		return;
1099 	}
1100 
1101 	if (vi->mergeable_rx_bufs)
1102 		skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1103 					stats);
1104 	else if (vi->big_packets)
1105 		skb = receive_big(dev, vi, rq, buf, len, stats);
1106 	else
1107 		skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1108 
1109 	if (unlikely(!skb))
1110 		return;
1111 
1112 	hdr = skb_vnet_hdr(skb);
1113 
1114 	if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
1115 		skb->ip_summed = CHECKSUM_UNNECESSARY;
1116 
1117 	if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1118 				  virtio_is_little_endian(vi->vdev))) {
1119 		net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1120 				     dev->name, hdr->hdr.gso_type,
1121 				     hdr->hdr.gso_size);
1122 		goto frame_err;
1123 	}
1124 
1125 	skb_record_rx_queue(skb, vq2rxq(rq->vq));
1126 	skb->protocol = eth_type_trans(skb, dev);
1127 	pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1128 		 ntohs(skb->protocol), skb->len, skb->pkt_type);
1129 
1130 	napi_gro_receive(&rq->napi, skb);
1131 	return;
1132 
1133 frame_err:
1134 	dev->stats.rx_frame_errors++;
1135 	dev_kfree_skb(skb);
1136 }
1137 
1138 /* Unlike mergeable buffers, all buffers are allocated to the
1139  * same size, except for the headroom. For this reason we do
1140  * not need to use  mergeable_len_to_ctx here - it is enough
1141  * to store the headroom as the context ignoring the truesize.
1142  */
add_recvbuf_small(struct virtnet_info * vi,struct receive_queue * rq,gfp_t gfp)1143 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1144 			     gfp_t gfp)
1145 {
1146 	struct page_frag *alloc_frag = &rq->alloc_frag;
1147 	char *buf;
1148 	unsigned int xdp_headroom = virtnet_get_headroom(vi);
1149 	void *ctx = (void *)(unsigned long)xdp_headroom;
1150 	int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1151 	int err;
1152 
1153 	len = SKB_DATA_ALIGN(len) +
1154 	      SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1155 	if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
1156 		return -ENOMEM;
1157 
1158 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1159 	get_page(alloc_frag->page);
1160 	alloc_frag->offset += len;
1161 	sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1162 		    vi->hdr_len + GOOD_PACKET_LEN);
1163 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1164 	if (err < 0)
1165 		put_page(virt_to_head_page(buf));
1166 	return err;
1167 }
1168 
add_recvbuf_big(struct virtnet_info * vi,struct receive_queue * rq,gfp_t gfp)1169 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1170 			   gfp_t gfp)
1171 {
1172 	struct page *first, *list = NULL;
1173 	char *p;
1174 	int i, err, offset;
1175 
1176 	sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
1177 
1178 	/* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
1179 	for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
1180 		first = get_a_page(rq, gfp);
1181 		if (!first) {
1182 			if (list)
1183 				give_pages(rq, list);
1184 			return -ENOMEM;
1185 		}
1186 		sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1187 
1188 		/* chain new page in list head to match sg */
1189 		first->private = (unsigned long)list;
1190 		list = first;
1191 	}
1192 
1193 	first = get_a_page(rq, gfp);
1194 	if (!first) {
1195 		give_pages(rq, list);
1196 		return -ENOMEM;
1197 	}
1198 	p = page_address(first);
1199 
1200 	/* rq->sg[0], rq->sg[1] share the same page */
1201 	/* a separated rq->sg[0] for header - required in case !any_header_sg */
1202 	sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1203 
1204 	/* rq->sg[1] for data packet, from offset */
1205 	offset = sizeof(struct padded_vnet_hdr);
1206 	sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1207 
1208 	/* chain first in list head */
1209 	first->private = (unsigned long)list;
1210 	err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
1211 				  first, gfp);
1212 	if (err < 0)
1213 		give_pages(rq, first);
1214 
1215 	return err;
1216 }
1217 
get_mergeable_buf_len(struct receive_queue * rq,struct ewma_pkt_len * avg_pkt_len,unsigned int room)1218 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1219 					  struct ewma_pkt_len *avg_pkt_len,
1220 					  unsigned int room)
1221 {
1222 	const size_t hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1223 	unsigned int len;
1224 
1225 	if (room)
1226 		return PAGE_SIZE - room;
1227 
1228 	len = hdr_len +	clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1229 				rq->min_buf_len, PAGE_SIZE - hdr_len);
1230 
1231 	return ALIGN(len, L1_CACHE_BYTES);
1232 }
1233 
add_recvbuf_mergeable(struct virtnet_info * vi,struct receive_queue * rq,gfp_t gfp)1234 static int add_recvbuf_mergeable(struct virtnet_info *vi,
1235 				 struct receive_queue *rq, gfp_t gfp)
1236 {
1237 	struct page_frag *alloc_frag = &rq->alloc_frag;
1238 	unsigned int headroom = virtnet_get_headroom(vi);
1239 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1240 	unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1241 	char *buf;
1242 	void *ctx;
1243 	int err;
1244 	unsigned int len, hole;
1245 
1246 	/* Extra tailroom is needed to satisfy XDP's assumption. This
1247 	 * means rx frags coalescing won't work, but consider we've
1248 	 * disabled GSO for XDP, it won't be a big issue.
1249 	 */
1250 	len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1251 	if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
1252 		return -ENOMEM;
1253 
1254 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1255 	buf += headroom; /* advance address leaving hole at front of pkt */
1256 	get_page(alloc_frag->page);
1257 	alloc_frag->offset += len + room;
1258 	hole = alloc_frag->size - alloc_frag->offset;
1259 	if (hole < len + room) {
1260 		/* To avoid internal fragmentation, if there is very likely not
1261 		 * enough space for another buffer, add the remaining space to
1262 		 * the current buffer.
1263 		 */
1264 		len += hole;
1265 		alloc_frag->offset += hole;
1266 	}
1267 
1268 	sg_init_one(rq->sg, buf, len);
1269 	ctx = mergeable_len_to_ctx(len, headroom);
1270 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1271 	if (err < 0)
1272 		put_page(virt_to_head_page(buf));
1273 
1274 	return err;
1275 }
1276 
1277 /*
1278  * Returns false if we couldn't fill entirely (OOM).
1279  *
1280  * Normally run in the receive path, but can also be run from ndo_open
1281  * before we're receiving packets, or from refill_work which is
1282  * careful to disable receiving (using napi_disable).
1283  */
try_fill_recv(struct virtnet_info * vi,struct receive_queue * rq,gfp_t gfp)1284 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1285 			  gfp_t gfp)
1286 {
1287 	int err;
1288 	bool oom;
1289 
1290 	do {
1291 		if (vi->mergeable_rx_bufs)
1292 			err = add_recvbuf_mergeable(vi, rq, gfp);
1293 		else if (vi->big_packets)
1294 			err = add_recvbuf_big(vi, rq, gfp);
1295 		else
1296 			err = add_recvbuf_small(vi, rq, gfp);
1297 
1298 		oom = err == -ENOMEM;
1299 		if (err)
1300 			break;
1301 	} while (rq->vq->num_free);
1302 	if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
1303 		unsigned long flags;
1304 
1305 		flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1306 		rq->stats.kicks++;
1307 		u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1308 	}
1309 
1310 	return !oom;
1311 }
1312 
skb_recv_done(struct virtqueue * rvq)1313 static void skb_recv_done(struct virtqueue *rvq)
1314 {
1315 	struct virtnet_info *vi = rvq->vdev->priv;
1316 	struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1317 
1318 	virtqueue_napi_schedule(&rq->napi, rvq);
1319 }
1320 
virtnet_napi_enable(struct virtqueue * vq,struct napi_struct * napi)1321 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
1322 {
1323 	napi_enable(napi);
1324 
1325 	/* If all buffers were filled by other side before we napi_enabled, we
1326 	 * won't get another interrupt, so process any outstanding packets now.
1327 	 * Call local_bh_enable after to trigger softIRQ processing.
1328 	 */
1329 	local_bh_disable();
1330 	virtqueue_napi_schedule(napi, vq);
1331 	local_bh_enable();
1332 }
1333 
virtnet_napi_tx_enable(struct virtnet_info * vi,struct virtqueue * vq,struct napi_struct * napi)1334 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1335 				   struct virtqueue *vq,
1336 				   struct napi_struct *napi)
1337 {
1338 	if (!napi->weight)
1339 		return;
1340 
1341 	/* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1342 	 * enable the feature if this is likely affine with the transmit path.
1343 	 */
1344 	if (!vi->affinity_hint_set) {
1345 		napi->weight = 0;
1346 		return;
1347 	}
1348 
1349 	return virtnet_napi_enable(vq, napi);
1350 }
1351 
virtnet_napi_tx_disable(struct napi_struct * napi)1352 static void virtnet_napi_tx_disable(struct napi_struct *napi)
1353 {
1354 	if (napi->weight)
1355 		napi_disable(napi);
1356 }
1357 
refill_work(struct work_struct * work)1358 static void refill_work(struct work_struct *work)
1359 {
1360 	struct virtnet_info *vi =
1361 		container_of(work, struct virtnet_info, refill.work);
1362 	bool still_empty;
1363 	int i;
1364 
1365 	for (i = 0; i < vi->curr_queue_pairs; i++) {
1366 		struct receive_queue *rq = &vi->rq[i];
1367 
1368 		napi_disable(&rq->napi);
1369 		still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1370 		virtnet_napi_enable(rq->vq, &rq->napi);
1371 
1372 		/* In theory, this can happen: if we don't get any buffers in
1373 		 * we will *never* try to fill again.
1374 		 */
1375 		if (still_empty)
1376 			schedule_delayed_work(&vi->refill, HZ/2);
1377 	}
1378 }
1379 
virtnet_receive(struct receive_queue * rq,int budget,unsigned int * xdp_xmit)1380 static int virtnet_receive(struct receive_queue *rq, int budget,
1381 			   unsigned int *xdp_xmit)
1382 {
1383 	struct virtnet_info *vi = rq->vq->vdev->priv;
1384 	struct virtnet_rq_stats stats = {};
1385 	unsigned int len;
1386 	void *buf;
1387 	int i;
1388 
1389 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
1390 		void *ctx;
1391 
1392 		while (stats.packets < budget &&
1393 		       (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1394 			receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1395 			stats.packets++;
1396 		}
1397 	} else {
1398 		while (stats.packets < budget &&
1399 		       (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1400 			receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1401 			stats.packets++;
1402 		}
1403 	}
1404 
1405 	if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1406 		if (!try_fill_recv(vi, rq, GFP_ATOMIC))
1407 			schedule_delayed_work(&vi->refill, 0);
1408 	}
1409 
1410 	u64_stats_update_begin(&rq->stats.syncp);
1411 	for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1412 		size_t offset = virtnet_rq_stats_desc[i].offset;
1413 		u64 *item;
1414 
1415 		item = (u64 *)((u8 *)&rq->stats + offset);
1416 		*item += *(u64 *)((u8 *)&stats + offset);
1417 	}
1418 	u64_stats_update_end(&rq->stats.syncp);
1419 
1420 	return stats.packets;
1421 }
1422 
free_old_xmit_skbs(struct send_queue * sq,bool in_napi)1423 static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
1424 {
1425 	unsigned int len;
1426 	unsigned int packets = 0;
1427 	unsigned int bytes = 0;
1428 	void *ptr;
1429 
1430 	while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
1431 		if (likely(!is_xdp_frame(ptr))) {
1432 			struct sk_buff *skb = ptr;
1433 
1434 			pr_debug("Sent skb %p\n", skb);
1435 
1436 			bytes += skb->len;
1437 			napi_consume_skb(skb, in_napi);
1438 		} else {
1439 			struct xdp_frame *frame = ptr_to_xdp(ptr);
1440 
1441 			bytes += frame->len;
1442 			xdp_return_frame(frame);
1443 		}
1444 		packets++;
1445 	}
1446 
1447 	/* Avoid overhead when no packets have been processed
1448 	 * happens when called speculatively from start_xmit.
1449 	 */
1450 	if (!packets)
1451 		return;
1452 
1453 	u64_stats_update_begin(&sq->stats.syncp);
1454 	sq->stats.bytes += bytes;
1455 	sq->stats.packets += packets;
1456 	u64_stats_update_end(&sq->stats.syncp);
1457 }
1458 
is_xdp_raw_buffer_queue(struct virtnet_info * vi,int q)1459 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
1460 {
1461 	if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
1462 		return false;
1463 	else if (q < vi->curr_queue_pairs)
1464 		return true;
1465 	else
1466 		return false;
1467 }
1468 
virtnet_poll_cleantx(struct receive_queue * rq)1469 static void virtnet_poll_cleantx(struct receive_queue *rq)
1470 {
1471 	struct virtnet_info *vi = rq->vq->vdev->priv;
1472 	unsigned int index = vq2rxq(rq->vq);
1473 	struct send_queue *sq = &vi->sq[index];
1474 	struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
1475 
1476 	if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
1477 		return;
1478 
1479 	if (__netif_tx_trylock(txq)) {
1480 		free_old_xmit_skbs(sq, true);
1481 		__netif_tx_unlock(txq);
1482 	}
1483 
1484 	if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1485 		netif_tx_wake_queue(txq);
1486 }
1487 
virtnet_poll(struct napi_struct * napi,int budget)1488 static int virtnet_poll(struct napi_struct *napi, int budget)
1489 {
1490 	struct receive_queue *rq =
1491 		container_of(napi, struct receive_queue, napi);
1492 	struct virtnet_info *vi = rq->vq->vdev->priv;
1493 	struct send_queue *sq;
1494 	unsigned int received;
1495 	unsigned int xdp_xmit = 0;
1496 
1497 	virtnet_poll_cleantx(rq);
1498 
1499 	received = virtnet_receive(rq, budget, &xdp_xmit);
1500 
1501 	/* Out of packets? */
1502 	if (received < budget)
1503 		virtqueue_napi_complete(napi, rq->vq, received);
1504 
1505 	if (xdp_xmit & VIRTIO_XDP_REDIR)
1506 		xdp_do_flush();
1507 
1508 	if (xdp_xmit & VIRTIO_XDP_TX) {
1509 		sq = virtnet_xdp_get_sq(vi);
1510 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1511 			u64_stats_update_begin(&sq->stats.syncp);
1512 			sq->stats.kicks++;
1513 			u64_stats_update_end(&sq->stats.syncp);
1514 		}
1515 		virtnet_xdp_put_sq(vi, sq);
1516 	}
1517 
1518 	return received;
1519 }
1520 
virtnet_open(struct net_device * dev)1521 static int virtnet_open(struct net_device *dev)
1522 {
1523 	struct virtnet_info *vi = netdev_priv(dev);
1524 	int i, err;
1525 
1526 	for (i = 0; i < vi->max_queue_pairs; i++) {
1527 		if (i < vi->curr_queue_pairs)
1528 			/* Make sure we have some buffers: if oom use wq. */
1529 			if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1530 				schedule_delayed_work(&vi->refill, 0);
1531 
1532 		err = xdp_rxq_info_reg(&vi->rq[i].xdp_rxq, dev, i);
1533 		if (err < 0)
1534 			return err;
1535 
1536 		err = xdp_rxq_info_reg_mem_model(&vi->rq[i].xdp_rxq,
1537 						 MEM_TYPE_PAGE_SHARED, NULL);
1538 		if (err < 0) {
1539 			xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1540 			return err;
1541 		}
1542 
1543 		virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1544 		virtnet_napi_tx_enable(vi, vi->sq[i].vq, &vi->sq[i].napi);
1545 	}
1546 
1547 	return 0;
1548 }
1549 
virtnet_poll_tx(struct napi_struct * napi,int budget)1550 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1551 {
1552 	struct send_queue *sq = container_of(napi, struct send_queue, napi);
1553 	struct virtnet_info *vi = sq->vq->vdev->priv;
1554 	unsigned int index = vq2txq(sq->vq);
1555 	struct netdev_queue *txq;
1556 	int opaque;
1557 	bool done;
1558 
1559 	if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
1560 		/* We don't need to enable cb for XDP */
1561 		napi_complete_done(napi, 0);
1562 		return 0;
1563 	}
1564 
1565 	txq = netdev_get_tx_queue(vi->dev, index);
1566 	__netif_tx_lock(txq, raw_smp_processor_id());
1567 	virtqueue_disable_cb(sq->vq);
1568 	free_old_xmit_skbs(sq, true);
1569 
1570 	opaque = virtqueue_enable_cb_prepare(sq->vq);
1571 
1572 	done = napi_complete_done(napi, 0);
1573 
1574 	if (!done)
1575 		virtqueue_disable_cb(sq->vq);
1576 
1577 	__netif_tx_unlock(txq);
1578 
1579 	if (done) {
1580 		if (unlikely(virtqueue_poll(sq->vq, opaque))) {
1581 			if (napi_schedule_prep(napi)) {
1582 				__netif_tx_lock(txq, raw_smp_processor_id());
1583 				virtqueue_disable_cb(sq->vq);
1584 				__netif_tx_unlock(txq);
1585 				__napi_schedule(napi);
1586 			}
1587 		}
1588 	}
1589 
1590 	if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1591 		netif_tx_wake_queue(txq);
1592 
1593 	return 0;
1594 }
1595 
xmit_skb(struct send_queue * sq,struct sk_buff * skb)1596 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1597 {
1598 	struct virtio_net_hdr_mrg_rxbuf *hdr;
1599 	const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1600 	struct virtnet_info *vi = sq->vq->vdev->priv;
1601 	int num_sg;
1602 	unsigned hdr_len = vi->hdr_len;
1603 	bool can_push;
1604 
1605 	pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1606 
1607 	can_push = vi->any_header_sg &&
1608 		!((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1609 		!skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1610 	/* Even if we can, don't push here yet as this would skew
1611 	 * csum_start offset below. */
1612 	if (can_push)
1613 		hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1614 	else
1615 		hdr = skb_vnet_hdr(skb);
1616 
1617 	if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1618 				    virtio_is_little_endian(vi->vdev), false,
1619 				    0))
1620 		return -EPROTO;
1621 
1622 	if (vi->mergeable_rx_bufs)
1623 		hdr->num_buffers = 0;
1624 
1625 	sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1626 	if (can_push) {
1627 		__skb_push(skb, hdr_len);
1628 		num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1629 		if (unlikely(num_sg < 0))
1630 			return num_sg;
1631 		/* Pull header back to avoid skew in tx bytes calculations. */
1632 		__skb_pull(skb, hdr_len);
1633 	} else {
1634 		sg_set_buf(sq->sg, hdr, hdr_len);
1635 		num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
1636 		if (unlikely(num_sg < 0))
1637 			return num_sg;
1638 		num_sg++;
1639 	}
1640 	return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1641 }
1642 
start_xmit(struct sk_buff * skb,struct net_device * dev)1643 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1644 {
1645 	struct virtnet_info *vi = netdev_priv(dev);
1646 	int qnum = skb_get_queue_mapping(skb);
1647 	struct send_queue *sq = &vi->sq[qnum];
1648 	int err;
1649 	struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1650 	bool kick = !netdev_xmit_more();
1651 	bool use_napi = sq->napi.weight;
1652 
1653 	/* Free up any pending old buffers before queueing new ones. */
1654 	free_old_xmit_skbs(sq, false);
1655 
1656 	if (use_napi && kick)
1657 		virtqueue_enable_cb_delayed(sq->vq);
1658 
1659 	/* timestamp packet in software */
1660 	skb_tx_timestamp(skb);
1661 
1662 	/* Try to transmit */
1663 	err = xmit_skb(sq, skb);
1664 
1665 	/* This should not happen! */
1666 	if (unlikely(err)) {
1667 		dev->stats.tx_fifo_errors++;
1668 		if (net_ratelimit())
1669 			dev_warn(&dev->dev,
1670 				 "Unexpected TXQ (%d) queue failure: %d\n",
1671 				 qnum, err);
1672 		dev->stats.tx_dropped++;
1673 		dev_kfree_skb_any(skb);
1674 		return NETDEV_TX_OK;
1675 	}
1676 
1677 	/* Don't wait up for transmitted skbs to be freed. */
1678 	if (!use_napi) {
1679 		skb_orphan(skb);
1680 		nf_reset_ct(skb);
1681 	}
1682 
1683 	/* If running out of space, stop queue to avoid getting packets that we
1684 	 * are then unable to transmit.
1685 	 * An alternative would be to force queuing layer to requeue the skb by
1686 	 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
1687 	 * returned in a normal path of operation: it means that driver is not
1688 	 * maintaining the TX queue stop/start state properly, and causes
1689 	 * the stack to do a non-trivial amount of useless work.
1690 	 * Since most packets only take 1 or 2 ring slots, stopping the queue
1691 	 * early means 16 slots are typically wasted.
1692 	 */
1693 	if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1694 		netif_stop_subqueue(dev, qnum);
1695 		if (!use_napi &&
1696 		    unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1697 			/* More just got used, free them then recheck. */
1698 			free_old_xmit_skbs(sq, false);
1699 			if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1700 				netif_start_subqueue(dev, qnum);
1701 				virtqueue_disable_cb(sq->vq);
1702 			}
1703 		}
1704 	}
1705 
1706 	if (kick || netif_xmit_stopped(txq)) {
1707 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1708 			u64_stats_update_begin(&sq->stats.syncp);
1709 			sq->stats.kicks++;
1710 			u64_stats_update_end(&sq->stats.syncp);
1711 		}
1712 	}
1713 
1714 	return NETDEV_TX_OK;
1715 }
1716 
1717 /*
1718  * Send command via the control virtqueue and check status.  Commands
1719  * supported by the hypervisor, as indicated by feature bits, should
1720  * never fail unless improperly formatted.
1721  */
virtnet_send_command(struct virtnet_info * vi,u8 class,u8 cmd,struct scatterlist * out)1722 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1723 				 struct scatterlist *out)
1724 {
1725 	struct scatterlist *sgs[4], hdr, stat;
1726 	unsigned out_num = 0, tmp;
1727 
1728 	/* Caller should know better */
1729 	BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1730 
1731 	vi->ctrl->status = ~0;
1732 	vi->ctrl->hdr.class = class;
1733 	vi->ctrl->hdr.cmd = cmd;
1734 	/* Add header */
1735 	sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
1736 	sgs[out_num++] = &hdr;
1737 
1738 	if (out)
1739 		sgs[out_num++] = out;
1740 
1741 	/* Add return status. */
1742 	sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
1743 	sgs[out_num] = &stat;
1744 
1745 	BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1746 	virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1747 
1748 	if (unlikely(!virtqueue_kick(vi->cvq)))
1749 		return vi->ctrl->status == VIRTIO_NET_OK;
1750 
1751 	/* Spin for a response, the kick causes an ioport write, trapping
1752 	 * into the hypervisor, so the request should be handled immediately.
1753 	 */
1754 	while (!virtqueue_get_buf(vi->cvq, &tmp) &&
1755 	       !virtqueue_is_broken(vi->cvq))
1756 		cpu_relax();
1757 
1758 	return vi->ctrl->status == VIRTIO_NET_OK;
1759 }
1760 
virtnet_set_mac_address(struct net_device * dev,void * p)1761 static int virtnet_set_mac_address(struct net_device *dev, void *p)
1762 {
1763 	struct virtnet_info *vi = netdev_priv(dev);
1764 	struct virtio_device *vdev = vi->vdev;
1765 	int ret;
1766 	struct sockaddr *addr;
1767 	struct scatterlist sg;
1768 
1769 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
1770 		return -EOPNOTSUPP;
1771 
1772 	addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
1773 	if (!addr)
1774 		return -ENOMEM;
1775 
1776 	ret = eth_prepare_mac_addr_change(dev, addr);
1777 	if (ret)
1778 		goto out;
1779 
1780 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1781 		sg_init_one(&sg, addr->sa_data, dev->addr_len);
1782 		if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1783 					  VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
1784 			dev_warn(&vdev->dev,
1785 				 "Failed to set mac address by vq command.\n");
1786 			ret = -EINVAL;
1787 			goto out;
1788 		}
1789 	} else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
1790 		   !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1791 		unsigned int i;
1792 
1793 		/* Naturally, this has an atomicity problem. */
1794 		for (i = 0; i < dev->addr_len; i++)
1795 			virtio_cwrite8(vdev,
1796 				       offsetof(struct virtio_net_config, mac) +
1797 				       i, addr->sa_data[i]);
1798 	}
1799 
1800 	eth_commit_mac_addr_change(dev, p);
1801 	ret = 0;
1802 
1803 out:
1804 	kfree(addr);
1805 	return ret;
1806 }
1807 
virtnet_stats(struct net_device * dev,struct rtnl_link_stats64 * tot)1808 static void virtnet_stats(struct net_device *dev,
1809 			  struct rtnl_link_stats64 *tot)
1810 {
1811 	struct virtnet_info *vi = netdev_priv(dev);
1812 	unsigned int start;
1813 	int i;
1814 
1815 	for (i = 0; i < vi->max_queue_pairs; i++) {
1816 		u64 tpackets, tbytes, rpackets, rbytes, rdrops;
1817 		struct receive_queue *rq = &vi->rq[i];
1818 		struct send_queue *sq = &vi->sq[i];
1819 
1820 		do {
1821 			start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
1822 			tpackets = sq->stats.packets;
1823 			tbytes   = sq->stats.bytes;
1824 		} while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
1825 
1826 		do {
1827 			start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
1828 			rpackets = rq->stats.packets;
1829 			rbytes   = rq->stats.bytes;
1830 			rdrops   = rq->stats.drops;
1831 		} while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
1832 
1833 		tot->rx_packets += rpackets;
1834 		tot->tx_packets += tpackets;
1835 		tot->rx_bytes   += rbytes;
1836 		tot->tx_bytes   += tbytes;
1837 		tot->rx_dropped += rdrops;
1838 	}
1839 
1840 	tot->tx_dropped = dev->stats.tx_dropped;
1841 	tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
1842 	tot->rx_length_errors = dev->stats.rx_length_errors;
1843 	tot->rx_frame_errors = dev->stats.rx_frame_errors;
1844 }
1845 
virtnet_ack_link_announce(struct virtnet_info * vi)1846 static void virtnet_ack_link_announce(struct virtnet_info *vi)
1847 {
1848 	rtnl_lock();
1849 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
1850 				  VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
1851 		dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
1852 	rtnl_unlock();
1853 }
1854 
_virtnet_set_queues(struct virtnet_info * vi,u16 queue_pairs)1855 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1856 {
1857 	struct scatterlist sg;
1858 	struct net_device *dev = vi->dev;
1859 
1860 	if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
1861 		return 0;
1862 
1863 	vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
1864 	sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
1865 
1866 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
1867 				  VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
1868 		dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
1869 			 queue_pairs);
1870 		return -EINVAL;
1871 	} else {
1872 		vi->curr_queue_pairs = queue_pairs;
1873 		/* virtnet_open() will refill when device is going to up. */
1874 		if (dev->flags & IFF_UP)
1875 			schedule_delayed_work(&vi->refill, 0);
1876 	}
1877 
1878 	return 0;
1879 }
1880 
virtnet_set_queues(struct virtnet_info * vi,u16 queue_pairs)1881 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1882 {
1883 	int err;
1884 
1885 	rtnl_lock();
1886 	err = _virtnet_set_queues(vi, queue_pairs);
1887 	rtnl_unlock();
1888 	return err;
1889 }
1890 
virtnet_close(struct net_device * dev)1891 static int virtnet_close(struct net_device *dev)
1892 {
1893 	struct virtnet_info *vi = netdev_priv(dev);
1894 	int i;
1895 
1896 	/* Make sure refill_work doesn't re-enable napi! */
1897 	cancel_delayed_work_sync(&vi->refill);
1898 
1899 	for (i = 0; i < vi->max_queue_pairs; i++) {
1900 		xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1901 		napi_disable(&vi->rq[i].napi);
1902 		virtnet_napi_tx_disable(&vi->sq[i].napi);
1903 	}
1904 
1905 	return 0;
1906 }
1907 
virtnet_set_rx_mode(struct net_device * dev)1908 static void virtnet_set_rx_mode(struct net_device *dev)
1909 {
1910 	struct virtnet_info *vi = netdev_priv(dev);
1911 	struct scatterlist sg[2];
1912 	struct virtio_net_ctrl_mac *mac_data;
1913 	struct netdev_hw_addr *ha;
1914 	int uc_count;
1915 	int mc_count;
1916 	void *buf;
1917 	int i;
1918 
1919 	/* We can't dynamically set ndo_set_rx_mode, so return gracefully */
1920 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
1921 		return;
1922 
1923 	vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
1924 	vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
1925 
1926 	sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
1927 
1928 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1929 				  VIRTIO_NET_CTRL_RX_PROMISC, sg))
1930 		dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
1931 			 vi->ctrl->promisc ? "en" : "dis");
1932 
1933 	sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
1934 
1935 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1936 				  VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
1937 		dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
1938 			 vi->ctrl->allmulti ? "en" : "dis");
1939 
1940 	uc_count = netdev_uc_count(dev);
1941 	mc_count = netdev_mc_count(dev);
1942 	/* MAC filter - use one buffer for both lists */
1943 	buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
1944 		      (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
1945 	mac_data = buf;
1946 	if (!buf)
1947 		return;
1948 
1949 	sg_init_table(sg, 2);
1950 
1951 	/* Store the unicast list and count in the front of the buffer */
1952 	mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
1953 	i = 0;
1954 	netdev_for_each_uc_addr(ha, dev)
1955 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1956 
1957 	sg_set_buf(&sg[0], mac_data,
1958 		   sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
1959 
1960 	/* multicast list and count fill the end */
1961 	mac_data = (void *)&mac_data->macs[uc_count][0];
1962 
1963 	mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
1964 	i = 0;
1965 	netdev_for_each_mc_addr(ha, dev)
1966 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1967 
1968 	sg_set_buf(&sg[1], mac_data,
1969 		   sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
1970 
1971 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1972 				  VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
1973 		dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
1974 
1975 	kfree(buf);
1976 }
1977 
virtnet_vlan_rx_add_vid(struct net_device * dev,__be16 proto,u16 vid)1978 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
1979 				   __be16 proto, u16 vid)
1980 {
1981 	struct virtnet_info *vi = netdev_priv(dev);
1982 	struct scatterlist sg;
1983 
1984 	vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
1985 	sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
1986 
1987 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1988 				  VIRTIO_NET_CTRL_VLAN_ADD, &sg))
1989 		dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
1990 	return 0;
1991 }
1992 
virtnet_vlan_rx_kill_vid(struct net_device * dev,__be16 proto,u16 vid)1993 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
1994 				    __be16 proto, u16 vid)
1995 {
1996 	struct virtnet_info *vi = netdev_priv(dev);
1997 	struct scatterlist sg;
1998 
1999 	vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2000 	sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2001 
2002 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2003 				  VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2004 		dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2005 	return 0;
2006 }
2007 
virtnet_clean_affinity(struct virtnet_info * vi)2008 static void virtnet_clean_affinity(struct virtnet_info *vi)
2009 {
2010 	int i;
2011 
2012 	if (vi->affinity_hint_set) {
2013 		for (i = 0; i < vi->max_queue_pairs; i++) {
2014 			virtqueue_set_affinity(vi->rq[i].vq, NULL);
2015 			virtqueue_set_affinity(vi->sq[i].vq, NULL);
2016 		}
2017 
2018 		vi->affinity_hint_set = false;
2019 	}
2020 }
2021 
virtnet_set_affinity(struct virtnet_info * vi)2022 static void virtnet_set_affinity(struct virtnet_info *vi)
2023 {
2024 	cpumask_var_t mask;
2025 	int stragglers;
2026 	int group_size;
2027 	int i, j, cpu;
2028 	int num_cpu;
2029 	int stride;
2030 
2031 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2032 		virtnet_clean_affinity(vi);
2033 		return;
2034 	}
2035 
2036 	num_cpu = num_online_cpus();
2037 	stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2038 	stragglers = num_cpu >= vi->curr_queue_pairs ?
2039 			num_cpu % vi->curr_queue_pairs :
2040 			0;
2041 	cpu = cpumask_next(-1, cpu_online_mask);
2042 
2043 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2044 		group_size = stride + (i < stragglers ? 1 : 0);
2045 
2046 		for (j = 0; j < group_size; j++) {
2047 			cpumask_set_cpu(cpu, mask);
2048 			cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2049 						nr_cpu_ids, false);
2050 		}
2051 		virtqueue_set_affinity(vi->rq[i].vq, mask);
2052 		virtqueue_set_affinity(vi->sq[i].vq, mask);
2053 		__netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, false);
2054 		cpumask_clear(mask);
2055 	}
2056 
2057 	vi->affinity_hint_set = true;
2058 	free_cpumask_var(mask);
2059 }
2060 
virtnet_cpu_online(unsigned int cpu,struct hlist_node * node)2061 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2062 {
2063 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2064 						   node);
2065 	virtnet_set_affinity(vi);
2066 	return 0;
2067 }
2068 
virtnet_cpu_dead(unsigned int cpu,struct hlist_node * node)2069 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2070 {
2071 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2072 						   node_dead);
2073 	virtnet_set_affinity(vi);
2074 	return 0;
2075 }
2076 
virtnet_cpu_down_prep(unsigned int cpu,struct hlist_node * node)2077 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2078 {
2079 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2080 						   node);
2081 
2082 	virtnet_clean_affinity(vi);
2083 	return 0;
2084 }
2085 
2086 static enum cpuhp_state virtionet_online;
2087 
virtnet_cpu_notif_add(struct virtnet_info * vi)2088 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2089 {
2090 	int ret;
2091 
2092 	ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2093 	if (ret)
2094 		return ret;
2095 	ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2096 					       &vi->node_dead);
2097 	if (!ret)
2098 		return ret;
2099 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2100 	return ret;
2101 }
2102 
virtnet_cpu_notif_remove(struct virtnet_info * vi)2103 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2104 {
2105 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2106 	cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2107 					    &vi->node_dead);
2108 }
2109 
virtnet_get_ringparam(struct net_device * dev,struct ethtool_ringparam * ring)2110 static void virtnet_get_ringparam(struct net_device *dev,
2111 				struct ethtool_ringparam *ring)
2112 {
2113 	struct virtnet_info *vi = netdev_priv(dev);
2114 
2115 	ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2116 	ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2117 	ring->rx_pending = ring->rx_max_pending;
2118 	ring->tx_pending = ring->tx_max_pending;
2119 }
2120 
2121 
virtnet_get_drvinfo(struct net_device * dev,struct ethtool_drvinfo * info)2122 static void virtnet_get_drvinfo(struct net_device *dev,
2123 				struct ethtool_drvinfo *info)
2124 {
2125 	struct virtnet_info *vi = netdev_priv(dev);
2126 	struct virtio_device *vdev = vi->vdev;
2127 
2128 	strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2129 	strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2130 	strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2131 
2132 }
2133 
2134 /* TODO: Eliminate OOO packets during switching */
virtnet_set_channels(struct net_device * dev,struct ethtool_channels * channels)2135 static int virtnet_set_channels(struct net_device *dev,
2136 				struct ethtool_channels *channels)
2137 {
2138 	struct virtnet_info *vi = netdev_priv(dev);
2139 	u16 queue_pairs = channels->combined_count;
2140 	int err;
2141 
2142 	/* We don't support separate rx/tx channels.
2143 	 * We don't allow setting 'other' channels.
2144 	 */
2145 	if (channels->rx_count || channels->tx_count || channels->other_count)
2146 		return -EINVAL;
2147 
2148 	if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2149 		return -EINVAL;
2150 
2151 	/* For now we don't support modifying channels while XDP is loaded
2152 	 * also when XDP is loaded all RX queues have XDP programs so we only
2153 	 * need to check a single RX queue.
2154 	 */
2155 	if (vi->rq[0].xdp_prog)
2156 		return -EINVAL;
2157 
2158 	get_online_cpus();
2159 	err = _virtnet_set_queues(vi, queue_pairs);
2160 	if (err) {
2161 		put_online_cpus();
2162 		goto err;
2163 	}
2164 	virtnet_set_affinity(vi);
2165 	put_online_cpus();
2166 
2167 	netif_set_real_num_tx_queues(dev, queue_pairs);
2168 	netif_set_real_num_rx_queues(dev, queue_pairs);
2169  err:
2170 	return err;
2171 }
2172 
virtnet_get_strings(struct net_device * dev,u32 stringset,u8 * data)2173 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2174 {
2175 	struct virtnet_info *vi = netdev_priv(dev);
2176 	char *p = (char *)data;
2177 	unsigned int i, j;
2178 
2179 	switch (stringset) {
2180 	case ETH_SS_STATS:
2181 		for (i = 0; i < vi->curr_queue_pairs; i++) {
2182 			for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2183 				snprintf(p, ETH_GSTRING_LEN, "rx_queue_%u_%s",
2184 					 i, virtnet_rq_stats_desc[j].desc);
2185 				p += ETH_GSTRING_LEN;
2186 			}
2187 		}
2188 
2189 		for (i = 0; i < vi->curr_queue_pairs; i++) {
2190 			for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2191 				snprintf(p, ETH_GSTRING_LEN, "tx_queue_%u_%s",
2192 					 i, virtnet_sq_stats_desc[j].desc);
2193 				p += ETH_GSTRING_LEN;
2194 			}
2195 		}
2196 		break;
2197 	}
2198 }
2199 
virtnet_get_sset_count(struct net_device * dev,int sset)2200 static int virtnet_get_sset_count(struct net_device *dev, int sset)
2201 {
2202 	struct virtnet_info *vi = netdev_priv(dev);
2203 
2204 	switch (sset) {
2205 	case ETH_SS_STATS:
2206 		return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2207 					       VIRTNET_SQ_STATS_LEN);
2208 	default:
2209 		return -EOPNOTSUPP;
2210 	}
2211 }
2212 
virtnet_get_ethtool_stats(struct net_device * dev,struct ethtool_stats * stats,u64 * data)2213 static void virtnet_get_ethtool_stats(struct net_device *dev,
2214 				      struct ethtool_stats *stats, u64 *data)
2215 {
2216 	struct virtnet_info *vi = netdev_priv(dev);
2217 	unsigned int idx = 0, start, i, j;
2218 	const u8 *stats_base;
2219 	size_t offset;
2220 
2221 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2222 		struct receive_queue *rq = &vi->rq[i];
2223 
2224 		stats_base = (u8 *)&rq->stats;
2225 		do {
2226 			start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2227 			for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2228 				offset = virtnet_rq_stats_desc[j].offset;
2229 				data[idx + j] = *(u64 *)(stats_base + offset);
2230 			}
2231 		} while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2232 		idx += VIRTNET_RQ_STATS_LEN;
2233 	}
2234 
2235 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2236 		struct send_queue *sq = &vi->sq[i];
2237 
2238 		stats_base = (u8 *)&sq->stats;
2239 		do {
2240 			start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2241 			for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2242 				offset = virtnet_sq_stats_desc[j].offset;
2243 				data[idx + j] = *(u64 *)(stats_base + offset);
2244 			}
2245 		} while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2246 		idx += VIRTNET_SQ_STATS_LEN;
2247 	}
2248 }
2249 
virtnet_get_channels(struct net_device * dev,struct ethtool_channels * channels)2250 static void virtnet_get_channels(struct net_device *dev,
2251 				 struct ethtool_channels *channels)
2252 {
2253 	struct virtnet_info *vi = netdev_priv(dev);
2254 
2255 	channels->combined_count = vi->curr_queue_pairs;
2256 	channels->max_combined = vi->max_queue_pairs;
2257 	channels->max_other = 0;
2258 	channels->rx_count = 0;
2259 	channels->tx_count = 0;
2260 	channels->other_count = 0;
2261 }
2262 
virtnet_set_link_ksettings(struct net_device * dev,const struct ethtool_link_ksettings * cmd)2263 static int virtnet_set_link_ksettings(struct net_device *dev,
2264 				      const struct ethtool_link_ksettings *cmd)
2265 {
2266 	struct virtnet_info *vi = netdev_priv(dev);
2267 
2268 	return ethtool_virtdev_set_link_ksettings(dev, cmd,
2269 						  &vi->speed, &vi->duplex);
2270 }
2271 
virtnet_get_link_ksettings(struct net_device * dev,struct ethtool_link_ksettings * cmd)2272 static int virtnet_get_link_ksettings(struct net_device *dev,
2273 				      struct ethtool_link_ksettings *cmd)
2274 {
2275 	struct virtnet_info *vi = netdev_priv(dev);
2276 
2277 	cmd->base.speed = vi->speed;
2278 	cmd->base.duplex = vi->duplex;
2279 	cmd->base.port = PORT_OTHER;
2280 
2281 	return 0;
2282 }
2283 
virtnet_set_coalesce(struct net_device * dev,struct ethtool_coalesce * ec)2284 static int virtnet_set_coalesce(struct net_device *dev,
2285 				struct ethtool_coalesce *ec)
2286 {
2287 	struct virtnet_info *vi = netdev_priv(dev);
2288 	int i, napi_weight;
2289 
2290 	if (ec->tx_max_coalesced_frames > 1 ||
2291 	    ec->rx_max_coalesced_frames != 1)
2292 		return -EINVAL;
2293 
2294 	napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
2295 	if (napi_weight ^ vi->sq[0].napi.weight) {
2296 		if (dev->flags & IFF_UP)
2297 			return -EBUSY;
2298 		for (i = 0; i < vi->max_queue_pairs; i++)
2299 			vi->sq[i].napi.weight = napi_weight;
2300 	}
2301 
2302 	return 0;
2303 }
2304 
virtnet_get_coalesce(struct net_device * dev,struct ethtool_coalesce * ec)2305 static int virtnet_get_coalesce(struct net_device *dev,
2306 				struct ethtool_coalesce *ec)
2307 {
2308 	struct ethtool_coalesce ec_default = {
2309 		.cmd = ETHTOOL_GCOALESCE,
2310 		.rx_max_coalesced_frames = 1,
2311 	};
2312 	struct virtnet_info *vi = netdev_priv(dev);
2313 
2314 	memcpy(ec, &ec_default, sizeof(ec_default));
2315 
2316 	if (vi->sq[0].napi.weight)
2317 		ec->tx_max_coalesced_frames = 1;
2318 
2319 	return 0;
2320 }
2321 
virtnet_init_settings(struct net_device * dev)2322 static void virtnet_init_settings(struct net_device *dev)
2323 {
2324 	struct virtnet_info *vi = netdev_priv(dev);
2325 
2326 	vi->speed = SPEED_UNKNOWN;
2327 	vi->duplex = DUPLEX_UNKNOWN;
2328 }
2329 
virtnet_update_settings(struct virtnet_info * vi)2330 static void virtnet_update_settings(struct virtnet_info *vi)
2331 {
2332 	u32 speed;
2333 	u8 duplex;
2334 
2335 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
2336 		return;
2337 
2338 	virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
2339 
2340 	if (ethtool_validate_speed(speed))
2341 		vi->speed = speed;
2342 
2343 	virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
2344 
2345 	if (ethtool_validate_duplex(duplex))
2346 		vi->duplex = duplex;
2347 }
2348 
2349 static const struct ethtool_ops virtnet_ethtool_ops = {
2350 	.supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES,
2351 	.get_drvinfo = virtnet_get_drvinfo,
2352 	.get_link = ethtool_op_get_link,
2353 	.get_ringparam = virtnet_get_ringparam,
2354 	.get_strings = virtnet_get_strings,
2355 	.get_sset_count = virtnet_get_sset_count,
2356 	.get_ethtool_stats = virtnet_get_ethtool_stats,
2357 	.set_channels = virtnet_set_channels,
2358 	.get_channels = virtnet_get_channels,
2359 	.get_ts_info = ethtool_op_get_ts_info,
2360 	.get_link_ksettings = virtnet_get_link_ksettings,
2361 	.set_link_ksettings = virtnet_set_link_ksettings,
2362 	.set_coalesce = virtnet_set_coalesce,
2363 	.get_coalesce = virtnet_get_coalesce,
2364 };
2365 
virtnet_freeze_down(struct virtio_device * vdev)2366 static void virtnet_freeze_down(struct virtio_device *vdev)
2367 {
2368 	struct virtnet_info *vi = vdev->priv;
2369 	int i;
2370 
2371 	/* Make sure no work handler is accessing the device */
2372 	flush_work(&vi->config_work);
2373 
2374 	netif_tx_lock_bh(vi->dev);
2375 	netif_device_detach(vi->dev);
2376 	netif_tx_unlock_bh(vi->dev);
2377 	cancel_delayed_work_sync(&vi->refill);
2378 
2379 	if (netif_running(vi->dev)) {
2380 		for (i = 0; i < vi->max_queue_pairs; i++) {
2381 			napi_disable(&vi->rq[i].napi);
2382 			virtnet_napi_tx_disable(&vi->sq[i].napi);
2383 		}
2384 	}
2385 }
2386 
2387 static int init_vqs(struct virtnet_info *vi);
2388 
virtnet_restore_up(struct virtio_device * vdev)2389 static int virtnet_restore_up(struct virtio_device *vdev)
2390 {
2391 	struct virtnet_info *vi = vdev->priv;
2392 	int err, i;
2393 
2394 	err = init_vqs(vi);
2395 	if (err)
2396 		return err;
2397 
2398 	virtio_device_ready(vdev);
2399 
2400 	if (netif_running(vi->dev)) {
2401 		for (i = 0; i < vi->curr_queue_pairs; i++)
2402 			if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
2403 				schedule_delayed_work(&vi->refill, 0);
2404 
2405 		for (i = 0; i < vi->max_queue_pairs; i++) {
2406 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2407 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2408 					       &vi->sq[i].napi);
2409 		}
2410 	}
2411 
2412 	netif_tx_lock_bh(vi->dev);
2413 	netif_device_attach(vi->dev);
2414 	netif_tx_unlock_bh(vi->dev);
2415 	return err;
2416 }
2417 
virtnet_set_guest_offloads(struct virtnet_info * vi,u64 offloads)2418 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
2419 {
2420 	struct scatterlist sg;
2421 	vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
2422 
2423 	sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
2424 
2425 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
2426 				  VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
2427 		dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
2428 		return -EINVAL;
2429 	}
2430 
2431 	return 0;
2432 }
2433 
virtnet_clear_guest_offloads(struct virtnet_info * vi)2434 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
2435 {
2436 	u64 offloads = 0;
2437 
2438 	if (!vi->guest_offloads)
2439 		return 0;
2440 
2441 	return virtnet_set_guest_offloads(vi, offloads);
2442 }
2443 
virtnet_restore_guest_offloads(struct virtnet_info * vi)2444 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
2445 {
2446 	u64 offloads = vi->guest_offloads;
2447 
2448 	if (!vi->guest_offloads)
2449 		return 0;
2450 
2451 	return virtnet_set_guest_offloads(vi, offloads);
2452 }
2453 
virtnet_xdp_set(struct net_device * dev,struct bpf_prog * prog,struct netlink_ext_ack * extack)2454 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
2455 			   struct netlink_ext_ack *extack)
2456 {
2457 	unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
2458 	struct virtnet_info *vi = netdev_priv(dev);
2459 	struct bpf_prog *old_prog;
2460 	u16 xdp_qp = 0, curr_qp;
2461 	int i, err;
2462 
2463 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
2464 	    && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
2465 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
2466 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
2467 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
2468 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM))) {
2469 		NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
2470 		return -EOPNOTSUPP;
2471 	}
2472 
2473 	if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
2474 		NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
2475 		return -EINVAL;
2476 	}
2477 
2478 	if (dev->mtu > max_sz) {
2479 		NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
2480 		netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
2481 		return -EINVAL;
2482 	}
2483 
2484 	curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
2485 	if (prog)
2486 		xdp_qp = nr_cpu_ids;
2487 
2488 	/* XDP requires extra queues for XDP_TX */
2489 	if (curr_qp + xdp_qp > vi->max_queue_pairs) {
2490 		netdev_warn(dev, "XDP request %i queues but max is %i. XDP_TX and XDP_REDIRECT will operate in a slower locked tx mode.\n",
2491 			    curr_qp + xdp_qp, vi->max_queue_pairs);
2492 		xdp_qp = 0;
2493 	}
2494 
2495 	old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
2496 	if (!prog && !old_prog)
2497 		return 0;
2498 
2499 	if (prog)
2500 		bpf_prog_add(prog, vi->max_queue_pairs - 1);
2501 
2502 	/* Make sure NAPI is not using any XDP TX queues for RX. */
2503 	if (netif_running(dev)) {
2504 		for (i = 0; i < vi->max_queue_pairs; i++) {
2505 			napi_disable(&vi->rq[i].napi);
2506 			virtnet_napi_tx_disable(&vi->sq[i].napi);
2507 		}
2508 	}
2509 
2510 	if (!prog) {
2511 		for (i = 0; i < vi->max_queue_pairs; i++) {
2512 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
2513 			if (i == 0)
2514 				virtnet_restore_guest_offloads(vi);
2515 		}
2516 		synchronize_net();
2517 	}
2518 
2519 	err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
2520 	if (err)
2521 		goto err;
2522 	netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
2523 	vi->xdp_queue_pairs = xdp_qp;
2524 
2525 	if (prog) {
2526 		vi->xdp_enabled = true;
2527 		for (i = 0; i < vi->max_queue_pairs; i++) {
2528 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
2529 			if (i == 0 && !old_prog)
2530 				virtnet_clear_guest_offloads(vi);
2531 		}
2532 	} else {
2533 		vi->xdp_enabled = false;
2534 	}
2535 
2536 	for (i = 0; i < vi->max_queue_pairs; i++) {
2537 		if (old_prog)
2538 			bpf_prog_put(old_prog);
2539 		if (netif_running(dev)) {
2540 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2541 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2542 					       &vi->sq[i].napi);
2543 		}
2544 	}
2545 
2546 	return 0;
2547 
2548 err:
2549 	if (!prog) {
2550 		virtnet_clear_guest_offloads(vi);
2551 		for (i = 0; i < vi->max_queue_pairs; i++)
2552 			rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
2553 	}
2554 
2555 	if (netif_running(dev)) {
2556 		for (i = 0; i < vi->max_queue_pairs; i++) {
2557 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2558 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2559 					       &vi->sq[i].napi);
2560 		}
2561 	}
2562 	if (prog)
2563 		bpf_prog_sub(prog, vi->max_queue_pairs - 1);
2564 	return err;
2565 }
2566 
virtnet_xdp(struct net_device * dev,struct netdev_bpf * xdp)2567 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
2568 {
2569 	switch (xdp->command) {
2570 	case XDP_SETUP_PROG:
2571 		return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
2572 	default:
2573 		return -EINVAL;
2574 	}
2575 }
2576 
virtnet_get_phys_port_name(struct net_device * dev,char * buf,size_t len)2577 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
2578 				      size_t len)
2579 {
2580 	struct virtnet_info *vi = netdev_priv(dev);
2581 	int ret;
2582 
2583 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2584 		return -EOPNOTSUPP;
2585 
2586 	ret = snprintf(buf, len, "sby");
2587 	if (ret >= len)
2588 		return -EOPNOTSUPP;
2589 
2590 	return 0;
2591 }
2592 
virtnet_set_features(struct net_device * dev,netdev_features_t features)2593 static int virtnet_set_features(struct net_device *dev,
2594 				netdev_features_t features)
2595 {
2596 	struct virtnet_info *vi = netdev_priv(dev);
2597 	u64 offloads;
2598 	int err;
2599 
2600 	if ((dev->features ^ features) & NETIF_F_GRO_HW) {
2601 		if (vi->xdp_enabled)
2602 			return -EBUSY;
2603 
2604 		if (features & NETIF_F_GRO_HW)
2605 			offloads = vi->guest_offloads_capable;
2606 		else
2607 			offloads = vi->guest_offloads_capable &
2608 				   ~GUEST_OFFLOAD_GRO_HW_MASK;
2609 
2610 		err = virtnet_set_guest_offloads(vi, offloads);
2611 		if (err)
2612 			return err;
2613 		vi->guest_offloads = offloads;
2614 	}
2615 
2616 	return 0;
2617 }
2618 
2619 static const struct net_device_ops virtnet_netdev = {
2620 	.ndo_open            = virtnet_open,
2621 	.ndo_stop   	     = virtnet_close,
2622 	.ndo_start_xmit      = start_xmit,
2623 	.ndo_validate_addr   = eth_validate_addr,
2624 	.ndo_set_mac_address = virtnet_set_mac_address,
2625 	.ndo_set_rx_mode     = virtnet_set_rx_mode,
2626 	.ndo_get_stats64     = virtnet_stats,
2627 	.ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
2628 	.ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
2629 	.ndo_bpf		= virtnet_xdp,
2630 	.ndo_xdp_xmit		= virtnet_xdp_xmit,
2631 	.ndo_features_check	= passthru_features_check,
2632 	.ndo_get_phys_port_name	= virtnet_get_phys_port_name,
2633 	.ndo_set_features	= virtnet_set_features,
2634 };
2635 
virtnet_config_changed_work(struct work_struct * work)2636 static void virtnet_config_changed_work(struct work_struct *work)
2637 {
2638 	struct virtnet_info *vi =
2639 		container_of(work, struct virtnet_info, config_work);
2640 	u16 v;
2641 
2642 	if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
2643 				 struct virtio_net_config, status, &v) < 0)
2644 		return;
2645 
2646 	if (v & VIRTIO_NET_S_ANNOUNCE) {
2647 		netdev_notify_peers(vi->dev);
2648 		virtnet_ack_link_announce(vi);
2649 	}
2650 
2651 	/* Ignore unknown (future) status bits */
2652 	v &= VIRTIO_NET_S_LINK_UP;
2653 
2654 	if (vi->status == v)
2655 		return;
2656 
2657 	vi->status = v;
2658 
2659 	if (vi->status & VIRTIO_NET_S_LINK_UP) {
2660 		virtnet_update_settings(vi);
2661 		netif_carrier_on(vi->dev);
2662 		netif_tx_wake_all_queues(vi->dev);
2663 	} else {
2664 		netif_carrier_off(vi->dev);
2665 		netif_tx_stop_all_queues(vi->dev);
2666 	}
2667 }
2668 
virtnet_config_changed(struct virtio_device * vdev)2669 static void virtnet_config_changed(struct virtio_device *vdev)
2670 {
2671 	struct virtnet_info *vi = vdev->priv;
2672 
2673 	schedule_work(&vi->config_work);
2674 }
2675 
virtnet_free_queues(struct virtnet_info * vi)2676 static void virtnet_free_queues(struct virtnet_info *vi)
2677 {
2678 	int i;
2679 
2680 	for (i = 0; i < vi->max_queue_pairs; i++) {
2681 		__netif_napi_del(&vi->rq[i].napi);
2682 		__netif_napi_del(&vi->sq[i].napi);
2683 	}
2684 
2685 	/* We called __netif_napi_del(),
2686 	 * we need to respect an RCU grace period before freeing vi->rq
2687 	 */
2688 	synchronize_net();
2689 
2690 	kfree(vi->rq);
2691 	kfree(vi->sq);
2692 	kfree(vi->ctrl);
2693 }
2694 
_free_receive_bufs(struct virtnet_info * vi)2695 static void _free_receive_bufs(struct virtnet_info *vi)
2696 {
2697 	struct bpf_prog *old_prog;
2698 	int i;
2699 
2700 	for (i = 0; i < vi->max_queue_pairs; i++) {
2701 		while (vi->rq[i].pages)
2702 			__free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
2703 
2704 		old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
2705 		RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
2706 		if (old_prog)
2707 			bpf_prog_put(old_prog);
2708 	}
2709 }
2710 
free_receive_bufs(struct virtnet_info * vi)2711 static void free_receive_bufs(struct virtnet_info *vi)
2712 {
2713 	rtnl_lock();
2714 	_free_receive_bufs(vi);
2715 	rtnl_unlock();
2716 }
2717 
free_receive_page_frags(struct virtnet_info * vi)2718 static void free_receive_page_frags(struct virtnet_info *vi)
2719 {
2720 	int i;
2721 	for (i = 0; i < vi->max_queue_pairs; i++)
2722 		if (vi->rq[i].alloc_frag.page)
2723 			put_page(vi->rq[i].alloc_frag.page);
2724 }
2725 
free_unused_bufs(struct virtnet_info * vi)2726 static void free_unused_bufs(struct virtnet_info *vi)
2727 {
2728 	void *buf;
2729 	int i;
2730 
2731 	for (i = 0; i < vi->max_queue_pairs; i++) {
2732 		struct virtqueue *vq = vi->sq[i].vq;
2733 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2734 			if (!is_xdp_frame(buf))
2735 				dev_kfree_skb(buf);
2736 			else
2737 				xdp_return_frame(ptr_to_xdp(buf));
2738 		}
2739 	}
2740 
2741 	for (i = 0; i < vi->max_queue_pairs; i++) {
2742 		struct virtqueue *vq = vi->rq[i].vq;
2743 
2744 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2745 			if (vi->mergeable_rx_bufs) {
2746 				put_page(virt_to_head_page(buf));
2747 			} else if (vi->big_packets) {
2748 				give_pages(&vi->rq[i], buf);
2749 			} else {
2750 				put_page(virt_to_head_page(buf));
2751 			}
2752 		}
2753 	}
2754 }
2755 
virtnet_del_vqs(struct virtnet_info * vi)2756 static void virtnet_del_vqs(struct virtnet_info *vi)
2757 {
2758 	struct virtio_device *vdev = vi->vdev;
2759 
2760 	virtnet_clean_affinity(vi);
2761 
2762 	vdev->config->del_vqs(vdev);
2763 
2764 	virtnet_free_queues(vi);
2765 }
2766 
2767 /* How large should a single buffer be so a queue full of these can fit at
2768  * least one full packet?
2769  * Logic below assumes the mergeable buffer header is used.
2770  */
mergeable_min_buf_len(struct virtnet_info * vi,struct virtqueue * vq)2771 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
2772 {
2773 	const unsigned int hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2774 	unsigned int rq_size = virtqueue_get_vring_size(vq);
2775 	unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
2776 	unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
2777 	unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
2778 
2779 	return max(max(min_buf_len, hdr_len) - hdr_len,
2780 		   (unsigned int)GOOD_PACKET_LEN);
2781 }
2782 
virtnet_find_vqs(struct virtnet_info * vi)2783 static int virtnet_find_vqs(struct virtnet_info *vi)
2784 {
2785 	vq_callback_t **callbacks;
2786 	struct virtqueue **vqs;
2787 	int ret = -ENOMEM;
2788 	int i, total_vqs;
2789 	const char **names;
2790 	bool *ctx;
2791 
2792 	/* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
2793 	 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
2794 	 * possible control vq.
2795 	 */
2796 	total_vqs = vi->max_queue_pairs * 2 +
2797 		    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
2798 
2799 	/* Allocate space for find_vqs parameters */
2800 	vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
2801 	if (!vqs)
2802 		goto err_vq;
2803 	callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
2804 	if (!callbacks)
2805 		goto err_callback;
2806 	names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
2807 	if (!names)
2808 		goto err_names;
2809 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
2810 		ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
2811 		if (!ctx)
2812 			goto err_ctx;
2813 	} else {
2814 		ctx = NULL;
2815 	}
2816 
2817 	/* Parameters for control virtqueue, if any */
2818 	if (vi->has_cvq) {
2819 		callbacks[total_vqs - 1] = NULL;
2820 		names[total_vqs - 1] = "control";
2821 	}
2822 
2823 	/* Allocate/initialize parameters for send/receive virtqueues */
2824 	for (i = 0; i < vi->max_queue_pairs; i++) {
2825 		callbacks[rxq2vq(i)] = skb_recv_done;
2826 		callbacks[txq2vq(i)] = skb_xmit_done;
2827 		sprintf(vi->rq[i].name, "input.%d", i);
2828 		sprintf(vi->sq[i].name, "output.%d", i);
2829 		names[rxq2vq(i)] = vi->rq[i].name;
2830 		names[txq2vq(i)] = vi->sq[i].name;
2831 		if (ctx)
2832 			ctx[rxq2vq(i)] = true;
2833 	}
2834 
2835 	ret = vi->vdev->config->find_vqs(vi->vdev, total_vqs, vqs, callbacks,
2836 					 names, ctx, NULL);
2837 	if (ret)
2838 		goto err_find;
2839 
2840 	if (vi->has_cvq) {
2841 		vi->cvq = vqs[total_vqs - 1];
2842 		if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
2843 			vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
2844 	}
2845 
2846 	for (i = 0; i < vi->max_queue_pairs; i++) {
2847 		vi->rq[i].vq = vqs[rxq2vq(i)];
2848 		vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
2849 		vi->sq[i].vq = vqs[txq2vq(i)];
2850 	}
2851 
2852 	/* run here: ret == 0. */
2853 
2854 
2855 err_find:
2856 	kfree(ctx);
2857 err_ctx:
2858 	kfree(names);
2859 err_names:
2860 	kfree(callbacks);
2861 err_callback:
2862 	kfree(vqs);
2863 err_vq:
2864 	return ret;
2865 }
2866 
virtnet_alloc_queues(struct virtnet_info * vi)2867 static int virtnet_alloc_queues(struct virtnet_info *vi)
2868 {
2869 	int i;
2870 
2871 	vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
2872 	if (!vi->ctrl)
2873 		goto err_ctrl;
2874 	vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
2875 	if (!vi->sq)
2876 		goto err_sq;
2877 	vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
2878 	if (!vi->rq)
2879 		goto err_rq;
2880 
2881 	INIT_DELAYED_WORK(&vi->refill, refill_work);
2882 	for (i = 0; i < vi->max_queue_pairs; i++) {
2883 		vi->rq[i].pages = NULL;
2884 		netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
2885 			       napi_weight);
2886 		netif_tx_napi_add(vi->dev, &vi->sq[i].napi, virtnet_poll_tx,
2887 				  napi_tx ? napi_weight : 0);
2888 
2889 		sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
2890 		ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
2891 		sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
2892 
2893 		u64_stats_init(&vi->rq[i].stats.syncp);
2894 		u64_stats_init(&vi->sq[i].stats.syncp);
2895 	}
2896 
2897 	return 0;
2898 
2899 err_rq:
2900 	kfree(vi->sq);
2901 err_sq:
2902 	kfree(vi->ctrl);
2903 err_ctrl:
2904 	return -ENOMEM;
2905 }
2906 
init_vqs(struct virtnet_info * vi)2907 static int init_vqs(struct virtnet_info *vi)
2908 {
2909 	int ret;
2910 
2911 	/* Allocate send & receive queues */
2912 	ret = virtnet_alloc_queues(vi);
2913 	if (ret)
2914 		goto err;
2915 
2916 	ret = virtnet_find_vqs(vi);
2917 	if (ret)
2918 		goto err_free;
2919 
2920 	get_online_cpus();
2921 	virtnet_set_affinity(vi);
2922 	put_online_cpus();
2923 
2924 	return 0;
2925 
2926 err_free:
2927 	virtnet_free_queues(vi);
2928 err:
2929 	return ret;
2930 }
2931 
2932 #ifdef CONFIG_SYSFS
mergeable_rx_buffer_size_show(struct netdev_rx_queue * queue,char * buf)2933 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
2934 		char *buf)
2935 {
2936 	struct virtnet_info *vi = netdev_priv(queue->dev);
2937 	unsigned int queue_index = get_netdev_rx_queue_index(queue);
2938 	unsigned int headroom = virtnet_get_headroom(vi);
2939 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
2940 	struct ewma_pkt_len *avg;
2941 
2942 	BUG_ON(queue_index >= vi->max_queue_pairs);
2943 	avg = &vi->rq[queue_index].mrg_avg_pkt_len;
2944 	return sprintf(buf, "%u\n",
2945 		       get_mergeable_buf_len(&vi->rq[queue_index], avg,
2946 				       SKB_DATA_ALIGN(headroom + tailroom)));
2947 }
2948 
2949 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
2950 	__ATTR_RO(mergeable_rx_buffer_size);
2951 
2952 static struct attribute *virtio_net_mrg_rx_attrs[] = {
2953 	&mergeable_rx_buffer_size_attribute.attr,
2954 	NULL
2955 };
2956 
2957 static const struct attribute_group virtio_net_mrg_rx_group = {
2958 	.name = "virtio_net",
2959 	.attrs = virtio_net_mrg_rx_attrs
2960 };
2961 #endif
2962 
virtnet_fail_on_feature(struct virtio_device * vdev,unsigned int fbit,const char * fname,const char * dname)2963 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
2964 				    unsigned int fbit,
2965 				    const char *fname, const char *dname)
2966 {
2967 	if (!virtio_has_feature(vdev, fbit))
2968 		return false;
2969 
2970 	dev_err(&vdev->dev, "device advertises feature %s but not %s",
2971 		fname, dname);
2972 
2973 	return true;
2974 }
2975 
2976 #define VIRTNET_FAIL_ON(vdev, fbit, dbit)			\
2977 	virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
2978 
virtnet_validate_features(struct virtio_device * vdev)2979 static bool virtnet_validate_features(struct virtio_device *vdev)
2980 {
2981 	if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
2982 	    (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
2983 			     "VIRTIO_NET_F_CTRL_VQ") ||
2984 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
2985 			     "VIRTIO_NET_F_CTRL_VQ") ||
2986 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
2987 			     "VIRTIO_NET_F_CTRL_VQ") ||
2988 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
2989 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
2990 			     "VIRTIO_NET_F_CTRL_VQ"))) {
2991 		return false;
2992 	}
2993 
2994 	return true;
2995 }
2996 
2997 #define MIN_MTU ETH_MIN_MTU
2998 #define MAX_MTU ETH_MAX_MTU
2999 
virtnet_validate(struct virtio_device * vdev)3000 static int virtnet_validate(struct virtio_device *vdev)
3001 {
3002 	if (!vdev->config->get) {
3003 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
3004 			__func__);
3005 		return -EINVAL;
3006 	}
3007 
3008 	if (!virtnet_validate_features(vdev))
3009 		return -EINVAL;
3010 
3011 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3012 		int mtu = virtio_cread16(vdev,
3013 					 offsetof(struct virtio_net_config,
3014 						  mtu));
3015 		if (mtu < MIN_MTU)
3016 			__virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3017 	}
3018 
3019 	return 0;
3020 }
3021 
virtnet_probe(struct virtio_device * vdev)3022 static int virtnet_probe(struct virtio_device *vdev)
3023 {
3024 	int i, err = -ENOMEM;
3025 	struct net_device *dev;
3026 	struct virtnet_info *vi;
3027 	u16 max_queue_pairs;
3028 	int mtu;
3029 
3030 	/* Find if host supports multiqueue virtio_net device */
3031 	err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
3032 				   struct virtio_net_config,
3033 				   max_virtqueue_pairs, &max_queue_pairs);
3034 
3035 	/* We need at least 2 queue's */
3036 	if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
3037 	    max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
3038 	    !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3039 		max_queue_pairs = 1;
3040 
3041 	/* Allocate ourselves a network device with room for our info */
3042 	dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
3043 	if (!dev)
3044 		return -ENOMEM;
3045 
3046 	/* Set up network device as normal. */
3047 	dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
3048 	dev->netdev_ops = &virtnet_netdev;
3049 	dev->features = NETIF_F_HIGHDMA;
3050 
3051 	dev->ethtool_ops = &virtnet_ethtool_ops;
3052 	SET_NETDEV_DEV(dev, &vdev->dev);
3053 
3054 	/* Do we support "hardware" checksums? */
3055 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
3056 		/* This opens up the world of extra features. */
3057 		dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3058 		if (csum)
3059 			dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3060 
3061 		if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
3062 			dev->hw_features |= NETIF_F_TSO
3063 				| NETIF_F_TSO_ECN | NETIF_F_TSO6;
3064 		}
3065 		/* Individual feature bits: what can host handle? */
3066 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
3067 			dev->hw_features |= NETIF_F_TSO;
3068 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
3069 			dev->hw_features |= NETIF_F_TSO6;
3070 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
3071 			dev->hw_features |= NETIF_F_TSO_ECN;
3072 
3073 		dev->features |= NETIF_F_GSO_ROBUST;
3074 
3075 		if (gso)
3076 			dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
3077 		/* (!csum && gso) case will be fixed by register_netdev() */
3078 	}
3079 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
3080 		dev->features |= NETIF_F_RXCSUM;
3081 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3082 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3083 		dev->features |= NETIF_F_GRO_HW;
3084 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3085 		dev->hw_features |= NETIF_F_GRO_HW;
3086 
3087 	dev->vlan_features = dev->features;
3088 
3089 	/* MTU range: 68 - 65535 */
3090 	dev->min_mtu = MIN_MTU;
3091 	dev->max_mtu = MAX_MTU;
3092 
3093 	/* Configuration may specify what MAC to use.  Otherwise random. */
3094 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
3095 		virtio_cread_bytes(vdev,
3096 				   offsetof(struct virtio_net_config, mac),
3097 				   dev->dev_addr, dev->addr_len);
3098 	else
3099 		eth_hw_addr_random(dev);
3100 
3101 	/* Set up our device-specific information */
3102 	vi = netdev_priv(dev);
3103 	vi->dev = dev;
3104 	vi->vdev = vdev;
3105 	vdev->priv = vi;
3106 
3107 	INIT_WORK(&vi->config_work, virtnet_config_changed_work);
3108 
3109 	/* If we can receive ANY GSO packets, we must allocate large ones. */
3110 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3111 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3112 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
3113 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
3114 		vi->big_packets = true;
3115 
3116 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
3117 		vi->mergeable_rx_bufs = true;
3118 
3119 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
3120 	    virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3121 		vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
3122 	else
3123 		vi->hdr_len = sizeof(struct virtio_net_hdr);
3124 
3125 	if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
3126 	    virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3127 		vi->any_header_sg = true;
3128 
3129 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3130 		vi->has_cvq = true;
3131 
3132 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3133 		mtu = virtio_cread16(vdev,
3134 				     offsetof(struct virtio_net_config,
3135 					      mtu));
3136 		if (mtu < dev->min_mtu) {
3137 			/* Should never trigger: MTU was previously validated
3138 			 * in virtnet_validate.
3139 			 */
3140 			dev_err(&vdev->dev,
3141 				"device MTU appears to have changed it is now %d < %d",
3142 				mtu, dev->min_mtu);
3143 			err = -EINVAL;
3144 			goto free;
3145 		}
3146 
3147 		dev->mtu = mtu;
3148 		dev->max_mtu = mtu;
3149 
3150 		/* TODO: size buffers correctly in this case. */
3151 		if (dev->mtu > ETH_DATA_LEN)
3152 			vi->big_packets = true;
3153 	}
3154 
3155 	if (vi->any_header_sg)
3156 		dev->needed_headroom = vi->hdr_len;
3157 
3158 	/* Enable multiqueue by default */
3159 	if (num_online_cpus() >= max_queue_pairs)
3160 		vi->curr_queue_pairs = max_queue_pairs;
3161 	else
3162 		vi->curr_queue_pairs = num_online_cpus();
3163 	vi->max_queue_pairs = max_queue_pairs;
3164 
3165 	/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
3166 	err = init_vqs(vi);
3167 	if (err)
3168 		goto free;
3169 
3170 #ifdef CONFIG_SYSFS
3171 	if (vi->mergeable_rx_bufs)
3172 		dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
3173 #endif
3174 	netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
3175 	netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
3176 
3177 	virtnet_init_settings(dev);
3178 
3179 	if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
3180 		vi->failover = net_failover_create(vi->dev);
3181 		if (IS_ERR(vi->failover)) {
3182 			err = PTR_ERR(vi->failover);
3183 			goto free_vqs;
3184 		}
3185 	}
3186 
3187 	err = register_netdev(dev);
3188 	if (err) {
3189 		pr_debug("virtio_net: registering device failed\n");
3190 		goto free_failover;
3191 	}
3192 
3193 	virtio_device_ready(vdev);
3194 
3195 	err = virtnet_cpu_notif_add(vi);
3196 	if (err) {
3197 		pr_debug("virtio_net: registering cpu notifier failed\n");
3198 		goto free_unregister_netdev;
3199 	}
3200 
3201 	virtnet_set_queues(vi, vi->curr_queue_pairs);
3202 
3203 	/* Assume link up if device can't report link status,
3204 	   otherwise get link status from config. */
3205 	netif_carrier_off(dev);
3206 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
3207 		schedule_work(&vi->config_work);
3208 	} else {
3209 		vi->status = VIRTIO_NET_S_LINK_UP;
3210 		virtnet_update_settings(vi);
3211 		netif_carrier_on(dev);
3212 	}
3213 
3214 	for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
3215 		if (virtio_has_feature(vi->vdev, guest_offloads[i]))
3216 			set_bit(guest_offloads[i], &vi->guest_offloads);
3217 	vi->guest_offloads_capable = vi->guest_offloads;
3218 
3219 	pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
3220 		 dev->name, max_queue_pairs);
3221 
3222 	return 0;
3223 
3224 free_unregister_netdev:
3225 	vi->vdev->config->reset(vdev);
3226 
3227 	unregister_netdev(dev);
3228 free_failover:
3229 	net_failover_destroy(vi->failover);
3230 free_vqs:
3231 	cancel_delayed_work_sync(&vi->refill);
3232 	free_receive_page_frags(vi);
3233 	virtnet_del_vqs(vi);
3234 free:
3235 	free_netdev(dev);
3236 	return err;
3237 }
3238 
remove_vq_common(struct virtnet_info * vi)3239 static void remove_vq_common(struct virtnet_info *vi)
3240 {
3241 	vi->vdev->config->reset(vi->vdev);
3242 
3243 	/* Free unused buffers in both send and recv, if any. */
3244 	free_unused_bufs(vi);
3245 
3246 	free_receive_bufs(vi);
3247 
3248 	free_receive_page_frags(vi);
3249 
3250 	virtnet_del_vqs(vi);
3251 }
3252 
virtnet_remove(struct virtio_device * vdev)3253 static void virtnet_remove(struct virtio_device *vdev)
3254 {
3255 	struct virtnet_info *vi = vdev->priv;
3256 
3257 	virtnet_cpu_notif_remove(vi);
3258 
3259 	/* Make sure no work handler is accessing the device. */
3260 	flush_work(&vi->config_work);
3261 
3262 	unregister_netdev(vi->dev);
3263 
3264 	net_failover_destroy(vi->failover);
3265 
3266 	remove_vq_common(vi);
3267 
3268 	free_netdev(vi->dev);
3269 }
3270 
virtnet_freeze(struct virtio_device * vdev)3271 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
3272 {
3273 	struct virtnet_info *vi = vdev->priv;
3274 
3275 	virtnet_cpu_notif_remove(vi);
3276 	virtnet_freeze_down(vdev);
3277 	remove_vq_common(vi);
3278 
3279 	return 0;
3280 }
3281 
virtnet_restore(struct virtio_device * vdev)3282 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
3283 {
3284 	struct virtnet_info *vi = vdev->priv;
3285 	int err;
3286 
3287 	err = virtnet_restore_up(vdev);
3288 	if (err)
3289 		return err;
3290 	virtnet_set_queues(vi, vi->curr_queue_pairs);
3291 
3292 	err = virtnet_cpu_notif_add(vi);
3293 	if (err) {
3294 		virtnet_freeze_down(vdev);
3295 		remove_vq_common(vi);
3296 		return err;
3297 	}
3298 
3299 	return 0;
3300 }
3301 
3302 static struct virtio_device_id id_table[] = {
3303 	{ VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
3304 	{ 0 },
3305 };
3306 
3307 #define VIRTNET_FEATURES \
3308 	VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
3309 	VIRTIO_NET_F_MAC, \
3310 	VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
3311 	VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
3312 	VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
3313 	VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
3314 	VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
3315 	VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
3316 	VIRTIO_NET_F_CTRL_MAC_ADDR, \
3317 	VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
3318 	VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY
3319 
3320 static unsigned int features[] = {
3321 	VIRTNET_FEATURES,
3322 };
3323 
3324 static unsigned int features_legacy[] = {
3325 	VIRTNET_FEATURES,
3326 	VIRTIO_NET_F_GSO,
3327 	VIRTIO_F_ANY_LAYOUT,
3328 };
3329 
3330 static struct virtio_driver virtio_net_driver = {
3331 	.feature_table = features,
3332 	.feature_table_size = ARRAY_SIZE(features),
3333 	.feature_table_legacy = features_legacy,
3334 	.feature_table_size_legacy = ARRAY_SIZE(features_legacy),
3335 	.driver.name =	KBUILD_MODNAME,
3336 	.driver.owner =	THIS_MODULE,
3337 	.id_table =	id_table,
3338 	.validate =	virtnet_validate,
3339 	.probe =	virtnet_probe,
3340 	.remove =	virtnet_remove,
3341 	.config_changed = virtnet_config_changed,
3342 #ifdef CONFIG_PM_SLEEP
3343 	.freeze =	virtnet_freeze,
3344 	.restore =	virtnet_restore,
3345 #endif
3346 };
3347 
virtio_net_driver_init(void)3348 static __init int virtio_net_driver_init(void)
3349 {
3350 	int ret;
3351 
3352 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
3353 				      virtnet_cpu_online,
3354 				      virtnet_cpu_down_prep);
3355 	if (ret < 0)
3356 		goto out;
3357 	virtionet_online = ret;
3358 	ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
3359 				      NULL, virtnet_cpu_dead);
3360 	if (ret)
3361 		goto err_dead;
3362 
3363         ret = register_virtio_driver(&virtio_net_driver);
3364 	if (ret)
3365 		goto err_virtio;
3366 	return 0;
3367 err_virtio:
3368 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
3369 err_dead:
3370 	cpuhp_remove_multi_state(virtionet_online);
3371 out:
3372 	return ret;
3373 }
3374 module_init(virtio_net_driver_init);
3375 
virtio_net_driver_exit(void)3376 static __exit void virtio_net_driver_exit(void)
3377 {
3378 	unregister_virtio_driver(&virtio_net_driver);
3379 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
3380 	cpuhp_remove_multi_state(virtionet_online);
3381 }
3382 module_exit(virtio_net_driver_exit);
3383 
3384 MODULE_DEVICE_TABLE(virtio, id_table);
3385 MODULE_DESCRIPTION("Virtio network driver");
3386 MODULE_LICENSE("GPL");
3387