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