1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* A network driver using virtio.
4 * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
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>
24 #include <net/net_failover.h>
26 static int napi_weight = NAPI_POLL_WEIGHT;
27 module_param(napi_weight, int, 0444);
29 static bool csum = true, gso = true, napi_tx = true;
30 module_param(csum, bool, 0444);
31 module_param(gso, bool, 0444);
32 module_param(napi_tx, bool, 0644);
34 /* FIXME: MTU in config. */
35 #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
36 #define GOOD_COPY_LEN 128
38 #define VIRTNET_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
40 /* Amount of XDP headroom to prepend to packets for use by xdp_adjust_head */
41 #define VIRTIO_XDP_HEADROOM 256
43 /* Separating two types of XDP xmit */
44 #define VIRTIO_XDP_TX BIT(0)
45 #define VIRTIO_XDP_REDIR BIT(1)
47 #define VIRTIO_XDP_FLAG BIT(0)
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.
54 DECLARE_EWMA(pkt_len, 0, 64)
56 #define VIRTNET_DRIVER_VERSION "1.0.0"
58 static const unsigned long guest_offloads[] = {
59 VIRTIO_NET_F_GUEST_TSO4,
60 VIRTIO_NET_F_GUEST_TSO6,
61 VIRTIO_NET_F_GUEST_ECN,
62 VIRTIO_NET_F_GUEST_UFO,
63 VIRTIO_NET_F_GUEST_CSUM
66 #define GUEST_OFFLOAD_LRO_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))
71 struct virtnet_stat_desc {
72 char desc[ETH_GSTRING_LEN];
76 struct virtnet_sq_stats {
77 struct u64_stats_sync syncp;
85 struct virtnet_rq_stats {
86 struct u64_stats_sync syncp;
97 #define VIRTNET_SQ_STAT(m) offsetof(struct virtnet_sq_stats, m)
98 #define VIRTNET_RQ_STAT(m) offsetof(struct virtnet_rq_stats, m)
100 static const struct virtnet_stat_desc virtnet_sq_stats_desc[] = {
101 { "packets", VIRTNET_SQ_STAT(packets) },
102 { "bytes", VIRTNET_SQ_STAT(bytes) },
103 { "xdp_tx", VIRTNET_SQ_STAT(xdp_tx) },
104 { "xdp_tx_drops", VIRTNET_SQ_STAT(xdp_tx_drops) },
105 { "kicks", VIRTNET_SQ_STAT(kicks) },
108 static const struct virtnet_stat_desc virtnet_rq_stats_desc[] = {
109 { "packets", VIRTNET_RQ_STAT(packets) },
110 { "bytes", VIRTNET_RQ_STAT(bytes) },
111 { "drops", VIRTNET_RQ_STAT(drops) },
112 { "xdp_packets", VIRTNET_RQ_STAT(xdp_packets) },
113 { "xdp_tx", VIRTNET_RQ_STAT(xdp_tx) },
114 { "xdp_redirects", VIRTNET_RQ_STAT(xdp_redirects) },
115 { "xdp_drops", VIRTNET_RQ_STAT(xdp_drops) },
116 { "kicks", VIRTNET_RQ_STAT(kicks) },
119 #define VIRTNET_SQ_STATS_LEN ARRAY_SIZE(virtnet_sq_stats_desc)
120 #define VIRTNET_RQ_STATS_LEN ARRAY_SIZE(virtnet_rq_stats_desc)
122 /* Internal representation of a send virtqueue */
124 /* Virtqueue associated with this send _queue */
125 struct virtqueue *vq;
127 /* TX: fragments + linear part + virtio header */
128 struct scatterlist sg[MAX_SKB_FRAGS + 2];
130 /* Name of the send queue: output.$index */
133 struct virtnet_sq_stats stats;
135 struct napi_struct napi;
138 /* Internal representation of a receive virtqueue */
139 struct receive_queue {
140 /* Virtqueue associated with this receive_queue */
141 struct virtqueue *vq;
143 struct napi_struct napi;
145 struct bpf_prog __rcu *xdp_prog;
147 struct virtnet_rq_stats stats;
149 /* Chain pages by the private ptr. */
152 /* Average packet length for mergeable receive buffers. */
153 struct ewma_pkt_len mrg_avg_pkt_len;
155 /* Page frag for packet buffer allocation. */
156 struct page_frag alloc_frag;
158 /* RX: fragments + linear part + virtio header */
159 struct scatterlist sg[MAX_SKB_FRAGS + 2];
161 /* Min single buffer size for mergeable buffers case. */
162 unsigned int min_buf_len;
164 /* Name of this receive queue: input.$index */
167 struct xdp_rxq_info xdp_rxq;
170 /* Control VQ buffers: protected by the rtnl lock */
172 struct virtio_net_ctrl_hdr hdr;
173 virtio_net_ctrl_ack status;
174 struct virtio_net_ctrl_mq mq;
181 struct virtnet_info {
182 struct virtio_device *vdev;
183 struct virtqueue *cvq;
184 struct net_device *dev;
185 struct send_queue *sq;
186 struct receive_queue *rq;
189 /* Max # of queue pairs supported by the device */
192 /* # of queue pairs currently used by the driver */
193 u16 curr_queue_pairs;
195 /* # of XDP queue pairs currently used by the driver */
198 /* xdp_queue_pairs may be 0, when xdp is already loaded. So add this. */
201 /* I like... big packets and I cannot lie! */
204 /* Host will merge rx buffers for big packets (shake it! shake it!) */
205 bool mergeable_rx_bufs;
207 /* Has control virtqueue */
210 /* Host can handle any s/g split between our header and packet data */
213 /* Packet virtio header size */
216 /* Work struct for refilling if we run low on memory. */
217 struct delayed_work refill;
219 /* Work struct for config space updates */
220 struct work_struct config_work;
222 /* Does the affinity hint is set for virtqueues? */
223 bool affinity_hint_set;
225 /* CPU hotplug instances for online & dead */
226 struct hlist_node node;
227 struct hlist_node node_dead;
229 struct control_buf *ctrl;
231 /* Ethtool settings */
235 unsigned long guest_offloads;
236 unsigned long guest_offloads_capable;
238 /* failover when STANDBY feature enabled */
239 struct failover *failover;
242 struct padded_vnet_hdr {
243 struct virtio_net_hdr_mrg_rxbuf hdr;
245 * hdr is in a separate sg buffer, and data sg buffer shares same page
246 * with this header sg. This padding makes next sg 16 byte aligned
252 static bool is_xdp_frame(void *ptr)
254 return (unsigned long)ptr & VIRTIO_XDP_FLAG;
257 static void *xdp_to_ptr(struct xdp_frame *ptr)
259 return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
262 static struct xdp_frame *ptr_to_xdp(void *ptr)
264 return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
267 /* Converting between virtqueue no. and kernel tx/rx queue no.
268 * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
270 static int vq2txq(struct virtqueue *vq)
272 return (vq->index - 1) / 2;
275 static int txq2vq(int txq)
280 static int vq2rxq(struct virtqueue *vq)
282 return vq->index / 2;
285 static int rxq2vq(int rxq)
290 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
292 return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
296 * private is used to chain pages for big packets, put the whole
297 * most recent used list in the beginning for reuse
299 static void give_pages(struct receive_queue *rq, struct page *page)
303 /* Find end of list, sew whole thing into vi->rq.pages. */
304 for (end = page; end->private; end = (struct page *)end->private);
305 end->private = (unsigned long)rq->pages;
309 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
311 struct page *p = rq->pages;
314 rq->pages = (struct page *)p->private;
315 /* clear private here, it is used to chain pages */
318 p = alloc_page(gfp_mask);
322 static void virtqueue_napi_schedule(struct napi_struct *napi,
323 struct virtqueue *vq)
325 if (napi_schedule_prep(napi)) {
326 virtqueue_disable_cb(vq);
327 __napi_schedule(napi);
331 static void virtqueue_napi_complete(struct napi_struct *napi,
332 struct virtqueue *vq, int processed)
336 opaque = virtqueue_enable_cb_prepare(vq);
337 if (napi_complete_done(napi, processed)) {
338 if (unlikely(virtqueue_poll(vq, opaque)))
339 virtqueue_napi_schedule(napi, vq);
341 virtqueue_disable_cb(vq);
345 static void skb_xmit_done(struct virtqueue *vq)
347 struct virtnet_info *vi = vq->vdev->priv;
348 struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
350 /* Suppress further interrupts. */
351 virtqueue_disable_cb(vq);
354 virtqueue_napi_schedule(napi, vq);
356 /* We were probably waiting for more output buffers. */
357 netif_wake_subqueue(vi->dev, vq2txq(vq));
360 #define MRG_CTX_HEADER_SHIFT 22
361 static void *mergeable_len_to_ctx(unsigned int truesize,
362 unsigned int headroom)
364 return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
367 static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
369 return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
372 static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
374 return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
377 /* Called from bottom half context */
378 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
379 struct receive_queue *rq,
380 struct page *page, unsigned int offset,
381 unsigned int len, unsigned int truesize,
382 bool hdr_valid, unsigned int metasize,
383 unsigned int headroom)
386 struct virtio_net_hdr_mrg_rxbuf *hdr;
387 unsigned int copy, hdr_len, hdr_padded_len;
388 struct page *page_to_free = NULL;
389 int tailroom, shinfo_size;
390 char *p, *hdr_p, *buf;
392 p = page_address(page) + offset;
395 hdr_len = vi->hdr_len;
396 if (vi->mergeable_rx_bufs)
397 hdr_padded_len = sizeof(*hdr);
399 hdr_padded_len = sizeof(struct padded_vnet_hdr);
401 /* If headroom is not 0, there is an offset between the beginning of the
402 * data and the allocated space, otherwise the data and the allocated
405 * Buffers with headroom use PAGE_SIZE as alloc size, see
406 * add_recvbuf_mergeable() + get_mergeable_buf_len()
408 truesize = headroom ? PAGE_SIZE : truesize;
409 tailroom = truesize - len - headroom - (hdr_padded_len - hdr_len);
413 offset += hdr_padded_len;
416 shinfo_size = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
418 /* copy small packet so we can reuse these pages */
419 if (!NET_IP_ALIGN && len > GOOD_COPY_LEN && tailroom >= shinfo_size) {
420 skb = build_skb(buf, truesize);
424 skb_reserve(skb, p - buf);
429 /* copy small packet so we can reuse these pages for small data */
430 skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
434 /* Copy all frame if it fits skb->head, otherwise
435 * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
437 if (len <= skb_tailroom(skb))
440 copy = ETH_HLEN + metasize;
441 skb_put_data(skb, p, copy);
446 if (vi->mergeable_rx_bufs) {
448 skb_add_rx_frag(skb, 0, page, offset, len, truesize);
455 * Verify that we can indeed put this data into a skb.
456 * This is here to handle cases when the device erroneously
457 * tries to receive more than is possible. This is usually
458 * the case of a broken device.
460 if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
461 net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
465 BUG_ON(offset >= PAGE_SIZE);
467 unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
468 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
469 frag_size, truesize);
471 page = (struct page *)page->private;
476 give_pages(rq, page);
479 /* hdr_valid means no XDP, so we can copy the vnet header */
481 hdr = skb_vnet_hdr(skb);
482 memcpy(hdr, hdr_p, hdr_len);
485 put_page(page_to_free);
488 __skb_pull(skb, metasize);
489 skb_metadata_set(skb, metasize);
495 static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
496 struct send_queue *sq,
497 struct xdp_frame *xdpf)
499 struct virtio_net_hdr_mrg_rxbuf *hdr;
502 if (unlikely(xdpf->headroom < vi->hdr_len))
505 /* Make room for virtqueue hdr (also change xdpf->headroom?) */
506 xdpf->data -= vi->hdr_len;
507 /* Zero header and leave csum up to XDP layers */
509 memset(hdr, 0, vi->hdr_len);
510 xdpf->len += vi->hdr_len;
512 sg_init_one(sq->sg, xdpf->data, xdpf->len);
514 err = virtqueue_add_outbuf(sq->vq, sq->sg, 1, xdp_to_ptr(xdpf),
517 return -ENOSPC; /* Caller handle free/refcnt */
522 /* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
523 * the current cpu, so it does not need to be locked.
525 * Here we use marco instead of inline functions because we have to deal with
526 * three issues at the same time: 1. the choice of sq. 2. judge and execute the
527 * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
528 * functions to perfectly solve these three problems at the same time.
530 #define virtnet_xdp_get_sq(vi) ({ \
531 struct netdev_queue *txq; \
532 typeof(vi) v = (vi); \
535 if (v->curr_queue_pairs > nr_cpu_ids) { \
536 qp = v->curr_queue_pairs - v->xdp_queue_pairs; \
537 qp += smp_processor_id(); \
538 txq = netdev_get_tx_queue(v->dev, qp); \
539 __netif_tx_acquire(txq); \
541 qp = smp_processor_id() % v->curr_queue_pairs; \
542 txq = netdev_get_tx_queue(v->dev, qp); \
543 __netif_tx_lock(txq, raw_smp_processor_id()); \
548 #define virtnet_xdp_put_sq(vi, q) { \
549 struct netdev_queue *txq; \
550 typeof(vi) v = (vi); \
552 txq = netdev_get_tx_queue(v->dev, (q) - v->sq); \
553 if (v->curr_queue_pairs > nr_cpu_ids) \
554 __netif_tx_release(txq); \
556 __netif_tx_unlock(txq); \
559 static int virtnet_xdp_xmit(struct net_device *dev,
560 int n, struct xdp_frame **frames, u32 flags)
562 struct virtnet_info *vi = netdev_priv(dev);
563 struct receive_queue *rq = vi->rq;
564 struct bpf_prog *xdp_prog;
565 struct send_queue *sq;
575 /* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
576 * indicate XDP resources have been successfully allocated.
578 xdp_prog = rcu_access_pointer(rq->xdp_prog);
582 sq = virtnet_xdp_get_sq(vi);
584 if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
589 /* Free up any pending old buffers before queueing new ones. */
590 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
591 if (likely(is_xdp_frame(ptr))) {
592 struct xdp_frame *frame = ptr_to_xdp(ptr);
595 xdp_return_frame(frame);
597 struct sk_buff *skb = ptr;
600 napi_consume_skb(skb, false);
605 for (i = 0; i < n; i++) {
606 struct xdp_frame *xdpf = frames[i];
608 if (__virtnet_xdp_xmit_one(vi, sq, xdpf))
614 if (flags & XDP_XMIT_FLUSH) {
615 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
619 u64_stats_update_begin(&sq->stats.syncp);
620 sq->stats.bytes += bytes;
621 sq->stats.packets += packets;
622 sq->stats.xdp_tx += n;
623 sq->stats.xdp_tx_drops += n - nxmit;
624 sq->stats.kicks += kicks;
625 u64_stats_update_end(&sq->stats.syncp);
627 virtnet_xdp_put_sq(vi, sq);
631 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
633 return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
636 /* We copy the packet for XDP in the following cases:
638 * 1) Packet is scattered across multiple rx buffers.
639 * 2) Headroom space is insufficient.
641 * This is inefficient but it's a temporary condition that
642 * we hit right after XDP is enabled and until queue is refilled
643 * with large buffers with sufficient headroom - so it should affect
644 * at most queue size packets.
645 * Afterwards, the conditions to enable
646 * XDP should preclude the underlying device from sending packets
647 * across multiple buffers (num_buf > 1), and we make sure buffers
648 * have enough headroom.
650 static struct page *xdp_linearize_page(struct receive_queue *rq,
657 struct page *page = alloc_page(GFP_ATOMIC);
662 memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
666 int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
671 buf = virtqueue_get_buf(rq->vq, &buflen);
675 p = virt_to_head_page(buf);
676 off = buf - page_address(p);
678 /* guard against a misconfigured or uncooperative backend that
679 * is sending packet larger than the MTU.
681 if ((page_off + buflen + tailroom) > PAGE_SIZE) {
686 memcpy(page_address(page) + page_off,
687 page_address(p) + off, buflen);
692 /* Headroom does not contribute to packet length */
693 *len = page_off - VIRTIO_XDP_HEADROOM;
696 __free_pages(page, 0);
700 static struct sk_buff *receive_small(struct net_device *dev,
701 struct virtnet_info *vi,
702 struct receive_queue *rq,
703 void *buf, void *ctx,
705 unsigned int *xdp_xmit,
706 struct virtnet_rq_stats *stats)
709 struct bpf_prog *xdp_prog;
710 unsigned int xdp_headroom = (unsigned long)ctx;
711 unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
712 unsigned int headroom = vi->hdr_len + header_offset;
713 unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
714 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
715 struct page *page = virt_to_head_page(buf);
716 unsigned int delta = 0;
717 struct page *xdp_page;
719 unsigned int metasize = 0;
725 xdp_prog = rcu_dereference(rq->xdp_prog);
727 struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
728 struct xdp_frame *xdpf;
733 if (unlikely(hdr->hdr.gso_type))
736 if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
737 int offset = buf - page_address(page) + header_offset;
738 unsigned int tlen = len + vi->hdr_len;
741 xdp_headroom = virtnet_get_headroom(vi);
742 header_offset = VIRTNET_RX_PAD + xdp_headroom;
743 headroom = vi->hdr_len + header_offset;
744 buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
745 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
746 xdp_page = xdp_linearize_page(rq, &num_buf, page,
747 offset, header_offset,
752 buf = page_address(xdp_page);
757 xdp_init_buff(&xdp, buflen, &rq->xdp_rxq);
758 xdp_prepare_buff(&xdp, buf + VIRTNET_RX_PAD + vi->hdr_len,
759 xdp_headroom, len, true);
760 orig_data = xdp.data;
761 act = bpf_prog_run_xdp(xdp_prog, &xdp);
762 stats->xdp_packets++;
766 /* Recalculate length in case bpf program changed it */
767 delta = orig_data - xdp.data;
768 len = xdp.data_end - xdp.data;
769 metasize = xdp.data - xdp.data_meta;
773 xdpf = xdp_convert_buff_to_frame(&xdp);
776 err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
777 if (unlikely(!err)) {
778 xdp_return_frame_rx_napi(xdpf);
779 } else if (unlikely(err < 0)) {
780 trace_xdp_exception(vi->dev, xdp_prog, act);
783 *xdp_xmit |= VIRTIO_XDP_TX;
787 stats->xdp_redirects++;
788 err = xdp_do_redirect(dev, &xdp, xdp_prog);
791 *xdp_xmit |= VIRTIO_XDP_REDIR;
795 bpf_warn_invalid_xdp_action(act);
798 trace_xdp_exception(vi->dev, xdp_prog, act);
806 skb = build_skb(buf, buflen);
811 skb_reserve(skb, headroom - delta);
814 buf += header_offset;
815 memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
816 } /* keep zeroed vnet hdr since XDP is loaded */
819 skb_metadata_set(skb, metasize);
833 static struct sk_buff *receive_big(struct net_device *dev,
834 struct virtnet_info *vi,
835 struct receive_queue *rq,
838 struct virtnet_rq_stats *stats)
840 struct page *page = buf;
841 struct sk_buff *skb =
842 page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, true, 0, 0);
844 stats->bytes += len - vi->hdr_len;
852 give_pages(rq, page);
856 static struct sk_buff *receive_mergeable(struct net_device *dev,
857 struct virtnet_info *vi,
858 struct receive_queue *rq,
862 unsigned int *xdp_xmit,
863 struct virtnet_rq_stats *stats)
865 struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
866 u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
867 struct page *page = virt_to_head_page(buf);
868 int offset = buf - page_address(page);
869 struct sk_buff *head_skb, *curr_skb;
870 struct bpf_prog *xdp_prog;
871 unsigned int truesize = mergeable_ctx_to_truesize(ctx);
872 unsigned int headroom = mergeable_ctx_to_headroom(ctx);
873 unsigned int metasize = 0;
874 unsigned int frame_sz;
878 stats->bytes += len - vi->hdr_len;
881 xdp_prog = rcu_dereference(rq->xdp_prog);
883 struct xdp_frame *xdpf;
884 struct page *xdp_page;
889 /* Transient failure which in theory could occur if
890 * in-flight packets from before XDP was enabled reach
891 * the receive path after XDP is loaded.
893 if (unlikely(hdr->hdr.gso_type))
896 /* Buffers with headroom use PAGE_SIZE as alloc size,
897 * see add_recvbuf_mergeable() + get_mergeable_buf_len()
899 frame_sz = headroom ? PAGE_SIZE : truesize;
901 /* This happens when rx buffer size is underestimated
902 * or headroom is not enough because of the buffer
903 * was refilled before XDP is set. This should only
904 * happen for the first several packets, so we don't
905 * care much about its performance.
907 if (unlikely(num_buf > 1 ||
908 headroom < virtnet_get_headroom(vi))) {
909 /* linearize data for XDP */
910 xdp_page = xdp_linearize_page(rq, &num_buf,
914 frame_sz = PAGE_SIZE;
918 offset = VIRTIO_XDP_HEADROOM;
923 /* Allow consuming headroom but reserve enough space to push
924 * the descriptor on if we get an XDP_TX return code.
926 data = page_address(xdp_page) + offset;
927 xdp_init_buff(&xdp, frame_sz - vi->hdr_len, &rq->xdp_rxq);
928 xdp_prepare_buff(&xdp, data - VIRTIO_XDP_HEADROOM + vi->hdr_len,
929 VIRTIO_XDP_HEADROOM, len - vi->hdr_len, true);
931 act = bpf_prog_run_xdp(xdp_prog, &xdp);
932 stats->xdp_packets++;
936 metasize = xdp.data - xdp.data_meta;
938 /* recalculate offset to account for any header
939 * adjustments and minus the metasize to copy the
940 * metadata in page_to_skb(). Note other cases do not
941 * build an skb and avoid using offset
943 offset = xdp.data - page_address(xdp_page) -
944 vi->hdr_len - metasize;
946 /* recalculate len if xdp.data, xdp.data_end or
947 * xdp.data_meta were adjusted
949 len = xdp.data_end - xdp.data + vi->hdr_len + metasize;
950 /* We can only create skb based on xdp_page. */
951 if (unlikely(xdp_page != page)) {
954 head_skb = page_to_skb(vi, rq, xdp_page, offset,
955 len, PAGE_SIZE, false,
957 VIRTIO_XDP_HEADROOM);
963 xdpf = xdp_convert_buff_to_frame(&xdp);
966 err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
967 if (unlikely(!err)) {
968 xdp_return_frame_rx_napi(xdpf);
969 } else if (unlikely(err < 0)) {
970 trace_xdp_exception(vi->dev, xdp_prog, act);
971 if (unlikely(xdp_page != page))
975 *xdp_xmit |= VIRTIO_XDP_TX;
976 if (unlikely(xdp_page != page))
981 stats->xdp_redirects++;
982 err = xdp_do_redirect(dev, &xdp, xdp_prog);
984 if (unlikely(xdp_page != page))
988 *xdp_xmit |= VIRTIO_XDP_REDIR;
989 if (unlikely(xdp_page != page))
994 bpf_warn_invalid_xdp_action(act);
997 trace_xdp_exception(vi->dev, xdp_prog, act);
1000 if (unlikely(xdp_page != page))
1001 __free_pages(xdp_page, 0);
1007 if (unlikely(len > truesize)) {
1008 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1009 dev->name, len, (unsigned long)ctx);
1010 dev->stats.rx_length_errors++;
1014 head_skb = page_to_skb(vi, rq, page, offset, len, truesize, !xdp_prog,
1015 metasize, headroom);
1016 curr_skb = head_skb;
1018 if (unlikely(!curr_skb))
1023 buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1024 if (unlikely(!buf)) {
1025 pr_debug("%s: rx error: %d buffers out of %d missing\n",
1027 virtio16_to_cpu(vi->vdev,
1029 dev->stats.rx_length_errors++;
1033 stats->bytes += len;
1034 page = virt_to_head_page(buf);
1036 truesize = mergeable_ctx_to_truesize(ctx);
1037 if (unlikely(len > truesize)) {
1038 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1039 dev->name, len, (unsigned long)ctx);
1040 dev->stats.rx_length_errors++;
1044 num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1045 if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1046 struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1048 if (unlikely(!nskb))
1050 if (curr_skb == head_skb)
1051 skb_shinfo(curr_skb)->frag_list = nskb;
1053 curr_skb->next = nskb;
1055 head_skb->truesize += nskb->truesize;
1058 if (curr_skb != head_skb) {
1059 head_skb->data_len += len;
1060 head_skb->len += len;
1061 head_skb->truesize += truesize;
1063 offset = buf - page_address(page);
1064 if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1066 skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1069 skb_add_rx_frag(curr_skb, num_skb_frags, page,
1070 offset, len, truesize);
1074 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1082 while (num_buf-- > 1) {
1083 buf = virtqueue_get_buf(rq->vq, &len);
1084 if (unlikely(!buf)) {
1085 pr_debug("%s: rx error: %d buffers missing\n",
1086 dev->name, num_buf);
1087 dev->stats.rx_length_errors++;
1090 stats->bytes += len;
1091 page = virt_to_head_page(buf);
1096 dev_kfree_skb(head_skb);
1101 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1102 void *buf, unsigned int len, void **ctx,
1103 unsigned int *xdp_xmit,
1104 struct virtnet_rq_stats *stats)
1106 struct net_device *dev = vi->dev;
1107 struct sk_buff *skb;
1108 struct virtio_net_hdr_mrg_rxbuf *hdr;
1110 if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1111 pr_debug("%s: short packet %i\n", dev->name, len);
1112 dev->stats.rx_length_errors++;
1113 if (vi->mergeable_rx_bufs) {
1114 put_page(virt_to_head_page(buf));
1115 } else if (vi->big_packets) {
1116 give_pages(rq, buf);
1118 put_page(virt_to_head_page(buf));
1123 if (vi->mergeable_rx_bufs)
1124 skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1126 else if (vi->big_packets)
1127 skb = receive_big(dev, vi, rq, buf, len, stats);
1129 skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1134 hdr = skb_vnet_hdr(skb);
1136 if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
1137 skb->ip_summed = CHECKSUM_UNNECESSARY;
1139 if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1140 virtio_is_little_endian(vi->vdev))) {
1141 net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1142 dev->name, hdr->hdr.gso_type,
1147 skb_record_rx_queue(skb, vq2rxq(rq->vq));
1148 skb->protocol = eth_type_trans(skb, dev);
1149 pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1150 ntohs(skb->protocol), skb->len, skb->pkt_type);
1152 napi_gro_receive(&rq->napi, skb);
1156 dev->stats.rx_frame_errors++;
1160 /* Unlike mergeable buffers, all buffers are allocated to the
1161 * same size, except for the headroom. For this reason we do
1162 * not need to use mergeable_len_to_ctx here - it is enough
1163 * to store the headroom as the context ignoring the truesize.
1165 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1168 struct page_frag *alloc_frag = &rq->alloc_frag;
1170 unsigned int xdp_headroom = virtnet_get_headroom(vi);
1171 void *ctx = (void *)(unsigned long)xdp_headroom;
1172 int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1175 len = SKB_DATA_ALIGN(len) +
1176 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1177 if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
1180 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1181 get_page(alloc_frag->page);
1182 alloc_frag->offset += len;
1183 sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1184 vi->hdr_len + GOOD_PACKET_LEN);
1185 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1187 put_page(virt_to_head_page(buf));
1191 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1194 struct page *first, *list = NULL;
1198 sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
1200 /* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
1201 for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
1202 first = get_a_page(rq, gfp);
1205 give_pages(rq, list);
1208 sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1210 /* chain new page in list head to match sg */
1211 first->private = (unsigned long)list;
1215 first = get_a_page(rq, gfp);
1217 give_pages(rq, list);
1220 p = page_address(first);
1222 /* rq->sg[0], rq->sg[1] share the same page */
1223 /* a separated rq->sg[0] for header - required in case !any_header_sg */
1224 sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1226 /* rq->sg[1] for data packet, from offset */
1227 offset = sizeof(struct padded_vnet_hdr);
1228 sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1230 /* chain first in list head */
1231 first->private = (unsigned long)list;
1232 err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
1235 give_pages(rq, first);
1240 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1241 struct ewma_pkt_len *avg_pkt_len,
1244 const size_t hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1248 return PAGE_SIZE - room;
1250 len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1251 rq->min_buf_len, PAGE_SIZE - hdr_len);
1253 return ALIGN(len, L1_CACHE_BYTES);
1256 static int add_recvbuf_mergeable(struct virtnet_info *vi,
1257 struct receive_queue *rq, gfp_t gfp)
1259 struct page_frag *alloc_frag = &rq->alloc_frag;
1260 unsigned int headroom = virtnet_get_headroom(vi);
1261 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1262 unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1266 unsigned int len, hole;
1268 /* Extra tailroom is needed to satisfy XDP's assumption. This
1269 * means rx frags coalescing won't work, but consider we've
1270 * disabled GSO for XDP, it won't be a big issue.
1272 len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1273 if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
1276 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1277 buf += headroom; /* advance address leaving hole at front of pkt */
1278 get_page(alloc_frag->page);
1279 alloc_frag->offset += len + room;
1280 hole = alloc_frag->size - alloc_frag->offset;
1281 if (hole < len + room) {
1282 /* To avoid internal fragmentation, if there is very likely not
1283 * enough space for another buffer, add the remaining space to
1284 * the current buffer.
1287 alloc_frag->offset += hole;
1290 sg_init_one(rq->sg, buf, len);
1291 ctx = mergeable_len_to_ctx(len, headroom);
1292 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1294 put_page(virt_to_head_page(buf));
1300 * Returns false if we couldn't fill entirely (OOM).
1302 * Normally run in the receive path, but can also be run from ndo_open
1303 * before we're receiving packets, or from refill_work which is
1304 * careful to disable receiving (using napi_disable).
1306 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1313 if (vi->mergeable_rx_bufs)
1314 err = add_recvbuf_mergeable(vi, rq, gfp);
1315 else if (vi->big_packets)
1316 err = add_recvbuf_big(vi, rq, gfp);
1318 err = add_recvbuf_small(vi, rq, gfp);
1320 oom = err == -ENOMEM;
1323 } while (rq->vq->num_free);
1324 if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
1325 unsigned long flags;
1327 flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1329 u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1335 static void skb_recv_done(struct virtqueue *rvq)
1337 struct virtnet_info *vi = rvq->vdev->priv;
1338 struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1340 virtqueue_napi_schedule(&rq->napi, rvq);
1343 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
1347 /* If all buffers were filled by other side before we napi_enabled, we
1348 * won't get another interrupt, so process any outstanding packets now.
1349 * Call local_bh_enable after to trigger softIRQ processing.
1352 virtqueue_napi_schedule(napi, vq);
1356 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1357 struct virtqueue *vq,
1358 struct napi_struct *napi)
1363 /* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1364 * enable the feature if this is likely affine with the transmit path.
1366 if (!vi->affinity_hint_set) {
1371 return virtnet_napi_enable(vq, napi);
1374 static void virtnet_napi_tx_disable(struct napi_struct *napi)
1380 static void refill_work(struct work_struct *work)
1382 struct virtnet_info *vi =
1383 container_of(work, struct virtnet_info, refill.work);
1387 for (i = 0; i < vi->curr_queue_pairs; i++) {
1388 struct receive_queue *rq = &vi->rq[i];
1390 napi_disable(&rq->napi);
1391 still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1392 virtnet_napi_enable(rq->vq, &rq->napi);
1394 /* In theory, this can happen: if we don't get any buffers in
1395 * we will *never* try to fill again.
1398 schedule_delayed_work(&vi->refill, HZ/2);
1402 static int virtnet_receive(struct receive_queue *rq, int budget,
1403 unsigned int *xdp_xmit)
1405 struct virtnet_info *vi = rq->vq->vdev->priv;
1406 struct virtnet_rq_stats stats = {};
1411 if (!vi->big_packets || vi->mergeable_rx_bufs) {
1414 while (stats.packets < budget &&
1415 (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1416 receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1420 while (stats.packets < budget &&
1421 (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1422 receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1427 if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1428 if (!try_fill_recv(vi, rq, GFP_ATOMIC))
1429 schedule_delayed_work(&vi->refill, 0);
1432 u64_stats_update_begin(&rq->stats.syncp);
1433 for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1434 size_t offset = virtnet_rq_stats_desc[i].offset;
1437 item = (u64 *)((u8 *)&rq->stats + offset);
1438 *item += *(u64 *)((u8 *)&stats + offset);
1440 u64_stats_update_end(&rq->stats.syncp);
1442 return stats.packets;
1445 static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
1448 unsigned int packets = 0;
1449 unsigned int bytes = 0;
1452 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
1453 if (likely(!is_xdp_frame(ptr))) {
1454 struct sk_buff *skb = ptr;
1456 pr_debug("Sent skb %p\n", skb);
1459 napi_consume_skb(skb, in_napi);
1461 struct xdp_frame *frame = ptr_to_xdp(ptr);
1463 bytes += frame->len;
1464 xdp_return_frame(frame);
1469 /* Avoid overhead when no packets have been processed
1470 * happens when called speculatively from start_xmit.
1475 u64_stats_update_begin(&sq->stats.syncp);
1476 sq->stats.bytes += bytes;
1477 sq->stats.packets += packets;
1478 u64_stats_update_end(&sq->stats.syncp);
1481 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
1483 if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
1485 else if (q < vi->curr_queue_pairs)
1491 static void virtnet_poll_cleantx(struct receive_queue *rq)
1493 struct virtnet_info *vi = rq->vq->vdev->priv;
1494 unsigned int index = vq2rxq(rq->vq);
1495 struct send_queue *sq = &vi->sq[index];
1496 struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
1498 if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
1501 if (__netif_tx_trylock(txq)) {
1502 free_old_xmit_skbs(sq, true);
1503 __netif_tx_unlock(txq);
1506 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1507 netif_tx_wake_queue(txq);
1510 static int virtnet_poll(struct napi_struct *napi, int budget)
1512 struct receive_queue *rq =
1513 container_of(napi, struct receive_queue, napi);
1514 struct virtnet_info *vi = rq->vq->vdev->priv;
1515 struct send_queue *sq;
1516 unsigned int received;
1517 unsigned int xdp_xmit = 0;
1519 virtnet_poll_cleantx(rq);
1521 received = virtnet_receive(rq, budget, &xdp_xmit);
1523 /* Out of packets? */
1524 if (received < budget)
1525 virtqueue_napi_complete(napi, rq->vq, received);
1527 if (xdp_xmit & VIRTIO_XDP_REDIR)
1530 if (xdp_xmit & VIRTIO_XDP_TX) {
1531 sq = virtnet_xdp_get_sq(vi);
1532 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1533 u64_stats_update_begin(&sq->stats.syncp);
1535 u64_stats_update_end(&sq->stats.syncp);
1537 virtnet_xdp_put_sq(vi, sq);
1543 static int virtnet_open(struct net_device *dev)
1545 struct virtnet_info *vi = netdev_priv(dev);
1548 for (i = 0; i < vi->max_queue_pairs; i++) {
1549 if (i < vi->curr_queue_pairs)
1550 /* Make sure we have some buffers: if oom use wq. */
1551 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1552 schedule_delayed_work(&vi->refill, 0);
1554 err = xdp_rxq_info_reg(&vi->rq[i].xdp_rxq, dev, i, vi->rq[i].napi.napi_id);
1558 err = xdp_rxq_info_reg_mem_model(&vi->rq[i].xdp_rxq,
1559 MEM_TYPE_PAGE_SHARED, NULL);
1561 xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1565 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1566 virtnet_napi_tx_enable(vi, vi->sq[i].vq, &vi->sq[i].napi);
1572 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1574 struct send_queue *sq = container_of(napi, struct send_queue, napi);
1575 struct virtnet_info *vi = sq->vq->vdev->priv;
1576 unsigned int index = vq2txq(sq->vq);
1577 struct netdev_queue *txq;
1579 if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
1580 /* We don't need to enable cb for XDP */
1581 napi_complete_done(napi, 0);
1585 txq = netdev_get_tx_queue(vi->dev, index);
1586 __netif_tx_lock(txq, raw_smp_processor_id());
1587 free_old_xmit_skbs(sq, true);
1588 __netif_tx_unlock(txq);
1590 virtqueue_napi_complete(napi, sq->vq, 0);
1592 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1593 netif_tx_wake_queue(txq);
1598 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1600 struct virtio_net_hdr_mrg_rxbuf *hdr;
1601 const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1602 struct virtnet_info *vi = sq->vq->vdev->priv;
1604 unsigned hdr_len = vi->hdr_len;
1607 pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1609 can_push = vi->any_header_sg &&
1610 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1611 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1612 /* Even if we can, don't push here yet as this would skew
1613 * csum_start offset below. */
1615 hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1617 hdr = skb_vnet_hdr(skb);
1619 if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1620 virtio_is_little_endian(vi->vdev), false,
1624 if (vi->mergeable_rx_bufs)
1625 hdr->num_buffers = 0;
1627 sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1629 __skb_push(skb, hdr_len);
1630 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1631 if (unlikely(num_sg < 0))
1633 /* Pull header back to avoid skew in tx bytes calculations. */
1634 __skb_pull(skb, hdr_len);
1636 sg_set_buf(sq->sg, hdr, hdr_len);
1637 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
1638 if (unlikely(num_sg < 0))
1642 return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1645 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1647 struct virtnet_info *vi = netdev_priv(dev);
1648 int qnum = skb_get_queue_mapping(skb);
1649 struct send_queue *sq = &vi->sq[qnum];
1651 struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1652 bool kick = !netdev_xmit_more();
1653 bool use_napi = sq->napi.weight;
1655 /* Free up any pending old buffers before queueing new ones. */
1656 free_old_xmit_skbs(sq, false);
1658 if (use_napi && kick)
1659 virtqueue_enable_cb_delayed(sq->vq);
1661 /* timestamp packet in software */
1662 skb_tx_timestamp(skb);
1664 /* Try to transmit */
1665 err = xmit_skb(sq, skb);
1667 /* This should not happen! */
1668 if (unlikely(err)) {
1669 dev->stats.tx_fifo_errors++;
1670 if (net_ratelimit())
1672 "Unexpected TXQ (%d) queue failure: %d\n",
1674 dev->stats.tx_dropped++;
1675 dev_kfree_skb_any(skb);
1676 return NETDEV_TX_OK;
1679 /* Don't wait up for transmitted skbs to be freed. */
1685 /* If running out of space, stop queue to avoid getting packets that we
1686 * are then unable to transmit.
1687 * An alternative would be to force queuing layer to requeue the skb by
1688 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
1689 * returned in a normal path of operation: it means that driver is not
1690 * maintaining the TX queue stop/start state properly, and causes
1691 * the stack to do a non-trivial amount of useless work.
1692 * Since most packets only take 1 or 2 ring slots, stopping the queue
1693 * early means 16 slots are typically wasted.
1695 if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1696 netif_stop_subqueue(dev, qnum);
1698 unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1699 /* More just got used, free them then recheck. */
1700 free_old_xmit_skbs(sq, false);
1701 if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1702 netif_start_subqueue(dev, qnum);
1703 virtqueue_disable_cb(sq->vq);
1708 if (kick || netif_xmit_stopped(txq)) {
1709 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1710 u64_stats_update_begin(&sq->stats.syncp);
1712 u64_stats_update_end(&sq->stats.syncp);
1716 return NETDEV_TX_OK;
1720 * Send command via the control virtqueue and check status. Commands
1721 * supported by the hypervisor, as indicated by feature bits, should
1722 * never fail unless improperly formatted.
1724 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1725 struct scatterlist *out)
1727 struct scatterlist *sgs[4], hdr, stat;
1728 unsigned out_num = 0, tmp;
1730 /* Caller should know better */
1731 BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1733 vi->ctrl->status = ~0;
1734 vi->ctrl->hdr.class = class;
1735 vi->ctrl->hdr.cmd = cmd;
1737 sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
1738 sgs[out_num++] = &hdr;
1741 sgs[out_num++] = out;
1743 /* Add return status. */
1744 sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
1745 sgs[out_num] = &stat;
1747 BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1748 virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1750 if (unlikely(!virtqueue_kick(vi->cvq)))
1751 return vi->ctrl->status == VIRTIO_NET_OK;
1753 /* Spin for a response, the kick causes an ioport write, trapping
1754 * into the hypervisor, so the request should be handled immediately.
1756 while (!virtqueue_get_buf(vi->cvq, &tmp) &&
1757 !virtqueue_is_broken(vi->cvq))
1760 return vi->ctrl->status == VIRTIO_NET_OK;
1763 static int virtnet_set_mac_address(struct net_device *dev, void *p)
1765 struct virtnet_info *vi = netdev_priv(dev);
1766 struct virtio_device *vdev = vi->vdev;
1768 struct sockaddr *addr;
1769 struct scatterlist sg;
1771 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
1774 addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
1778 ret = eth_prepare_mac_addr_change(dev, addr);
1782 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1783 sg_init_one(&sg, addr->sa_data, dev->addr_len);
1784 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1785 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
1786 dev_warn(&vdev->dev,
1787 "Failed to set mac address by vq command.\n");
1791 } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
1792 !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1795 /* Naturally, this has an atomicity problem. */
1796 for (i = 0; i < dev->addr_len; i++)
1797 virtio_cwrite8(vdev,
1798 offsetof(struct virtio_net_config, mac) +
1799 i, addr->sa_data[i]);
1802 eth_commit_mac_addr_change(dev, p);
1810 static void virtnet_stats(struct net_device *dev,
1811 struct rtnl_link_stats64 *tot)
1813 struct virtnet_info *vi = netdev_priv(dev);
1817 for (i = 0; i < vi->max_queue_pairs; i++) {
1818 u64 tpackets, tbytes, rpackets, rbytes, rdrops;
1819 struct receive_queue *rq = &vi->rq[i];
1820 struct send_queue *sq = &vi->sq[i];
1823 start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
1824 tpackets = sq->stats.packets;
1825 tbytes = sq->stats.bytes;
1826 } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
1829 start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
1830 rpackets = rq->stats.packets;
1831 rbytes = rq->stats.bytes;
1832 rdrops = rq->stats.drops;
1833 } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
1835 tot->rx_packets += rpackets;
1836 tot->tx_packets += tpackets;
1837 tot->rx_bytes += rbytes;
1838 tot->tx_bytes += tbytes;
1839 tot->rx_dropped += rdrops;
1842 tot->tx_dropped = dev->stats.tx_dropped;
1843 tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
1844 tot->rx_length_errors = dev->stats.rx_length_errors;
1845 tot->rx_frame_errors = dev->stats.rx_frame_errors;
1848 static void virtnet_ack_link_announce(struct virtnet_info *vi)
1851 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
1852 VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
1853 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
1857 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1859 struct scatterlist sg;
1860 struct net_device *dev = vi->dev;
1862 if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
1865 vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
1866 sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
1868 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
1869 VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
1870 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
1874 vi->curr_queue_pairs = queue_pairs;
1875 /* virtnet_open() will refill when device is going to up. */
1876 if (dev->flags & IFF_UP)
1877 schedule_delayed_work(&vi->refill, 0);
1883 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1888 err = _virtnet_set_queues(vi, queue_pairs);
1893 static int virtnet_close(struct net_device *dev)
1895 struct virtnet_info *vi = netdev_priv(dev);
1898 /* Make sure refill_work doesn't re-enable napi! */
1899 cancel_delayed_work_sync(&vi->refill);
1901 for (i = 0; i < vi->max_queue_pairs; i++) {
1902 xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1903 napi_disable(&vi->rq[i].napi);
1904 virtnet_napi_tx_disable(&vi->sq[i].napi);
1910 static void virtnet_set_rx_mode(struct net_device *dev)
1912 struct virtnet_info *vi = netdev_priv(dev);
1913 struct scatterlist sg[2];
1914 struct virtio_net_ctrl_mac *mac_data;
1915 struct netdev_hw_addr *ha;
1921 /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
1922 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
1925 vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
1926 vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
1928 sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
1930 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1931 VIRTIO_NET_CTRL_RX_PROMISC, sg))
1932 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
1933 vi->ctrl->promisc ? "en" : "dis");
1935 sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
1937 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1938 VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
1939 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
1940 vi->ctrl->allmulti ? "en" : "dis");
1942 uc_count = netdev_uc_count(dev);
1943 mc_count = netdev_mc_count(dev);
1944 /* MAC filter - use one buffer for both lists */
1945 buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
1946 (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
1951 sg_init_table(sg, 2);
1953 /* Store the unicast list and count in the front of the buffer */
1954 mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
1956 netdev_for_each_uc_addr(ha, dev)
1957 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1959 sg_set_buf(&sg[0], mac_data,
1960 sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
1962 /* multicast list and count fill the end */
1963 mac_data = (void *)&mac_data->macs[uc_count][0];
1965 mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
1967 netdev_for_each_mc_addr(ha, dev)
1968 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1970 sg_set_buf(&sg[1], mac_data,
1971 sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
1973 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1974 VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
1975 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
1980 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
1981 __be16 proto, u16 vid)
1983 struct virtnet_info *vi = netdev_priv(dev);
1984 struct scatterlist sg;
1986 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
1987 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
1989 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1990 VIRTIO_NET_CTRL_VLAN_ADD, &sg))
1991 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
1995 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
1996 __be16 proto, u16 vid)
1998 struct virtnet_info *vi = netdev_priv(dev);
1999 struct scatterlist sg;
2001 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2002 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2004 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2005 VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2006 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2010 static void virtnet_clean_affinity(struct virtnet_info *vi)
2014 if (vi->affinity_hint_set) {
2015 for (i = 0; i < vi->max_queue_pairs; i++) {
2016 virtqueue_set_affinity(vi->rq[i].vq, NULL);
2017 virtqueue_set_affinity(vi->sq[i].vq, NULL);
2020 vi->affinity_hint_set = false;
2024 static void virtnet_set_affinity(struct virtnet_info *vi)
2033 if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2034 virtnet_clean_affinity(vi);
2038 num_cpu = num_online_cpus();
2039 stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2040 stragglers = num_cpu >= vi->curr_queue_pairs ?
2041 num_cpu % vi->curr_queue_pairs :
2043 cpu = cpumask_next(-1, cpu_online_mask);
2045 for (i = 0; i < vi->curr_queue_pairs; i++) {
2046 group_size = stride + (i < stragglers ? 1 : 0);
2048 for (j = 0; j < group_size; j++) {
2049 cpumask_set_cpu(cpu, mask);
2050 cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2053 virtqueue_set_affinity(vi->rq[i].vq, mask);
2054 virtqueue_set_affinity(vi->sq[i].vq, mask);
2055 __netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2056 cpumask_clear(mask);
2059 vi->affinity_hint_set = true;
2060 free_cpumask_var(mask);
2063 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2065 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2067 virtnet_set_affinity(vi);
2071 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2073 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2075 virtnet_set_affinity(vi);
2079 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2081 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2084 virtnet_clean_affinity(vi);
2088 static enum cpuhp_state virtionet_online;
2090 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2094 ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2097 ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2101 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2105 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2107 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2108 cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2112 static void virtnet_get_ringparam(struct net_device *dev,
2113 struct ethtool_ringparam *ring)
2115 struct virtnet_info *vi = netdev_priv(dev);
2117 ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2118 ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2119 ring->rx_pending = ring->rx_max_pending;
2120 ring->tx_pending = ring->tx_max_pending;
2124 static void virtnet_get_drvinfo(struct net_device *dev,
2125 struct ethtool_drvinfo *info)
2127 struct virtnet_info *vi = netdev_priv(dev);
2128 struct virtio_device *vdev = vi->vdev;
2130 strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2131 strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2132 strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2136 /* TODO: Eliminate OOO packets during switching */
2137 static int virtnet_set_channels(struct net_device *dev,
2138 struct ethtool_channels *channels)
2140 struct virtnet_info *vi = netdev_priv(dev);
2141 u16 queue_pairs = channels->combined_count;
2144 /* We don't support separate rx/tx channels.
2145 * We don't allow setting 'other' channels.
2147 if (channels->rx_count || channels->tx_count || channels->other_count)
2150 if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2153 /* For now we don't support modifying channels while XDP is loaded
2154 * also when XDP is loaded all RX queues have XDP programs so we only
2155 * need to check a single RX queue.
2157 if (vi->rq[0].xdp_prog)
2161 err = _virtnet_set_queues(vi, queue_pairs);
2166 virtnet_set_affinity(vi);
2169 netif_set_real_num_tx_queues(dev, queue_pairs);
2170 netif_set_real_num_rx_queues(dev, queue_pairs);
2175 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2177 struct virtnet_info *vi = netdev_priv(dev);
2181 switch (stringset) {
2183 for (i = 0; i < vi->curr_queue_pairs; i++) {
2184 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
2185 ethtool_sprintf(&p, "rx_queue_%u_%s", i,
2186 virtnet_rq_stats_desc[j].desc);
2189 for (i = 0; i < vi->curr_queue_pairs; i++) {
2190 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
2191 ethtool_sprintf(&p, "tx_queue_%u_%s", i,
2192 virtnet_sq_stats_desc[j].desc);
2198 static int virtnet_get_sset_count(struct net_device *dev, int sset)
2200 struct virtnet_info *vi = netdev_priv(dev);
2204 return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2205 VIRTNET_SQ_STATS_LEN);
2211 static void virtnet_get_ethtool_stats(struct net_device *dev,
2212 struct ethtool_stats *stats, u64 *data)
2214 struct virtnet_info *vi = netdev_priv(dev);
2215 unsigned int idx = 0, start, i, j;
2216 const u8 *stats_base;
2219 for (i = 0; i < vi->curr_queue_pairs; i++) {
2220 struct receive_queue *rq = &vi->rq[i];
2222 stats_base = (u8 *)&rq->stats;
2224 start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2225 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2226 offset = virtnet_rq_stats_desc[j].offset;
2227 data[idx + j] = *(u64 *)(stats_base + offset);
2229 } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2230 idx += VIRTNET_RQ_STATS_LEN;
2233 for (i = 0; i < vi->curr_queue_pairs; i++) {
2234 struct send_queue *sq = &vi->sq[i];
2236 stats_base = (u8 *)&sq->stats;
2238 start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2239 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2240 offset = virtnet_sq_stats_desc[j].offset;
2241 data[idx + j] = *(u64 *)(stats_base + offset);
2243 } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2244 idx += VIRTNET_SQ_STATS_LEN;
2248 static void virtnet_get_channels(struct net_device *dev,
2249 struct ethtool_channels *channels)
2251 struct virtnet_info *vi = netdev_priv(dev);
2253 channels->combined_count = vi->curr_queue_pairs;
2254 channels->max_combined = vi->max_queue_pairs;
2255 channels->max_other = 0;
2256 channels->rx_count = 0;
2257 channels->tx_count = 0;
2258 channels->other_count = 0;
2261 static int virtnet_set_link_ksettings(struct net_device *dev,
2262 const struct ethtool_link_ksettings *cmd)
2264 struct virtnet_info *vi = netdev_priv(dev);
2266 return ethtool_virtdev_set_link_ksettings(dev, cmd,
2267 &vi->speed, &vi->duplex);
2270 static int virtnet_get_link_ksettings(struct net_device *dev,
2271 struct ethtool_link_ksettings *cmd)
2273 struct virtnet_info *vi = netdev_priv(dev);
2275 cmd->base.speed = vi->speed;
2276 cmd->base.duplex = vi->duplex;
2277 cmd->base.port = PORT_OTHER;
2282 static int virtnet_set_coalesce(struct net_device *dev,
2283 struct ethtool_coalesce *ec)
2285 struct virtnet_info *vi = netdev_priv(dev);
2288 if (ec->tx_max_coalesced_frames > 1 ||
2289 ec->rx_max_coalesced_frames != 1)
2292 napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
2293 if (napi_weight ^ vi->sq[0].napi.weight) {
2294 if (dev->flags & IFF_UP)
2296 for (i = 0; i < vi->max_queue_pairs; i++)
2297 vi->sq[i].napi.weight = napi_weight;
2303 static int virtnet_get_coalesce(struct net_device *dev,
2304 struct ethtool_coalesce *ec)
2306 struct ethtool_coalesce ec_default = {
2307 .cmd = ETHTOOL_GCOALESCE,
2308 .rx_max_coalesced_frames = 1,
2310 struct virtnet_info *vi = netdev_priv(dev);
2312 memcpy(ec, &ec_default, sizeof(ec_default));
2314 if (vi->sq[0].napi.weight)
2315 ec->tx_max_coalesced_frames = 1;
2320 static void virtnet_init_settings(struct net_device *dev)
2322 struct virtnet_info *vi = netdev_priv(dev);
2324 vi->speed = SPEED_UNKNOWN;
2325 vi->duplex = DUPLEX_UNKNOWN;
2328 static void virtnet_update_settings(struct virtnet_info *vi)
2333 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
2336 virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
2338 if (ethtool_validate_speed(speed))
2341 virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
2343 if (ethtool_validate_duplex(duplex))
2344 vi->duplex = duplex;
2347 static const struct ethtool_ops virtnet_ethtool_ops = {
2348 .supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES,
2349 .get_drvinfo = virtnet_get_drvinfo,
2350 .get_link = ethtool_op_get_link,
2351 .get_ringparam = virtnet_get_ringparam,
2352 .get_strings = virtnet_get_strings,
2353 .get_sset_count = virtnet_get_sset_count,
2354 .get_ethtool_stats = virtnet_get_ethtool_stats,
2355 .set_channels = virtnet_set_channels,
2356 .get_channels = virtnet_get_channels,
2357 .get_ts_info = ethtool_op_get_ts_info,
2358 .get_link_ksettings = virtnet_get_link_ksettings,
2359 .set_link_ksettings = virtnet_set_link_ksettings,
2360 .set_coalesce = virtnet_set_coalesce,
2361 .get_coalesce = virtnet_get_coalesce,
2364 static void virtnet_freeze_down(struct virtio_device *vdev)
2366 struct virtnet_info *vi = vdev->priv;
2369 /* Make sure no work handler is accessing the device */
2370 flush_work(&vi->config_work);
2372 netif_tx_lock_bh(vi->dev);
2373 netif_device_detach(vi->dev);
2374 netif_tx_unlock_bh(vi->dev);
2375 cancel_delayed_work_sync(&vi->refill);
2377 if (netif_running(vi->dev)) {
2378 for (i = 0; i < vi->max_queue_pairs; i++) {
2379 napi_disable(&vi->rq[i].napi);
2380 virtnet_napi_tx_disable(&vi->sq[i].napi);
2385 static int init_vqs(struct virtnet_info *vi);
2387 static int virtnet_restore_up(struct virtio_device *vdev)
2389 struct virtnet_info *vi = vdev->priv;
2396 virtio_device_ready(vdev);
2398 if (netif_running(vi->dev)) {
2399 for (i = 0; i < vi->curr_queue_pairs; i++)
2400 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
2401 schedule_delayed_work(&vi->refill, 0);
2403 for (i = 0; i < vi->max_queue_pairs; i++) {
2404 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2405 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2410 netif_tx_lock_bh(vi->dev);
2411 netif_device_attach(vi->dev);
2412 netif_tx_unlock_bh(vi->dev);
2416 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
2418 struct scatterlist sg;
2419 vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
2421 sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
2423 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
2424 VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
2425 dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
2432 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
2436 if (!vi->guest_offloads)
2439 return virtnet_set_guest_offloads(vi, offloads);
2442 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
2444 u64 offloads = vi->guest_offloads;
2446 if (!vi->guest_offloads)
2449 return virtnet_set_guest_offloads(vi, offloads);
2452 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
2453 struct netlink_ext_ack *extack)
2455 unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
2456 struct virtnet_info *vi = netdev_priv(dev);
2457 struct bpf_prog *old_prog;
2458 u16 xdp_qp = 0, curr_qp;
2461 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
2462 && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
2463 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
2464 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
2465 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
2466 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM))) {
2467 NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing LRO/CSUM, disable LRO/CSUM first");
2471 if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
2472 NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
2476 if (dev->mtu > max_sz) {
2477 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
2478 netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
2482 curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
2484 xdp_qp = nr_cpu_ids;
2486 /* XDP requires extra queues for XDP_TX */
2487 if (curr_qp + xdp_qp > vi->max_queue_pairs) {
2488 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",
2489 curr_qp + xdp_qp, vi->max_queue_pairs);
2493 old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
2494 if (!prog && !old_prog)
2498 bpf_prog_add(prog, vi->max_queue_pairs - 1);
2500 /* Make sure NAPI is not using any XDP TX queues for RX. */
2501 if (netif_running(dev)) {
2502 for (i = 0; i < vi->max_queue_pairs; i++) {
2503 napi_disable(&vi->rq[i].napi);
2504 virtnet_napi_tx_disable(&vi->sq[i].napi);
2509 for (i = 0; i < vi->max_queue_pairs; i++) {
2510 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
2512 virtnet_restore_guest_offloads(vi);
2517 err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
2520 netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
2521 vi->xdp_queue_pairs = xdp_qp;
2524 vi->xdp_enabled = true;
2525 for (i = 0; i < vi->max_queue_pairs; i++) {
2526 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
2527 if (i == 0 && !old_prog)
2528 virtnet_clear_guest_offloads(vi);
2531 vi->xdp_enabled = false;
2534 for (i = 0; i < vi->max_queue_pairs; i++) {
2536 bpf_prog_put(old_prog);
2537 if (netif_running(dev)) {
2538 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2539 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2548 virtnet_clear_guest_offloads(vi);
2549 for (i = 0; i < vi->max_queue_pairs; i++)
2550 rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
2553 if (netif_running(dev)) {
2554 for (i = 0; i < vi->max_queue_pairs; i++) {
2555 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2556 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2561 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
2565 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
2567 switch (xdp->command) {
2568 case XDP_SETUP_PROG:
2569 return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
2575 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
2578 struct virtnet_info *vi = netdev_priv(dev);
2581 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2584 ret = snprintf(buf, len, "sby");
2591 static int virtnet_set_features(struct net_device *dev,
2592 netdev_features_t features)
2594 struct virtnet_info *vi = netdev_priv(dev);
2598 if ((dev->features ^ features) & NETIF_F_LRO) {
2599 if (vi->xdp_enabled)
2602 if (features & NETIF_F_LRO)
2603 offloads = vi->guest_offloads_capable;
2605 offloads = vi->guest_offloads_capable &
2606 ~GUEST_OFFLOAD_LRO_MASK;
2608 err = virtnet_set_guest_offloads(vi, offloads);
2611 vi->guest_offloads = offloads;
2617 static const struct net_device_ops virtnet_netdev = {
2618 .ndo_open = virtnet_open,
2619 .ndo_stop = virtnet_close,
2620 .ndo_start_xmit = start_xmit,
2621 .ndo_validate_addr = eth_validate_addr,
2622 .ndo_set_mac_address = virtnet_set_mac_address,
2623 .ndo_set_rx_mode = virtnet_set_rx_mode,
2624 .ndo_get_stats64 = virtnet_stats,
2625 .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
2626 .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
2627 .ndo_bpf = virtnet_xdp,
2628 .ndo_xdp_xmit = virtnet_xdp_xmit,
2629 .ndo_features_check = passthru_features_check,
2630 .ndo_get_phys_port_name = virtnet_get_phys_port_name,
2631 .ndo_set_features = virtnet_set_features,
2634 static void virtnet_config_changed_work(struct work_struct *work)
2636 struct virtnet_info *vi =
2637 container_of(work, struct virtnet_info, config_work);
2640 if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
2641 struct virtio_net_config, status, &v) < 0)
2644 if (v & VIRTIO_NET_S_ANNOUNCE) {
2645 netdev_notify_peers(vi->dev);
2646 virtnet_ack_link_announce(vi);
2649 /* Ignore unknown (future) status bits */
2650 v &= VIRTIO_NET_S_LINK_UP;
2652 if (vi->status == v)
2657 if (vi->status & VIRTIO_NET_S_LINK_UP) {
2658 virtnet_update_settings(vi);
2659 netif_carrier_on(vi->dev);
2660 netif_tx_wake_all_queues(vi->dev);
2662 netif_carrier_off(vi->dev);
2663 netif_tx_stop_all_queues(vi->dev);
2667 static void virtnet_config_changed(struct virtio_device *vdev)
2669 struct virtnet_info *vi = vdev->priv;
2671 schedule_work(&vi->config_work);
2674 static void virtnet_free_queues(struct virtnet_info *vi)
2678 for (i = 0; i < vi->max_queue_pairs; i++) {
2679 __netif_napi_del(&vi->rq[i].napi);
2680 __netif_napi_del(&vi->sq[i].napi);
2683 /* We called __netif_napi_del(),
2684 * we need to respect an RCU grace period before freeing vi->rq
2693 static void _free_receive_bufs(struct virtnet_info *vi)
2695 struct bpf_prog *old_prog;
2698 for (i = 0; i < vi->max_queue_pairs; i++) {
2699 while (vi->rq[i].pages)
2700 __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
2702 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
2703 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
2705 bpf_prog_put(old_prog);
2709 static void free_receive_bufs(struct virtnet_info *vi)
2712 _free_receive_bufs(vi);
2716 static void free_receive_page_frags(struct virtnet_info *vi)
2719 for (i = 0; i < vi->max_queue_pairs; i++)
2720 if (vi->rq[i].alloc_frag.page)
2721 put_page(vi->rq[i].alloc_frag.page);
2724 static void free_unused_bufs(struct virtnet_info *vi)
2729 for (i = 0; i < vi->max_queue_pairs; i++) {
2730 struct virtqueue *vq = vi->sq[i].vq;
2731 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2732 if (!is_xdp_frame(buf))
2735 xdp_return_frame(ptr_to_xdp(buf));
2739 for (i = 0; i < vi->max_queue_pairs; i++) {
2740 struct virtqueue *vq = vi->rq[i].vq;
2742 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2743 if (vi->mergeable_rx_bufs) {
2744 put_page(virt_to_head_page(buf));
2745 } else if (vi->big_packets) {
2746 give_pages(&vi->rq[i], buf);
2748 put_page(virt_to_head_page(buf));
2754 static void virtnet_del_vqs(struct virtnet_info *vi)
2756 struct virtio_device *vdev = vi->vdev;
2758 virtnet_clean_affinity(vi);
2760 vdev->config->del_vqs(vdev);
2762 virtnet_free_queues(vi);
2765 /* How large should a single buffer be so a queue full of these can fit at
2766 * least one full packet?
2767 * Logic below assumes the mergeable buffer header is used.
2769 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
2771 const unsigned int hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2772 unsigned int rq_size = virtqueue_get_vring_size(vq);
2773 unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
2774 unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
2775 unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
2777 return max(max(min_buf_len, hdr_len) - hdr_len,
2778 (unsigned int)GOOD_PACKET_LEN);
2781 static int virtnet_find_vqs(struct virtnet_info *vi)
2783 vq_callback_t **callbacks;
2784 struct virtqueue **vqs;
2790 /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
2791 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
2792 * possible control vq.
2794 total_vqs = vi->max_queue_pairs * 2 +
2795 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
2797 /* Allocate space for find_vqs parameters */
2798 vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
2801 callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
2804 names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
2807 if (!vi->big_packets || vi->mergeable_rx_bufs) {
2808 ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
2815 /* Parameters for control virtqueue, if any */
2817 callbacks[total_vqs - 1] = NULL;
2818 names[total_vqs - 1] = "control";
2821 /* Allocate/initialize parameters for send/receive virtqueues */
2822 for (i = 0; i < vi->max_queue_pairs; i++) {
2823 callbacks[rxq2vq(i)] = skb_recv_done;
2824 callbacks[txq2vq(i)] = skb_xmit_done;
2825 sprintf(vi->rq[i].name, "input.%d", i);
2826 sprintf(vi->sq[i].name, "output.%d", i);
2827 names[rxq2vq(i)] = vi->rq[i].name;
2828 names[txq2vq(i)] = vi->sq[i].name;
2830 ctx[rxq2vq(i)] = true;
2833 ret = vi->vdev->config->find_vqs(vi->vdev, total_vqs, vqs, callbacks,
2839 vi->cvq = vqs[total_vqs - 1];
2840 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
2841 vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
2844 for (i = 0; i < vi->max_queue_pairs; i++) {
2845 vi->rq[i].vq = vqs[rxq2vq(i)];
2846 vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
2847 vi->sq[i].vq = vqs[txq2vq(i)];
2850 /* run here: ret == 0. */
2865 static int virtnet_alloc_queues(struct virtnet_info *vi)
2870 vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
2876 vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
2879 vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
2883 INIT_DELAYED_WORK(&vi->refill, refill_work);
2884 for (i = 0; i < vi->max_queue_pairs; i++) {
2885 vi->rq[i].pages = NULL;
2886 netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
2888 netif_tx_napi_add(vi->dev, &vi->sq[i].napi, virtnet_poll_tx,
2889 napi_tx ? napi_weight : 0);
2891 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
2892 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
2893 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
2895 u64_stats_init(&vi->rq[i].stats.syncp);
2896 u64_stats_init(&vi->sq[i].stats.syncp);
2909 static int init_vqs(struct virtnet_info *vi)
2913 /* Allocate send & receive queues */
2914 ret = virtnet_alloc_queues(vi);
2918 ret = virtnet_find_vqs(vi);
2923 virtnet_set_affinity(vi);
2929 virtnet_free_queues(vi);
2935 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
2938 struct virtnet_info *vi = netdev_priv(queue->dev);
2939 unsigned int queue_index = get_netdev_rx_queue_index(queue);
2940 unsigned int headroom = virtnet_get_headroom(vi);
2941 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
2942 struct ewma_pkt_len *avg;
2944 BUG_ON(queue_index >= vi->max_queue_pairs);
2945 avg = &vi->rq[queue_index].mrg_avg_pkt_len;
2946 return sprintf(buf, "%u\n",
2947 get_mergeable_buf_len(&vi->rq[queue_index], avg,
2948 SKB_DATA_ALIGN(headroom + tailroom)));
2951 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
2952 __ATTR_RO(mergeable_rx_buffer_size);
2954 static struct attribute *virtio_net_mrg_rx_attrs[] = {
2955 &mergeable_rx_buffer_size_attribute.attr,
2959 static const struct attribute_group virtio_net_mrg_rx_group = {
2960 .name = "virtio_net",
2961 .attrs = virtio_net_mrg_rx_attrs
2965 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
2967 const char *fname, const char *dname)
2969 if (!virtio_has_feature(vdev, fbit))
2972 dev_err(&vdev->dev, "device advertises feature %s but not %s",
2978 #define VIRTNET_FAIL_ON(vdev, fbit, dbit) \
2979 virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
2981 static bool virtnet_validate_features(struct virtio_device *vdev)
2983 if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
2984 (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
2985 "VIRTIO_NET_F_CTRL_VQ") ||
2986 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
2987 "VIRTIO_NET_F_CTRL_VQ") ||
2988 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
2989 "VIRTIO_NET_F_CTRL_VQ") ||
2990 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
2991 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
2992 "VIRTIO_NET_F_CTRL_VQ"))) {
2999 #define MIN_MTU ETH_MIN_MTU
3000 #define MAX_MTU ETH_MAX_MTU
3002 static int virtnet_validate(struct virtio_device *vdev)
3004 if (!vdev->config->get) {
3005 dev_err(&vdev->dev, "%s failure: config access disabled\n",
3010 if (!virtnet_validate_features(vdev))
3013 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3014 int mtu = virtio_cread16(vdev,
3015 offsetof(struct virtio_net_config,
3018 __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3024 static int virtnet_probe(struct virtio_device *vdev)
3026 int i, err = -ENOMEM;
3027 struct net_device *dev;
3028 struct virtnet_info *vi;
3029 u16 max_queue_pairs;
3032 /* Find if host supports multiqueue virtio_net device */
3033 err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
3034 struct virtio_net_config,
3035 max_virtqueue_pairs, &max_queue_pairs);
3037 /* We need at least 2 queue's */
3038 if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
3039 max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
3040 !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3041 max_queue_pairs = 1;
3043 /* Allocate ourselves a network device with room for our info */
3044 dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
3048 /* Set up network device as normal. */
3049 dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
3050 IFF_TX_SKB_NO_LINEAR;
3051 dev->netdev_ops = &virtnet_netdev;
3052 dev->features = NETIF_F_HIGHDMA;
3054 dev->ethtool_ops = &virtnet_ethtool_ops;
3055 SET_NETDEV_DEV(dev, &vdev->dev);
3057 /* Do we support "hardware" checksums? */
3058 if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
3059 /* This opens up the world of extra features. */
3060 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3062 dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3064 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
3065 dev->hw_features |= NETIF_F_TSO
3066 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
3068 /* Individual feature bits: what can host handle? */
3069 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
3070 dev->hw_features |= NETIF_F_TSO;
3071 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
3072 dev->hw_features |= NETIF_F_TSO6;
3073 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
3074 dev->hw_features |= NETIF_F_TSO_ECN;
3076 dev->features |= NETIF_F_GSO_ROBUST;
3079 dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
3080 /* (!csum && gso) case will be fixed by register_netdev() */
3082 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
3083 dev->features |= NETIF_F_RXCSUM;
3084 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3085 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3086 dev->features |= NETIF_F_LRO;
3087 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3088 dev->hw_features |= NETIF_F_LRO;
3090 dev->vlan_features = dev->features;
3092 /* MTU range: 68 - 65535 */
3093 dev->min_mtu = MIN_MTU;
3094 dev->max_mtu = MAX_MTU;
3096 /* Configuration may specify what MAC to use. Otherwise random. */
3097 if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
3098 virtio_cread_bytes(vdev,
3099 offsetof(struct virtio_net_config, mac),
3100 dev->dev_addr, dev->addr_len);
3102 eth_hw_addr_random(dev);
3104 /* Set up our device-specific information */
3105 vi = netdev_priv(dev);
3110 INIT_WORK(&vi->config_work, virtnet_config_changed_work);
3112 /* If we can receive ANY GSO packets, we must allocate large ones. */
3113 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3114 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3115 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
3116 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
3117 vi->big_packets = true;
3119 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
3120 vi->mergeable_rx_bufs = true;
3122 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
3123 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3124 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
3126 vi->hdr_len = sizeof(struct virtio_net_hdr);
3128 if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
3129 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3130 vi->any_header_sg = true;
3132 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3135 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3136 mtu = virtio_cread16(vdev,
3137 offsetof(struct virtio_net_config,
3139 if (mtu < dev->min_mtu) {
3140 /* Should never trigger: MTU was previously validated
3141 * in virtnet_validate.
3144 "device MTU appears to have changed it is now %d < %d",
3153 /* TODO: size buffers correctly in this case. */
3154 if (dev->mtu > ETH_DATA_LEN)
3155 vi->big_packets = true;
3158 if (vi->any_header_sg)
3159 dev->needed_headroom = vi->hdr_len;
3161 /* Enable multiqueue by default */
3162 if (num_online_cpus() >= max_queue_pairs)
3163 vi->curr_queue_pairs = max_queue_pairs;
3165 vi->curr_queue_pairs = num_online_cpus();
3166 vi->max_queue_pairs = max_queue_pairs;
3168 /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
3174 if (vi->mergeable_rx_bufs)
3175 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
3177 netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
3178 netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
3180 virtnet_init_settings(dev);
3182 if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
3183 vi->failover = net_failover_create(vi->dev);
3184 if (IS_ERR(vi->failover)) {
3185 err = PTR_ERR(vi->failover);
3190 err = register_netdev(dev);
3192 pr_debug("virtio_net: registering device failed\n");
3196 virtio_device_ready(vdev);
3198 err = virtnet_cpu_notif_add(vi);
3200 pr_debug("virtio_net: registering cpu notifier failed\n");
3201 goto free_unregister_netdev;
3204 virtnet_set_queues(vi, vi->curr_queue_pairs);
3206 /* Assume link up if device can't report link status,
3207 otherwise get link status from config. */
3208 netif_carrier_off(dev);
3209 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
3210 schedule_work(&vi->config_work);
3212 vi->status = VIRTIO_NET_S_LINK_UP;
3213 virtnet_update_settings(vi);
3214 netif_carrier_on(dev);
3217 for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
3218 if (virtio_has_feature(vi->vdev, guest_offloads[i]))
3219 set_bit(guest_offloads[i], &vi->guest_offloads);
3220 vi->guest_offloads_capable = vi->guest_offloads;
3222 pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
3223 dev->name, max_queue_pairs);
3227 free_unregister_netdev:
3228 vi->vdev->config->reset(vdev);
3230 unregister_netdev(dev);
3232 net_failover_destroy(vi->failover);
3234 cancel_delayed_work_sync(&vi->refill);
3235 free_receive_page_frags(vi);
3236 virtnet_del_vqs(vi);
3242 static void remove_vq_common(struct virtnet_info *vi)
3244 vi->vdev->config->reset(vi->vdev);
3246 /* Free unused buffers in both send and recv, if any. */
3247 free_unused_bufs(vi);
3249 free_receive_bufs(vi);
3251 free_receive_page_frags(vi);
3253 virtnet_del_vqs(vi);
3256 static void virtnet_remove(struct virtio_device *vdev)
3258 struct virtnet_info *vi = vdev->priv;
3260 virtnet_cpu_notif_remove(vi);
3262 /* Make sure no work handler is accessing the device. */
3263 flush_work(&vi->config_work);
3265 unregister_netdev(vi->dev);
3267 net_failover_destroy(vi->failover);
3269 remove_vq_common(vi);
3271 free_netdev(vi->dev);
3274 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
3276 struct virtnet_info *vi = vdev->priv;
3278 virtnet_cpu_notif_remove(vi);
3279 virtnet_freeze_down(vdev);
3280 remove_vq_common(vi);
3285 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
3287 struct virtnet_info *vi = vdev->priv;
3290 err = virtnet_restore_up(vdev);
3293 virtnet_set_queues(vi, vi->curr_queue_pairs);
3295 err = virtnet_cpu_notif_add(vi);
3302 static struct virtio_device_id id_table[] = {
3303 { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
3307 #define VIRTNET_FEATURES \
3308 VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
3310 VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
3311 VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
3312 VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
3313 VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
3314 VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
3315 VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
3316 VIRTIO_NET_F_CTRL_MAC_ADDR, \
3317 VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
3318 VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY
3320 static unsigned int features[] = {
3324 static unsigned int features_legacy[] = {
3327 VIRTIO_F_ANY_LAYOUT,
3330 static struct virtio_driver virtio_net_driver = {
3331 .feature_table = features,
3332 .feature_table_size = ARRAY_SIZE(features),
3333 .feature_table_legacy = features_legacy,
3334 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
3335 .driver.name = KBUILD_MODNAME,
3336 .driver.owner = THIS_MODULE,
3337 .id_table = id_table,
3338 .validate = virtnet_validate,
3339 .probe = virtnet_probe,
3340 .remove = virtnet_remove,
3341 .config_changed = virtnet_config_changed,
3342 #ifdef CONFIG_PM_SLEEP
3343 .freeze = virtnet_freeze,
3344 .restore = virtnet_restore,
3348 static __init int virtio_net_driver_init(void)
3352 ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
3354 virtnet_cpu_down_prep);
3357 virtionet_online = ret;
3358 ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
3359 NULL, virtnet_cpu_dead);
3363 ret = register_virtio_driver(&virtio_net_driver);
3368 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
3370 cpuhp_remove_multi_state(virtionet_online);
3374 module_init(virtio_net_driver_init);
3376 static __exit void virtio_net_driver_exit(void)
3378 unregister_virtio_driver(&virtio_net_driver);
3379 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
3380 cpuhp_remove_multi_state(virtionet_online);
3382 module_exit(virtio_net_driver_exit);
3384 MODULE_DEVICE_TABLE(virtio, id_table);
3385 MODULE_DESCRIPTION("Virtio network driver");
3386 MODULE_LICENSE("GPL");