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