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_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))
71 struct virtnet_stat_desc {
72 char desc[ETH_GSTRING_LEN];
76 struct virtnet_sq_stats {
77 struct u64_stats_sync syncp;
86 struct virtnet_rq_stats {
87 struct u64_stats_sync syncp;
98 #define VIRTNET_SQ_STAT(m) offsetof(struct virtnet_sq_stats, m)
99 #define VIRTNET_RQ_STAT(m) offsetof(struct virtnet_rq_stats, m)
101 static const struct virtnet_stat_desc virtnet_sq_stats_desc[] = {
102 { "packets", VIRTNET_SQ_STAT(packets) },
103 { "bytes", VIRTNET_SQ_STAT(bytes) },
104 { "xdp_tx", VIRTNET_SQ_STAT(xdp_tx) },
105 { "xdp_tx_drops", VIRTNET_SQ_STAT(xdp_tx_drops) },
106 { "kicks", VIRTNET_SQ_STAT(kicks) },
107 { "tx_timeouts", VIRTNET_SQ_STAT(tx_timeouts) },
110 static const struct virtnet_stat_desc virtnet_rq_stats_desc[] = {
111 { "packets", VIRTNET_RQ_STAT(packets) },
112 { "bytes", VIRTNET_RQ_STAT(bytes) },
113 { "drops", VIRTNET_RQ_STAT(drops) },
114 { "xdp_packets", VIRTNET_RQ_STAT(xdp_packets) },
115 { "xdp_tx", VIRTNET_RQ_STAT(xdp_tx) },
116 { "xdp_redirects", VIRTNET_RQ_STAT(xdp_redirects) },
117 { "xdp_drops", VIRTNET_RQ_STAT(xdp_drops) },
118 { "kicks", VIRTNET_RQ_STAT(kicks) },
121 #define VIRTNET_SQ_STATS_LEN ARRAY_SIZE(virtnet_sq_stats_desc)
122 #define VIRTNET_RQ_STATS_LEN ARRAY_SIZE(virtnet_rq_stats_desc)
124 /* Internal representation of a send virtqueue */
126 /* Virtqueue associated with this send _queue */
127 struct virtqueue *vq;
129 /* TX: fragments + linear part + virtio header */
130 struct scatterlist sg[MAX_SKB_FRAGS + 2];
132 /* Name of the send queue: output.$index */
135 struct virtnet_sq_stats stats;
137 struct napi_struct napi;
139 /* Record whether sq is in reset state. */
143 /* Internal representation of a receive virtqueue */
144 struct receive_queue {
145 /* Virtqueue associated with this receive_queue */
146 struct virtqueue *vq;
148 struct napi_struct napi;
150 struct bpf_prog __rcu *xdp_prog;
152 struct virtnet_rq_stats stats;
154 /* Chain pages by the private ptr. */
157 /* Average packet length for mergeable receive buffers. */
158 struct ewma_pkt_len mrg_avg_pkt_len;
160 /* Page frag for packet buffer allocation. */
161 struct page_frag alloc_frag;
163 /* RX: fragments + linear part + virtio header */
164 struct scatterlist sg[MAX_SKB_FRAGS + 2];
166 /* Min single buffer size for mergeable buffers case. */
167 unsigned int min_buf_len;
169 /* Name of this receive queue: input.$index */
172 struct xdp_rxq_info xdp_rxq;
175 /* This structure can contain rss message with maximum settings for indirection table and keysize
176 * Note, that default structure that describes RSS configuration virtio_net_rss_config
177 * contains same info but can't handle table values.
178 * In any case, structure would be passed to virtio hw through sg_buf split by parts
179 * because table sizes may be differ according to the device configuration.
181 #define VIRTIO_NET_RSS_MAX_KEY_SIZE 40
182 #define VIRTIO_NET_RSS_MAX_TABLE_LEN 128
183 struct virtio_net_ctrl_rss {
185 u16 indirection_table_mask;
186 u16 unclassified_queue;
187 u16 indirection_table[VIRTIO_NET_RSS_MAX_TABLE_LEN];
190 u8 key[VIRTIO_NET_RSS_MAX_KEY_SIZE];
193 /* Control VQ buffers: protected by the rtnl lock */
195 struct virtio_net_ctrl_hdr hdr;
196 virtio_net_ctrl_ack status;
197 struct virtio_net_ctrl_mq mq;
202 struct virtio_net_ctrl_rss rss;
205 struct virtnet_info {
206 struct virtio_device *vdev;
207 struct virtqueue *cvq;
208 struct net_device *dev;
209 struct send_queue *sq;
210 struct receive_queue *rq;
213 /* Max # of queue pairs supported by the device */
216 /* # of queue pairs currently used by the driver */
217 u16 curr_queue_pairs;
219 /* # of XDP queue pairs currently used by the driver */
222 /* xdp_queue_pairs may be 0, when xdp is already loaded. So add this. */
225 /* I like... big packets and I cannot lie! */
228 /* Host will merge rx buffers for big packets (shake it! shake it!) */
229 bool mergeable_rx_bufs;
231 /* Host supports rss and/or hash report */
233 bool has_rss_hash_report;
235 u16 rss_indir_table_size;
236 u32 rss_hash_types_supported;
237 u32 rss_hash_types_saved;
239 /* Has control virtqueue */
242 /* Host can handle any s/g split between our header and packet data */
245 /* Packet virtio header size */
248 /* Work struct for delayed refilling if we run low on memory. */
249 struct delayed_work refill;
251 /* Is delayed refill enabled? */
254 /* The lock to synchronize the access to refill_enabled */
255 spinlock_t refill_lock;
257 /* Work struct for config space updates */
258 struct work_struct config_work;
260 /* Does the affinity hint is set for virtqueues? */
261 bool affinity_hint_set;
263 /* CPU hotplug instances for online & dead */
264 struct hlist_node node;
265 struct hlist_node node_dead;
267 struct control_buf *ctrl;
269 /* Ethtool settings */
273 /* Interrupt coalescing settings */
279 unsigned long guest_offloads;
280 unsigned long guest_offloads_capable;
282 /* failover when STANDBY feature enabled */
283 struct failover *failover;
286 struct padded_vnet_hdr {
287 struct virtio_net_hdr_v1_hash hdr;
289 * hdr is in a separate sg buffer, and data sg buffer shares same page
290 * with this header sg. This padding makes next sg 16 byte aligned
296 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf);
297 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf);
299 static bool is_xdp_frame(void *ptr)
301 return (unsigned long)ptr & VIRTIO_XDP_FLAG;
304 static void *xdp_to_ptr(struct xdp_frame *ptr)
306 return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
309 static struct xdp_frame *ptr_to_xdp(void *ptr)
311 return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
314 /* Converting between virtqueue no. and kernel tx/rx queue no.
315 * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
317 static int vq2txq(struct virtqueue *vq)
319 return (vq->index - 1) / 2;
322 static int txq2vq(int txq)
327 static int vq2rxq(struct virtqueue *vq)
329 return vq->index / 2;
332 static int rxq2vq(int rxq)
337 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
339 return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
343 * private is used to chain pages for big packets, put the whole
344 * most recent used list in the beginning for reuse
346 static void give_pages(struct receive_queue *rq, struct page *page)
350 /* Find end of list, sew whole thing into vi->rq.pages. */
351 for (end = page; end->private; end = (struct page *)end->private);
352 end->private = (unsigned long)rq->pages;
356 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
358 struct page *p = rq->pages;
361 rq->pages = (struct page *)p->private;
362 /* clear private here, it is used to chain pages */
365 p = alloc_page(gfp_mask);
369 static void enable_delayed_refill(struct virtnet_info *vi)
371 spin_lock_bh(&vi->refill_lock);
372 vi->refill_enabled = true;
373 spin_unlock_bh(&vi->refill_lock);
376 static void disable_delayed_refill(struct virtnet_info *vi)
378 spin_lock_bh(&vi->refill_lock);
379 vi->refill_enabled = false;
380 spin_unlock_bh(&vi->refill_lock);
383 static void virtqueue_napi_schedule(struct napi_struct *napi,
384 struct virtqueue *vq)
386 if (napi_schedule_prep(napi)) {
387 virtqueue_disable_cb(vq);
388 __napi_schedule(napi);
392 static void virtqueue_napi_complete(struct napi_struct *napi,
393 struct virtqueue *vq, int processed)
397 opaque = virtqueue_enable_cb_prepare(vq);
398 if (napi_complete_done(napi, processed)) {
399 if (unlikely(virtqueue_poll(vq, opaque)))
400 virtqueue_napi_schedule(napi, vq);
402 virtqueue_disable_cb(vq);
406 static void skb_xmit_done(struct virtqueue *vq)
408 struct virtnet_info *vi = vq->vdev->priv;
409 struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
411 /* Suppress further interrupts. */
412 virtqueue_disable_cb(vq);
415 virtqueue_napi_schedule(napi, vq);
417 /* We were probably waiting for more output buffers. */
418 netif_wake_subqueue(vi->dev, vq2txq(vq));
421 #define MRG_CTX_HEADER_SHIFT 22
422 static void *mergeable_len_to_ctx(unsigned int truesize,
423 unsigned int headroom)
425 return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
428 static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
430 return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
433 static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
435 return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
438 /* Called from bottom half context */
439 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
440 struct receive_queue *rq,
441 struct page *page, unsigned int offset,
442 unsigned int len, unsigned int truesize,
443 bool hdr_valid, unsigned int metasize,
444 unsigned int headroom)
447 struct virtio_net_hdr_mrg_rxbuf *hdr;
448 unsigned int copy, hdr_len, hdr_padded_len;
449 struct page *page_to_free = NULL;
450 int tailroom, shinfo_size;
451 char *p, *hdr_p, *buf;
453 p = page_address(page) + offset;
456 hdr_len = vi->hdr_len;
457 if (vi->mergeable_rx_bufs)
458 hdr_padded_len = hdr_len;
460 hdr_padded_len = sizeof(struct padded_vnet_hdr);
462 /* If headroom is not 0, there is an offset between the beginning of the
463 * data and the allocated space, otherwise the data and the allocated
466 * Buffers with headroom use PAGE_SIZE as alloc size, see
467 * add_recvbuf_mergeable() + get_mergeable_buf_len()
469 truesize = headroom ? PAGE_SIZE : truesize;
470 tailroom = truesize - headroom;
474 offset += hdr_padded_len;
476 tailroom -= hdr_padded_len + len;
478 shinfo_size = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
480 /* copy small packet so we can reuse these pages */
481 if (!NET_IP_ALIGN && len > GOOD_COPY_LEN && tailroom >= shinfo_size) {
482 skb = build_skb(buf, truesize);
486 skb_reserve(skb, p - buf);
489 page = (struct page *)page->private;
491 give_pages(rq, page);
495 /* copy small packet so we can reuse these pages for small data */
496 skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
500 /* Copy all frame if it fits skb->head, otherwise
501 * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
503 if (len <= skb_tailroom(skb))
506 copy = ETH_HLEN + metasize;
507 skb_put_data(skb, p, copy);
512 if (vi->mergeable_rx_bufs) {
514 skb_add_rx_frag(skb, 0, page, offset, len, truesize);
521 * Verify that we can indeed put this data into a skb.
522 * This is here to handle cases when the device erroneously
523 * tries to receive more than is possible. This is usually
524 * the case of a broken device.
526 if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
527 net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
531 BUG_ON(offset >= PAGE_SIZE);
533 unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
534 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
535 frag_size, truesize);
537 page = (struct page *)page->private;
542 give_pages(rq, page);
545 /* hdr_valid means no XDP, so we can copy the vnet header */
547 hdr = skb_vnet_hdr(skb);
548 memcpy(hdr, hdr_p, hdr_len);
551 put_page(page_to_free);
554 __skb_pull(skb, metasize);
555 skb_metadata_set(skb, metasize);
561 static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
562 struct send_queue *sq,
563 struct xdp_frame *xdpf)
565 struct virtio_net_hdr_mrg_rxbuf *hdr;
568 if (unlikely(xdpf->headroom < vi->hdr_len))
571 /* Make room for virtqueue hdr (also change xdpf->headroom?) */
572 xdpf->data -= vi->hdr_len;
573 /* Zero header and leave csum up to XDP layers */
575 memset(hdr, 0, vi->hdr_len);
576 xdpf->len += vi->hdr_len;
578 sg_init_one(sq->sg, xdpf->data, xdpf->len);
580 err = virtqueue_add_outbuf(sq->vq, sq->sg, 1, xdp_to_ptr(xdpf),
583 return -ENOSPC; /* Caller handle free/refcnt */
588 /* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
589 * the current cpu, so it does not need to be locked.
591 * Here we use marco instead of inline functions because we have to deal with
592 * three issues at the same time: 1. the choice of sq. 2. judge and execute the
593 * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
594 * functions to perfectly solve these three problems at the same time.
596 #define virtnet_xdp_get_sq(vi) ({ \
597 int cpu = smp_processor_id(); \
598 struct netdev_queue *txq; \
599 typeof(vi) v = (vi); \
602 if (v->curr_queue_pairs > nr_cpu_ids) { \
603 qp = v->curr_queue_pairs - v->xdp_queue_pairs; \
605 txq = netdev_get_tx_queue(v->dev, qp); \
606 __netif_tx_acquire(txq); \
608 qp = cpu % v->curr_queue_pairs; \
609 txq = netdev_get_tx_queue(v->dev, qp); \
610 __netif_tx_lock(txq, cpu); \
615 #define virtnet_xdp_put_sq(vi, q) { \
616 struct netdev_queue *txq; \
617 typeof(vi) v = (vi); \
619 txq = netdev_get_tx_queue(v->dev, (q) - v->sq); \
620 if (v->curr_queue_pairs > nr_cpu_ids) \
621 __netif_tx_release(txq); \
623 __netif_tx_unlock(txq); \
626 static int virtnet_xdp_xmit(struct net_device *dev,
627 int n, struct xdp_frame **frames, u32 flags)
629 struct virtnet_info *vi = netdev_priv(dev);
630 struct receive_queue *rq = vi->rq;
631 struct bpf_prog *xdp_prog;
632 struct send_queue *sq;
642 /* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
643 * indicate XDP resources have been successfully allocated.
645 xdp_prog = rcu_access_pointer(rq->xdp_prog);
649 sq = virtnet_xdp_get_sq(vi);
651 if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
656 /* Free up any pending old buffers before queueing new ones. */
657 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
658 if (likely(is_xdp_frame(ptr))) {
659 struct xdp_frame *frame = ptr_to_xdp(ptr);
662 xdp_return_frame(frame);
664 struct sk_buff *skb = ptr;
667 napi_consume_skb(skb, false);
672 for (i = 0; i < n; i++) {
673 struct xdp_frame *xdpf = frames[i];
675 if (__virtnet_xdp_xmit_one(vi, sq, xdpf))
681 if (flags & XDP_XMIT_FLUSH) {
682 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
686 u64_stats_update_begin(&sq->stats.syncp);
687 sq->stats.bytes += bytes;
688 sq->stats.packets += packets;
689 sq->stats.xdp_tx += n;
690 sq->stats.xdp_tx_drops += n - nxmit;
691 sq->stats.kicks += kicks;
692 u64_stats_update_end(&sq->stats.syncp);
694 virtnet_xdp_put_sq(vi, sq);
698 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
700 return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
703 /* We copy the packet for XDP in the following cases:
705 * 1) Packet is scattered across multiple rx buffers.
706 * 2) Headroom space is insufficient.
708 * This is inefficient but it's a temporary condition that
709 * we hit right after XDP is enabled and until queue is refilled
710 * with large buffers with sufficient headroom - so it should affect
711 * at most queue size packets.
712 * Afterwards, the conditions to enable
713 * XDP should preclude the underlying device from sending packets
714 * across multiple buffers (num_buf > 1), and we make sure buffers
715 * have enough headroom.
717 static struct page *xdp_linearize_page(struct receive_queue *rq,
724 struct page *page = alloc_page(GFP_ATOMIC);
729 memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
733 int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
738 buf = virtqueue_get_buf(rq->vq, &buflen);
742 p = virt_to_head_page(buf);
743 off = buf - page_address(p);
745 /* guard against a misconfigured or uncooperative backend that
746 * is sending packet larger than the MTU.
748 if ((page_off + buflen + tailroom) > PAGE_SIZE) {
753 memcpy(page_address(page) + page_off,
754 page_address(p) + off, buflen);
759 /* Headroom does not contribute to packet length */
760 *len = page_off - VIRTIO_XDP_HEADROOM;
763 __free_pages(page, 0);
767 static struct sk_buff *receive_small(struct net_device *dev,
768 struct virtnet_info *vi,
769 struct receive_queue *rq,
770 void *buf, void *ctx,
772 unsigned int *xdp_xmit,
773 struct virtnet_rq_stats *stats)
776 struct bpf_prog *xdp_prog;
777 unsigned int xdp_headroom = (unsigned long)ctx;
778 unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
779 unsigned int headroom = vi->hdr_len + header_offset;
780 unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
781 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
782 struct page *page = virt_to_head_page(buf);
783 unsigned int delta = 0;
784 struct page *xdp_page;
786 unsigned int metasize = 0;
791 if (unlikely(len > GOOD_PACKET_LEN)) {
792 pr_debug("%s: rx error: len %u exceeds max size %d\n",
793 dev->name, len, GOOD_PACKET_LEN);
794 dev->stats.rx_length_errors++;
798 if (likely(!vi->xdp_enabled)) {
804 xdp_prog = rcu_dereference(rq->xdp_prog);
806 struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
807 struct xdp_frame *xdpf;
812 if (unlikely(hdr->hdr.gso_type))
815 if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
816 int offset = buf - page_address(page) + header_offset;
817 unsigned int tlen = len + vi->hdr_len;
820 xdp_headroom = virtnet_get_headroom(vi);
821 header_offset = VIRTNET_RX_PAD + xdp_headroom;
822 headroom = vi->hdr_len + header_offset;
823 buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
824 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
825 xdp_page = xdp_linearize_page(rq, &num_buf, page,
826 offset, header_offset,
831 buf = page_address(xdp_page);
836 xdp_init_buff(&xdp, buflen, &rq->xdp_rxq);
837 xdp_prepare_buff(&xdp, buf + VIRTNET_RX_PAD + vi->hdr_len,
838 xdp_headroom, len, true);
839 orig_data = xdp.data;
840 act = bpf_prog_run_xdp(xdp_prog, &xdp);
841 stats->xdp_packets++;
845 /* Recalculate length in case bpf program changed it */
846 delta = orig_data - xdp.data;
847 len = xdp.data_end - xdp.data;
848 metasize = xdp.data - xdp.data_meta;
852 xdpf = xdp_convert_buff_to_frame(&xdp);
855 err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
856 if (unlikely(!err)) {
857 xdp_return_frame_rx_napi(xdpf);
858 } else if (unlikely(err < 0)) {
859 trace_xdp_exception(vi->dev, xdp_prog, act);
862 *xdp_xmit |= VIRTIO_XDP_TX;
866 stats->xdp_redirects++;
867 err = xdp_do_redirect(dev, &xdp, xdp_prog);
870 *xdp_xmit |= VIRTIO_XDP_REDIR;
874 bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
877 trace_xdp_exception(vi->dev, xdp_prog, act);
886 skb = build_skb(buf, buflen);
889 skb_reserve(skb, headroom - delta);
892 buf += header_offset;
893 memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
894 } /* keep zeroed vnet hdr since XDP is loaded */
897 skb_metadata_set(skb, metasize);
911 static struct sk_buff *receive_big(struct net_device *dev,
912 struct virtnet_info *vi,
913 struct receive_queue *rq,
916 struct virtnet_rq_stats *stats)
918 struct page *page = buf;
919 struct sk_buff *skb =
920 page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, true, 0, 0);
922 stats->bytes += len - vi->hdr_len;
930 give_pages(rq, page);
934 static struct sk_buff *receive_mergeable(struct net_device *dev,
935 struct virtnet_info *vi,
936 struct receive_queue *rq,
940 unsigned int *xdp_xmit,
941 struct virtnet_rq_stats *stats)
943 struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
944 u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
945 struct page *page = virt_to_head_page(buf);
946 int offset = buf - page_address(page);
947 struct sk_buff *head_skb, *curr_skb;
948 struct bpf_prog *xdp_prog;
949 unsigned int truesize = mergeable_ctx_to_truesize(ctx);
950 unsigned int headroom = mergeable_ctx_to_headroom(ctx);
951 unsigned int metasize = 0;
952 unsigned int frame_sz;
956 stats->bytes += len - vi->hdr_len;
958 if (unlikely(len > truesize)) {
959 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
960 dev->name, len, (unsigned long)ctx);
961 dev->stats.rx_length_errors++;
965 if (likely(!vi->xdp_enabled)) {
971 xdp_prog = rcu_dereference(rq->xdp_prog);
973 struct xdp_frame *xdpf;
974 struct page *xdp_page;
979 /* Transient failure which in theory could occur if
980 * in-flight packets from before XDP was enabled reach
981 * the receive path after XDP is loaded.
983 if (unlikely(hdr->hdr.gso_type))
986 /* Buffers with headroom use PAGE_SIZE as alloc size,
987 * see add_recvbuf_mergeable() + get_mergeable_buf_len()
989 frame_sz = headroom ? PAGE_SIZE : truesize;
991 /* This happens when rx buffer size is underestimated
992 * or headroom is not enough because of the buffer
993 * was refilled before XDP is set. This should only
994 * happen for the first several packets, so we don't
995 * care much about its performance.
997 if (unlikely(num_buf > 1 ||
998 headroom < virtnet_get_headroom(vi))) {
999 /* linearize data for XDP */
1000 xdp_page = xdp_linearize_page(rq, &num_buf,
1002 VIRTIO_XDP_HEADROOM,
1004 frame_sz = PAGE_SIZE;
1008 offset = VIRTIO_XDP_HEADROOM;
1013 /* Allow consuming headroom but reserve enough space to push
1014 * the descriptor on if we get an XDP_TX return code.
1016 data = page_address(xdp_page) + offset;
1017 xdp_init_buff(&xdp, frame_sz - vi->hdr_len, &rq->xdp_rxq);
1018 xdp_prepare_buff(&xdp, data - VIRTIO_XDP_HEADROOM + vi->hdr_len,
1019 VIRTIO_XDP_HEADROOM, len - vi->hdr_len, true);
1021 act = bpf_prog_run_xdp(xdp_prog, &xdp);
1022 stats->xdp_packets++;
1026 metasize = xdp.data - xdp.data_meta;
1028 /* recalculate offset to account for any header
1029 * adjustments and minus the metasize to copy the
1030 * metadata in page_to_skb(). Note other cases do not
1031 * build an skb and avoid using offset
1033 offset = xdp.data - page_address(xdp_page) -
1034 vi->hdr_len - metasize;
1036 /* recalculate len if xdp.data, xdp.data_end or
1037 * xdp.data_meta were adjusted
1039 len = xdp.data_end - xdp.data + vi->hdr_len + metasize;
1041 /* recalculate headroom if xdp.data or xdp_data_meta
1042 * were adjusted, note that offset should always point
1043 * to the start of the reserved bytes for virtio_net
1044 * header which are followed by xdp.data, that means
1045 * that offset is equal to the headroom (when buf is
1046 * starting at the beginning of the page, otherwise
1047 * there is a base offset inside the page) but it's used
1048 * with a different starting point (buf start) than
1049 * xdp.data (buf start + vnet hdr size). If xdp.data or
1050 * data_meta were adjusted by the xdp prog then the
1051 * headroom size has changed and so has the offset, we
1052 * can use data_hard_start, which points at buf start +
1053 * vnet hdr size, to calculate the new headroom and use
1054 * it later to compute buf start in page_to_skb()
1056 headroom = xdp.data - xdp.data_hard_start - metasize;
1058 /* We can only create skb based on xdp_page. */
1059 if (unlikely(xdp_page != page)) {
1062 head_skb = page_to_skb(vi, rq, xdp_page, offset,
1063 len, PAGE_SIZE, false,
1071 xdpf = xdp_convert_buff_to_frame(&xdp);
1072 if (unlikely(!xdpf)) {
1073 if (unlikely(xdp_page != page))
1077 err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
1078 if (unlikely(!err)) {
1079 xdp_return_frame_rx_napi(xdpf);
1080 } else if (unlikely(err < 0)) {
1081 trace_xdp_exception(vi->dev, xdp_prog, act);
1082 if (unlikely(xdp_page != page))
1086 *xdp_xmit |= VIRTIO_XDP_TX;
1087 if (unlikely(xdp_page != page))
1092 stats->xdp_redirects++;
1093 err = xdp_do_redirect(dev, &xdp, xdp_prog);
1095 if (unlikely(xdp_page != page))
1099 *xdp_xmit |= VIRTIO_XDP_REDIR;
1100 if (unlikely(xdp_page != page))
1105 bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
1108 trace_xdp_exception(vi->dev, xdp_prog, act);
1111 if (unlikely(xdp_page != page))
1112 __free_pages(xdp_page, 0);
1119 head_skb = page_to_skb(vi, rq, page, offset, len, truesize, !xdp_prog,
1120 metasize, headroom);
1121 curr_skb = head_skb;
1123 if (unlikely(!curr_skb))
1128 buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1129 if (unlikely(!buf)) {
1130 pr_debug("%s: rx error: %d buffers out of %d missing\n",
1132 virtio16_to_cpu(vi->vdev,
1134 dev->stats.rx_length_errors++;
1138 stats->bytes += len;
1139 page = virt_to_head_page(buf);
1141 truesize = mergeable_ctx_to_truesize(ctx);
1142 if (unlikely(len > truesize)) {
1143 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1144 dev->name, len, (unsigned long)ctx);
1145 dev->stats.rx_length_errors++;
1149 num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1150 if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1151 struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1153 if (unlikely(!nskb))
1155 if (curr_skb == head_skb)
1156 skb_shinfo(curr_skb)->frag_list = nskb;
1158 curr_skb->next = nskb;
1160 head_skb->truesize += nskb->truesize;
1163 if (curr_skb != head_skb) {
1164 head_skb->data_len += len;
1165 head_skb->len += len;
1166 head_skb->truesize += truesize;
1168 offset = buf - page_address(page);
1169 if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1171 skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1174 skb_add_rx_frag(curr_skb, num_skb_frags, page,
1175 offset, len, truesize);
1179 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1187 while (num_buf-- > 1) {
1188 buf = virtqueue_get_buf(rq->vq, &len);
1189 if (unlikely(!buf)) {
1190 pr_debug("%s: rx error: %d buffers missing\n",
1191 dev->name, num_buf);
1192 dev->stats.rx_length_errors++;
1195 stats->bytes += len;
1196 page = virt_to_head_page(buf);
1201 dev_kfree_skb(head_skb);
1206 static void virtio_skb_set_hash(const struct virtio_net_hdr_v1_hash *hdr_hash,
1207 struct sk_buff *skb)
1209 enum pkt_hash_types rss_hash_type;
1211 if (!hdr_hash || !skb)
1214 switch (__le16_to_cpu(hdr_hash->hash_report)) {
1215 case VIRTIO_NET_HASH_REPORT_TCPv4:
1216 case VIRTIO_NET_HASH_REPORT_UDPv4:
1217 case VIRTIO_NET_HASH_REPORT_TCPv6:
1218 case VIRTIO_NET_HASH_REPORT_UDPv6:
1219 case VIRTIO_NET_HASH_REPORT_TCPv6_EX:
1220 case VIRTIO_NET_HASH_REPORT_UDPv6_EX:
1221 rss_hash_type = PKT_HASH_TYPE_L4;
1223 case VIRTIO_NET_HASH_REPORT_IPv4:
1224 case VIRTIO_NET_HASH_REPORT_IPv6:
1225 case VIRTIO_NET_HASH_REPORT_IPv6_EX:
1226 rss_hash_type = PKT_HASH_TYPE_L3;
1228 case VIRTIO_NET_HASH_REPORT_NONE:
1230 rss_hash_type = PKT_HASH_TYPE_NONE;
1232 skb_set_hash(skb, __le32_to_cpu(hdr_hash->hash_value), rss_hash_type);
1235 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1236 void *buf, unsigned int len, void **ctx,
1237 unsigned int *xdp_xmit,
1238 struct virtnet_rq_stats *stats)
1240 struct net_device *dev = vi->dev;
1241 struct sk_buff *skb;
1242 struct virtio_net_hdr_mrg_rxbuf *hdr;
1244 if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1245 pr_debug("%s: short packet %i\n", dev->name, len);
1246 dev->stats.rx_length_errors++;
1247 if (vi->mergeable_rx_bufs) {
1248 put_page(virt_to_head_page(buf));
1249 } else if (vi->big_packets) {
1250 give_pages(rq, buf);
1252 put_page(virt_to_head_page(buf));
1257 if (vi->mergeable_rx_bufs)
1258 skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1260 else if (vi->big_packets)
1261 skb = receive_big(dev, vi, rq, buf, len, stats);
1263 skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1268 hdr = skb_vnet_hdr(skb);
1269 if (dev->features & NETIF_F_RXHASH && vi->has_rss_hash_report)
1270 virtio_skb_set_hash((const struct virtio_net_hdr_v1_hash *)hdr, skb);
1272 if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
1273 skb->ip_summed = CHECKSUM_UNNECESSARY;
1275 if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1276 virtio_is_little_endian(vi->vdev))) {
1277 net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1278 dev->name, hdr->hdr.gso_type,
1283 skb_record_rx_queue(skb, vq2rxq(rq->vq));
1284 skb->protocol = eth_type_trans(skb, dev);
1285 pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1286 ntohs(skb->protocol), skb->len, skb->pkt_type);
1288 napi_gro_receive(&rq->napi, skb);
1292 dev->stats.rx_frame_errors++;
1296 /* Unlike mergeable buffers, all buffers are allocated to the
1297 * same size, except for the headroom. For this reason we do
1298 * not need to use mergeable_len_to_ctx here - it is enough
1299 * to store the headroom as the context ignoring the truesize.
1301 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1304 struct page_frag *alloc_frag = &rq->alloc_frag;
1306 unsigned int xdp_headroom = virtnet_get_headroom(vi);
1307 void *ctx = (void *)(unsigned long)xdp_headroom;
1308 int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1311 len = SKB_DATA_ALIGN(len) +
1312 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1313 if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
1316 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1317 get_page(alloc_frag->page);
1318 alloc_frag->offset += len;
1319 sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1320 vi->hdr_len + GOOD_PACKET_LEN);
1321 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1323 put_page(virt_to_head_page(buf));
1327 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1330 struct page *first, *list = NULL;
1334 sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
1336 /* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
1337 for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
1338 first = get_a_page(rq, gfp);
1341 give_pages(rq, list);
1344 sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1346 /* chain new page in list head to match sg */
1347 first->private = (unsigned long)list;
1351 first = get_a_page(rq, gfp);
1353 give_pages(rq, list);
1356 p = page_address(first);
1358 /* rq->sg[0], rq->sg[1] share the same page */
1359 /* a separated rq->sg[0] for header - required in case !any_header_sg */
1360 sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1362 /* rq->sg[1] for data packet, from offset */
1363 offset = sizeof(struct padded_vnet_hdr);
1364 sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1366 /* chain first in list head */
1367 first->private = (unsigned long)list;
1368 err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
1371 give_pages(rq, first);
1376 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1377 struct ewma_pkt_len *avg_pkt_len,
1380 struct virtnet_info *vi = rq->vq->vdev->priv;
1381 const size_t hdr_len = vi->hdr_len;
1385 return PAGE_SIZE - room;
1387 len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1388 rq->min_buf_len, PAGE_SIZE - hdr_len);
1390 return ALIGN(len, L1_CACHE_BYTES);
1393 static int add_recvbuf_mergeable(struct virtnet_info *vi,
1394 struct receive_queue *rq, gfp_t gfp)
1396 struct page_frag *alloc_frag = &rq->alloc_frag;
1397 unsigned int headroom = virtnet_get_headroom(vi);
1398 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1399 unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1403 unsigned int len, hole;
1405 /* Extra tailroom is needed to satisfy XDP's assumption. This
1406 * means rx frags coalescing won't work, but consider we've
1407 * disabled GSO for XDP, it won't be a big issue.
1409 len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1410 if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
1413 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1414 buf += headroom; /* advance address leaving hole at front of pkt */
1415 get_page(alloc_frag->page);
1416 alloc_frag->offset += len + room;
1417 hole = alloc_frag->size - alloc_frag->offset;
1418 if (hole < len + room) {
1419 /* To avoid internal fragmentation, if there is very likely not
1420 * enough space for another buffer, add the remaining space to
1421 * the current buffer.
1424 alloc_frag->offset += hole;
1427 sg_init_one(rq->sg, buf, len);
1428 ctx = mergeable_len_to_ctx(len, headroom);
1429 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1431 put_page(virt_to_head_page(buf));
1437 * Returns false if we couldn't fill entirely (OOM).
1439 * Normally run in the receive path, but can also be run from ndo_open
1440 * before we're receiving packets, or from refill_work which is
1441 * careful to disable receiving (using napi_disable).
1443 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1450 if (vi->mergeable_rx_bufs)
1451 err = add_recvbuf_mergeable(vi, rq, gfp);
1452 else if (vi->big_packets)
1453 err = add_recvbuf_big(vi, rq, gfp);
1455 err = add_recvbuf_small(vi, rq, gfp);
1457 oom = err == -ENOMEM;
1460 } while (rq->vq->num_free);
1461 if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
1462 unsigned long flags;
1464 flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1466 u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1472 static void skb_recv_done(struct virtqueue *rvq)
1474 struct virtnet_info *vi = rvq->vdev->priv;
1475 struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1477 virtqueue_napi_schedule(&rq->napi, rvq);
1480 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
1484 /* If all buffers were filled by other side before we napi_enabled, we
1485 * won't get another interrupt, so process any outstanding packets now.
1486 * Call local_bh_enable after to trigger softIRQ processing.
1489 virtqueue_napi_schedule(napi, vq);
1493 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1494 struct virtqueue *vq,
1495 struct napi_struct *napi)
1500 /* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1501 * enable the feature if this is likely affine with the transmit path.
1503 if (!vi->affinity_hint_set) {
1508 return virtnet_napi_enable(vq, napi);
1511 static void virtnet_napi_tx_disable(struct napi_struct *napi)
1517 static void refill_work(struct work_struct *work)
1519 struct virtnet_info *vi =
1520 container_of(work, struct virtnet_info, refill.work);
1524 for (i = 0; i < vi->curr_queue_pairs; i++) {
1525 struct receive_queue *rq = &vi->rq[i];
1527 napi_disable(&rq->napi);
1528 still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1529 virtnet_napi_enable(rq->vq, &rq->napi);
1531 /* In theory, this can happen: if we don't get any buffers in
1532 * we will *never* try to fill again.
1535 schedule_delayed_work(&vi->refill, HZ/2);
1539 static int virtnet_receive(struct receive_queue *rq, int budget,
1540 unsigned int *xdp_xmit)
1542 struct virtnet_info *vi = rq->vq->vdev->priv;
1543 struct virtnet_rq_stats stats = {};
1548 if (!vi->big_packets || vi->mergeable_rx_bufs) {
1551 while (stats.packets < budget &&
1552 (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1553 receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1557 while (stats.packets < budget &&
1558 (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1559 receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1564 if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1565 if (!try_fill_recv(vi, rq, GFP_ATOMIC)) {
1566 spin_lock(&vi->refill_lock);
1567 if (vi->refill_enabled)
1568 schedule_delayed_work(&vi->refill, 0);
1569 spin_unlock(&vi->refill_lock);
1573 u64_stats_update_begin(&rq->stats.syncp);
1574 for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1575 size_t offset = virtnet_rq_stats_desc[i].offset;
1578 item = (u64 *)((u8 *)&rq->stats + offset);
1579 *item += *(u64 *)((u8 *)&stats + offset);
1581 u64_stats_update_end(&rq->stats.syncp);
1583 return stats.packets;
1586 static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
1589 unsigned int packets = 0;
1590 unsigned int bytes = 0;
1593 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
1594 if (likely(!is_xdp_frame(ptr))) {
1595 struct sk_buff *skb = ptr;
1597 pr_debug("Sent skb %p\n", skb);
1600 napi_consume_skb(skb, in_napi);
1602 struct xdp_frame *frame = ptr_to_xdp(ptr);
1604 bytes += frame->len;
1605 xdp_return_frame(frame);
1610 /* Avoid overhead when no packets have been processed
1611 * happens when called speculatively from start_xmit.
1616 u64_stats_update_begin(&sq->stats.syncp);
1617 sq->stats.bytes += bytes;
1618 sq->stats.packets += packets;
1619 u64_stats_update_end(&sq->stats.syncp);
1622 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
1624 if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
1626 else if (q < vi->curr_queue_pairs)
1632 static void virtnet_poll_cleantx(struct receive_queue *rq)
1634 struct virtnet_info *vi = rq->vq->vdev->priv;
1635 unsigned int index = vq2rxq(rq->vq);
1636 struct send_queue *sq = &vi->sq[index];
1637 struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
1639 if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
1642 if (__netif_tx_trylock(txq)) {
1644 __netif_tx_unlock(txq);
1649 virtqueue_disable_cb(sq->vq);
1650 free_old_xmit_skbs(sq, true);
1651 } while (unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1653 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1654 netif_tx_wake_queue(txq);
1656 __netif_tx_unlock(txq);
1660 static int virtnet_poll(struct napi_struct *napi, int budget)
1662 struct receive_queue *rq =
1663 container_of(napi, struct receive_queue, napi);
1664 struct virtnet_info *vi = rq->vq->vdev->priv;
1665 struct send_queue *sq;
1666 unsigned int received;
1667 unsigned int xdp_xmit = 0;
1669 virtnet_poll_cleantx(rq);
1671 received = virtnet_receive(rq, budget, &xdp_xmit);
1673 /* Out of packets? */
1674 if (received < budget)
1675 virtqueue_napi_complete(napi, rq->vq, received);
1677 if (xdp_xmit & VIRTIO_XDP_REDIR)
1680 if (xdp_xmit & VIRTIO_XDP_TX) {
1681 sq = virtnet_xdp_get_sq(vi);
1682 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1683 u64_stats_update_begin(&sq->stats.syncp);
1685 u64_stats_update_end(&sq->stats.syncp);
1687 virtnet_xdp_put_sq(vi, sq);
1693 static int virtnet_open(struct net_device *dev)
1695 struct virtnet_info *vi = netdev_priv(dev);
1698 enable_delayed_refill(vi);
1700 for (i = 0; i < vi->max_queue_pairs; i++) {
1701 if (i < vi->curr_queue_pairs)
1702 /* Make sure we have some buffers: if oom use wq. */
1703 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1704 schedule_delayed_work(&vi->refill, 0);
1706 err = xdp_rxq_info_reg(&vi->rq[i].xdp_rxq, dev, i, vi->rq[i].napi.napi_id);
1710 err = xdp_rxq_info_reg_mem_model(&vi->rq[i].xdp_rxq,
1711 MEM_TYPE_PAGE_SHARED, NULL);
1713 xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1717 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1718 virtnet_napi_tx_enable(vi, vi->sq[i].vq, &vi->sq[i].napi);
1724 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1726 struct send_queue *sq = container_of(napi, struct send_queue, napi);
1727 struct virtnet_info *vi = sq->vq->vdev->priv;
1728 unsigned int index = vq2txq(sq->vq);
1729 struct netdev_queue *txq;
1733 if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
1734 /* We don't need to enable cb for XDP */
1735 napi_complete_done(napi, 0);
1739 txq = netdev_get_tx_queue(vi->dev, index);
1740 __netif_tx_lock(txq, raw_smp_processor_id());
1741 virtqueue_disable_cb(sq->vq);
1742 free_old_xmit_skbs(sq, true);
1744 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1745 netif_tx_wake_queue(txq);
1747 opaque = virtqueue_enable_cb_prepare(sq->vq);
1749 done = napi_complete_done(napi, 0);
1752 virtqueue_disable_cb(sq->vq);
1754 __netif_tx_unlock(txq);
1757 if (unlikely(virtqueue_poll(sq->vq, opaque))) {
1758 if (napi_schedule_prep(napi)) {
1759 __netif_tx_lock(txq, raw_smp_processor_id());
1760 virtqueue_disable_cb(sq->vq);
1761 __netif_tx_unlock(txq);
1762 __napi_schedule(napi);
1770 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1772 struct virtio_net_hdr_mrg_rxbuf *hdr;
1773 const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1774 struct virtnet_info *vi = sq->vq->vdev->priv;
1776 unsigned hdr_len = vi->hdr_len;
1779 pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1781 can_push = vi->any_header_sg &&
1782 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1783 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1784 /* Even if we can, don't push here yet as this would skew
1785 * csum_start offset below. */
1787 hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1789 hdr = skb_vnet_hdr(skb);
1791 if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1792 virtio_is_little_endian(vi->vdev), false,
1796 if (vi->mergeable_rx_bufs)
1797 hdr->num_buffers = 0;
1799 sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1801 __skb_push(skb, hdr_len);
1802 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1803 if (unlikely(num_sg < 0))
1805 /* Pull header back to avoid skew in tx bytes calculations. */
1806 __skb_pull(skb, hdr_len);
1808 sg_set_buf(sq->sg, hdr, hdr_len);
1809 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
1810 if (unlikely(num_sg < 0))
1814 return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1817 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1819 struct virtnet_info *vi = netdev_priv(dev);
1820 int qnum = skb_get_queue_mapping(skb);
1821 struct send_queue *sq = &vi->sq[qnum];
1823 struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1824 bool kick = !netdev_xmit_more();
1825 bool use_napi = sq->napi.weight;
1827 /* Free up any pending old buffers before queueing new ones. */
1830 virtqueue_disable_cb(sq->vq);
1832 free_old_xmit_skbs(sq, false);
1834 } while (use_napi && kick &&
1835 unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1837 /* timestamp packet in software */
1838 skb_tx_timestamp(skb);
1840 /* Try to transmit */
1841 err = xmit_skb(sq, skb);
1843 /* This should not happen! */
1844 if (unlikely(err)) {
1845 dev->stats.tx_fifo_errors++;
1846 if (net_ratelimit())
1848 "Unexpected TXQ (%d) queue failure: %d\n",
1850 dev->stats.tx_dropped++;
1851 dev_kfree_skb_any(skb);
1852 return NETDEV_TX_OK;
1855 /* Don't wait up for transmitted skbs to be freed. */
1861 /* If running out of space, stop queue to avoid getting packets that we
1862 * are then unable to transmit.
1863 * An alternative would be to force queuing layer to requeue the skb by
1864 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
1865 * returned in a normal path of operation: it means that driver is not
1866 * maintaining the TX queue stop/start state properly, and causes
1867 * the stack to do a non-trivial amount of useless work.
1868 * Since most packets only take 1 or 2 ring slots, stopping the queue
1869 * early means 16 slots are typically wasted.
1871 if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1872 netif_stop_subqueue(dev, qnum);
1874 unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1875 /* More just got used, free them then recheck. */
1876 free_old_xmit_skbs(sq, false);
1877 if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1878 netif_start_subqueue(dev, qnum);
1879 virtqueue_disable_cb(sq->vq);
1884 if (kick || netif_xmit_stopped(txq)) {
1885 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1886 u64_stats_update_begin(&sq->stats.syncp);
1888 u64_stats_update_end(&sq->stats.syncp);
1892 return NETDEV_TX_OK;
1895 static int virtnet_rx_resize(struct virtnet_info *vi,
1896 struct receive_queue *rq, u32 ring_num)
1898 bool running = netif_running(vi->dev);
1901 qindex = rq - vi->rq;
1904 napi_disable(&rq->napi);
1906 err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_free_unused_buf);
1908 netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
1910 if (!try_fill_recv(vi, rq, GFP_KERNEL))
1911 schedule_delayed_work(&vi->refill, 0);
1914 virtnet_napi_enable(rq->vq, &rq->napi);
1918 static int virtnet_tx_resize(struct virtnet_info *vi,
1919 struct send_queue *sq, u32 ring_num)
1921 bool running = netif_running(vi->dev);
1922 struct netdev_queue *txq;
1925 qindex = sq - vi->sq;
1928 virtnet_napi_tx_disable(&sq->napi);
1930 txq = netdev_get_tx_queue(vi->dev, qindex);
1932 /* 1. wait all ximt complete
1933 * 2. fix the race of netif_stop_subqueue() vs netif_start_subqueue()
1935 __netif_tx_lock_bh(txq);
1937 /* Prevent rx poll from accessing sq. */
1940 /* Prevent the upper layer from trying to send packets. */
1941 netif_stop_subqueue(vi->dev, qindex);
1943 __netif_tx_unlock_bh(txq);
1945 err = virtqueue_resize(sq->vq, ring_num, virtnet_sq_free_unused_buf);
1947 netdev_err(vi->dev, "resize tx fail: tx queue index: %d err: %d\n", qindex, err);
1949 __netif_tx_lock_bh(txq);
1951 netif_tx_wake_queue(txq);
1952 __netif_tx_unlock_bh(txq);
1955 virtnet_napi_tx_enable(vi, sq->vq, &sq->napi);
1960 * Send command via the control virtqueue and check status. Commands
1961 * supported by the hypervisor, as indicated by feature bits, should
1962 * never fail unless improperly formatted.
1964 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1965 struct scatterlist *out)
1967 struct scatterlist *sgs[4], hdr, stat;
1968 unsigned out_num = 0, tmp;
1971 /* Caller should know better */
1972 BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1974 vi->ctrl->status = ~0;
1975 vi->ctrl->hdr.class = class;
1976 vi->ctrl->hdr.cmd = cmd;
1978 sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
1979 sgs[out_num++] = &hdr;
1982 sgs[out_num++] = out;
1984 /* Add return status. */
1985 sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
1986 sgs[out_num] = &stat;
1988 BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1989 ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1991 dev_warn(&vi->vdev->dev,
1992 "Failed to add sgs for command vq: %d\n.", ret);
1996 if (unlikely(!virtqueue_kick(vi->cvq)))
1997 return vi->ctrl->status == VIRTIO_NET_OK;
1999 /* Spin for a response, the kick causes an ioport write, trapping
2000 * into the hypervisor, so the request should be handled immediately.
2002 while (!virtqueue_get_buf(vi->cvq, &tmp) &&
2003 !virtqueue_is_broken(vi->cvq))
2006 return vi->ctrl->status == VIRTIO_NET_OK;
2009 static int virtnet_set_mac_address(struct net_device *dev, void *p)
2011 struct virtnet_info *vi = netdev_priv(dev);
2012 struct virtio_device *vdev = vi->vdev;
2014 struct sockaddr *addr;
2015 struct scatterlist sg;
2017 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2020 addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
2024 ret = eth_prepare_mac_addr_change(dev, addr);
2028 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
2029 sg_init_one(&sg, addr->sa_data, dev->addr_len);
2030 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2031 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
2032 dev_warn(&vdev->dev,
2033 "Failed to set mac address by vq command.\n");
2037 } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
2038 !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2041 /* Naturally, this has an atomicity problem. */
2042 for (i = 0; i < dev->addr_len; i++)
2043 virtio_cwrite8(vdev,
2044 offsetof(struct virtio_net_config, mac) +
2045 i, addr->sa_data[i]);
2048 eth_commit_mac_addr_change(dev, p);
2056 static void virtnet_stats(struct net_device *dev,
2057 struct rtnl_link_stats64 *tot)
2059 struct virtnet_info *vi = netdev_priv(dev);
2063 for (i = 0; i < vi->max_queue_pairs; i++) {
2064 u64 tpackets, tbytes, terrors, rpackets, rbytes, rdrops;
2065 struct receive_queue *rq = &vi->rq[i];
2066 struct send_queue *sq = &vi->sq[i];
2069 start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2070 tpackets = sq->stats.packets;
2071 tbytes = sq->stats.bytes;
2072 terrors = sq->stats.tx_timeouts;
2073 } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2076 start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2077 rpackets = rq->stats.packets;
2078 rbytes = rq->stats.bytes;
2079 rdrops = rq->stats.drops;
2080 } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2082 tot->rx_packets += rpackets;
2083 tot->tx_packets += tpackets;
2084 tot->rx_bytes += rbytes;
2085 tot->tx_bytes += tbytes;
2086 tot->rx_dropped += rdrops;
2087 tot->tx_errors += terrors;
2090 tot->tx_dropped = dev->stats.tx_dropped;
2091 tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
2092 tot->rx_length_errors = dev->stats.rx_length_errors;
2093 tot->rx_frame_errors = dev->stats.rx_frame_errors;
2096 static void virtnet_ack_link_announce(struct virtnet_info *vi)
2099 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
2100 VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
2101 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
2105 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2107 struct scatterlist sg;
2108 struct net_device *dev = vi->dev;
2110 if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
2113 vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
2114 sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
2116 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2117 VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
2118 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
2122 vi->curr_queue_pairs = queue_pairs;
2123 /* virtnet_open() will refill when device is going to up. */
2124 if (dev->flags & IFF_UP)
2125 schedule_delayed_work(&vi->refill, 0);
2131 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2136 err = _virtnet_set_queues(vi, queue_pairs);
2141 static int virtnet_close(struct net_device *dev)
2143 struct virtnet_info *vi = netdev_priv(dev);
2146 /* Make sure NAPI doesn't schedule refill work */
2147 disable_delayed_refill(vi);
2148 /* Make sure refill_work doesn't re-enable napi! */
2149 cancel_delayed_work_sync(&vi->refill);
2151 for (i = 0; i < vi->max_queue_pairs; i++) {
2152 xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
2153 napi_disable(&vi->rq[i].napi);
2154 virtnet_napi_tx_disable(&vi->sq[i].napi);
2160 static void virtnet_set_rx_mode(struct net_device *dev)
2162 struct virtnet_info *vi = netdev_priv(dev);
2163 struct scatterlist sg[2];
2164 struct virtio_net_ctrl_mac *mac_data;
2165 struct netdev_hw_addr *ha;
2171 /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
2172 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
2175 vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
2176 vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
2178 sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
2180 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2181 VIRTIO_NET_CTRL_RX_PROMISC, sg))
2182 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
2183 vi->ctrl->promisc ? "en" : "dis");
2185 sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
2187 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2188 VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
2189 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
2190 vi->ctrl->allmulti ? "en" : "dis");
2192 uc_count = netdev_uc_count(dev);
2193 mc_count = netdev_mc_count(dev);
2194 /* MAC filter - use one buffer for both lists */
2195 buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
2196 (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
2201 sg_init_table(sg, 2);
2203 /* Store the unicast list and count in the front of the buffer */
2204 mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2206 netdev_for_each_uc_addr(ha, dev)
2207 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2209 sg_set_buf(&sg[0], mac_data,
2210 sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2212 /* multicast list and count fill the end */
2213 mac_data = (void *)&mac_data->macs[uc_count][0];
2215 mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2217 netdev_for_each_mc_addr(ha, dev)
2218 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2220 sg_set_buf(&sg[1], mac_data,
2221 sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2223 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2224 VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2225 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2230 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
2231 __be16 proto, u16 vid)
2233 struct virtnet_info *vi = netdev_priv(dev);
2234 struct scatterlist sg;
2236 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2237 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2239 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2240 VIRTIO_NET_CTRL_VLAN_ADD, &sg))
2241 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
2245 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
2246 __be16 proto, u16 vid)
2248 struct virtnet_info *vi = netdev_priv(dev);
2249 struct scatterlist sg;
2251 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2252 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2254 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2255 VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2256 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2260 static void virtnet_clean_affinity(struct virtnet_info *vi)
2264 if (vi->affinity_hint_set) {
2265 for (i = 0; i < vi->max_queue_pairs; i++) {
2266 virtqueue_set_affinity(vi->rq[i].vq, NULL);
2267 virtqueue_set_affinity(vi->sq[i].vq, NULL);
2270 vi->affinity_hint_set = false;
2274 static void virtnet_set_affinity(struct virtnet_info *vi)
2283 if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2284 virtnet_clean_affinity(vi);
2288 num_cpu = num_online_cpus();
2289 stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2290 stragglers = num_cpu >= vi->curr_queue_pairs ?
2291 num_cpu % vi->curr_queue_pairs :
2293 cpu = cpumask_first(cpu_online_mask);
2295 for (i = 0; i < vi->curr_queue_pairs; i++) {
2296 group_size = stride + (i < stragglers ? 1 : 0);
2298 for (j = 0; j < group_size; j++) {
2299 cpumask_set_cpu(cpu, mask);
2300 cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2303 virtqueue_set_affinity(vi->rq[i].vq, mask);
2304 virtqueue_set_affinity(vi->sq[i].vq, mask);
2305 __netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2306 cpumask_clear(mask);
2309 vi->affinity_hint_set = true;
2310 free_cpumask_var(mask);
2313 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2315 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2317 virtnet_set_affinity(vi);
2321 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2323 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2325 virtnet_set_affinity(vi);
2329 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2331 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2334 virtnet_clean_affinity(vi);
2338 static enum cpuhp_state virtionet_online;
2340 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2344 ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2347 ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2351 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2355 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2357 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2358 cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2362 static void virtnet_get_ringparam(struct net_device *dev,
2363 struct ethtool_ringparam *ring,
2364 struct kernel_ethtool_ringparam *kernel_ring,
2365 struct netlink_ext_ack *extack)
2367 struct virtnet_info *vi = netdev_priv(dev);
2369 ring->rx_max_pending = vi->rq[0].vq->num_max;
2370 ring->tx_max_pending = vi->sq[0].vq->num_max;
2371 ring->rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2372 ring->tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2375 static int virtnet_set_ringparam(struct net_device *dev,
2376 struct ethtool_ringparam *ring,
2377 struct kernel_ethtool_ringparam *kernel_ring,
2378 struct netlink_ext_ack *extack)
2380 struct virtnet_info *vi = netdev_priv(dev);
2381 u32 rx_pending, tx_pending;
2382 struct receive_queue *rq;
2383 struct send_queue *sq;
2386 if (ring->rx_mini_pending || ring->rx_jumbo_pending)
2389 rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2390 tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2392 if (ring->rx_pending == rx_pending &&
2393 ring->tx_pending == tx_pending)
2396 if (ring->rx_pending > vi->rq[0].vq->num_max)
2399 if (ring->tx_pending > vi->sq[0].vq->num_max)
2402 for (i = 0; i < vi->max_queue_pairs; i++) {
2406 if (ring->tx_pending != tx_pending) {
2407 err = virtnet_tx_resize(vi, sq, ring->tx_pending);
2412 if (ring->rx_pending != rx_pending) {
2413 err = virtnet_rx_resize(vi, rq, ring->rx_pending);
2422 static bool virtnet_commit_rss_command(struct virtnet_info *vi)
2424 struct net_device *dev = vi->dev;
2425 struct scatterlist sgs[4];
2426 unsigned int sg_buf_size;
2429 sg_init_table(sgs, 4);
2431 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, indirection_table);
2432 sg_set_buf(&sgs[0], &vi->ctrl->rss, sg_buf_size);
2434 sg_buf_size = sizeof(uint16_t) * (vi->ctrl->rss.indirection_table_mask + 1);
2435 sg_set_buf(&sgs[1], vi->ctrl->rss.indirection_table, sg_buf_size);
2437 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, key)
2438 - offsetof(struct virtio_net_ctrl_rss, max_tx_vq);
2439 sg_set_buf(&sgs[2], &vi->ctrl->rss.max_tx_vq, sg_buf_size);
2441 sg_buf_size = vi->rss_key_size;
2442 sg_set_buf(&sgs[3], vi->ctrl->rss.key, sg_buf_size);
2444 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2445 vi->has_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG
2446 : VIRTIO_NET_CTRL_MQ_HASH_CONFIG, sgs)) {
2447 dev_warn(&dev->dev, "VIRTIONET issue with committing RSS sgs\n");
2453 static void virtnet_init_default_rss(struct virtnet_info *vi)
2458 vi->ctrl->rss.hash_types = vi->rss_hash_types_supported;
2459 vi->rss_hash_types_saved = vi->rss_hash_types_supported;
2460 vi->ctrl->rss.indirection_table_mask = vi->rss_indir_table_size
2461 ? vi->rss_indir_table_size - 1 : 0;
2462 vi->ctrl->rss.unclassified_queue = 0;
2464 for (; i < vi->rss_indir_table_size; ++i) {
2465 indir_val = ethtool_rxfh_indir_default(i, vi->curr_queue_pairs);
2466 vi->ctrl->rss.indirection_table[i] = indir_val;
2469 vi->ctrl->rss.max_tx_vq = vi->curr_queue_pairs;
2470 vi->ctrl->rss.hash_key_length = vi->rss_key_size;
2472 netdev_rss_key_fill(vi->ctrl->rss.key, vi->rss_key_size);
2475 static void virtnet_get_hashflow(const struct virtnet_info *vi, struct ethtool_rxnfc *info)
2478 switch (info->flow_type) {
2480 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
2481 info->data = RXH_IP_SRC | RXH_IP_DST |
2482 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2483 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2484 info->data = RXH_IP_SRC | RXH_IP_DST;
2488 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
2489 info->data = RXH_IP_SRC | RXH_IP_DST |
2490 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2491 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2492 info->data = RXH_IP_SRC | RXH_IP_DST;
2496 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
2497 info->data = RXH_IP_SRC | RXH_IP_DST |
2498 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2499 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2500 info->data = RXH_IP_SRC | RXH_IP_DST;
2504 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
2505 info->data = RXH_IP_SRC | RXH_IP_DST |
2506 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2507 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2508 info->data = RXH_IP_SRC | RXH_IP_DST;
2512 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4)
2513 info->data = RXH_IP_SRC | RXH_IP_DST;
2517 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6)
2518 info->data = RXH_IP_SRC | RXH_IP_DST;
2527 static bool virtnet_set_hashflow(struct virtnet_info *vi, struct ethtool_rxnfc *info)
2529 u32 new_hashtypes = vi->rss_hash_types_saved;
2530 bool is_disable = info->data & RXH_DISCARD;
2531 bool is_l4 = info->data == (RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3);
2533 /* supports only 'sd', 'sdfn' and 'r' */
2534 if (!((info->data == (RXH_IP_SRC | RXH_IP_DST)) | is_l4 | is_disable))
2537 switch (info->flow_type) {
2539 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_TCPv4);
2541 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2542 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0);
2545 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_UDPv4);
2547 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2548 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0);
2551 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2553 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2556 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_TCPv6);
2558 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2559 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0);
2562 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_UDPv6);
2564 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2565 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0);
2568 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2570 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2573 /* unsupported flow */
2577 /* if unsupported hashtype was set */
2578 if (new_hashtypes != (new_hashtypes & vi->rss_hash_types_supported))
2581 if (new_hashtypes != vi->rss_hash_types_saved) {
2582 vi->rss_hash_types_saved = new_hashtypes;
2583 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
2584 if (vi->dev->features & NETIF_F_RXHASH)
2585 return virtnet_commit_rss_command(vi);
2591 static void virtnet_get_drvinfo(struct net_device *dev,
2592 struct ethtool_drvinfo *info)
2594 struct virtnet_info *vi = netdev_priv(dev);
2595 struct virtio_device *vdev = vi->vdev;
2597 strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2598 strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2599 strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2603 /* TODO: Eliminate OOO packets during switching */
2604 static int virtnet_set_channels(struct net_device *dev,
2605 struct ethtool_channels *channels)
2607 struct virtnet_info *vi = netdev_priv(dev);
2608 u16 queue_pairs = channels->combined_count;
2611 /* We don't support separate rx/tx channels.
2612 * We don't allow setting 'other' channels.
2614 if (channels->rx_count || channels->tx_count || channels->other_count)
2617 if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2620 /* For now we don't support modifying channels while XDP is loaded
2621 * also when XDP is loaded all RX queues have XDP programs so we only
2622 * need to check a single RX queue.
2624 if (vi->rq[0].xdp_prog)
2628 err = _virtnet_set_queues(vi, queue_pairs);
2633 virtnet_set_affinity(vi);
2636 netif_set_real_num_tx_queues(dev, queue_pairs);
2637 netif_set_real_num_rx_queues(dev, queue_pairs);
2642 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2644 struct virtnet_info *vi = netdev_priv(dev);
2648 switch (stringset) {
2650 for (i = 0; i < vi->curr_queue_pairs; i++) {
2651 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
2652 ethtool_sprintf(&p, "rx_queue_%u_%s", i,
2653 virtnet_rq_stats_desc[j].desc);
2656 for (i = 0; i < vi->curr_queue_pairs; i++) {
2657 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
2658 ethtool_sprintf(&p, "tx_queue_%u_%s", i,
2659 virtnet_sq_stats_desc[j].desc);
2665 static int virtnet_get_sset_count(struct net_device *dev, int sset)
2667 struct virtnet_info *vi = netdev_priv(dev);
2671 return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2672 VIRTNET_SQ_STATS_LEN);
2678 static void virtnet_get_ethtool_stats(struct net_device *dev,
2679 struct ethtool_stats *stats, u64 *data)
2681 struct virtnet_info *vi = netdev_priv(dev);
2682 unsigned int idx = 0, start, i, j;
2683 const u8 *stats_base;
2686 for (i = 0; i < vi->curr_queue_pairs; i++) {
2687 struct receive_queue *rq = &vi->rq[i];
2689 stats_base = (u8 *)&rq->stats;
2691 start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2692 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2693 offset = virtnet_rq_stats_desc[j].offset;
2694 data[idx + j] = *(u64 *)(stats_base + offset);
2696 } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2697 idx += VIRTNET_RQ_STATS_LEN;
2700 for (i = 0; i < vi->curr_queue_pairs; i++) {
2701 struct send_queue *sq = &vi->sq[i];
2703 stats_base = (u8 *)&sq->stats;
2705 start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2706 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2707 offset = virtnet_sq_stats_desc[j].offset;
2708 data[idx + j] = *(u64 *)(stats_base + offset);
2710 } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2711 idx += VIRTNET_SQ_STATS_LEN;
2715 static void virtnet_get_channels(struct net_device *dev,
2716 struct ethtool_channels *channels)
2718 struct virtnet_info *vi = netdev_priv(dev);
2720 channels->combined_count = vi->curr_queue_pairs;
2721 channels->max_combined = vi->max_queue_pairs;
2722 channels->max_other = 0;
2723 channels->rx_count = 0;
2724 channels->tx_count = 0;
2725 channels->other_count = 0;
2728 static int virtnet_set_link_ksettings(struct net_device *dev,
2729 const struct ethtool_link_ksettings *cmd)
2731 struct virtnet_info *vi = netdev_priv(dev);
2733 return ethtool_virtdev_set_link_ksettings(dev, cmd,
2734 &vi->speed, &vi->duplex);
2737 static int virtnet_get_link_ksettings(struct net_device *dev,
2738 struct ethtool_link_ksettings *cmd)
2740 struct virtnet_info *vi = netdev_priv(dev);
2742 cmd->base.speed = vi->speed;
2743 cmd->base.duplex = vi->duplex;
2744 cmd->base.port = PORT_OTHER;
2749 static int virtnet_send_notf_coal_cmds(struct virtnet_info *vi,
2750 struct ethtool_coalesce *ec)
2752 struct scatterlist sgs_tx, sgs_rx;
2753 struct virtio_net_ctrl_coal_tx coal_tx;
2754 struct virtio_net_ctrl_coal_rx coal_rx;
2756 coal_tx.tx_usecs = cpu_to_le32(ec->tx_coalesce_usecs);
2757 coal_tx.tx_max_packets = cpu_to_le32(ec->tx_max_coalesced_frames);
2758 sg_init_one(&sgs_tx, &coal_tx, sizeof(coal_tx));
2760 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2761 VIRTIO_NET_CTRL_NOTF_COAL_TX_SET,
2765 /* Save parameters */
2766 vi->tx_usecs = ec->tx_coalesce_usecs;
2767 vi->tx_max_packets = ec->tx_max_coalesced_frames;
2769 coal_rx.rx_usecs = cpu_to_le32(ec->rx_coalesce_usecs);
2770 coal_rx.rx_max_packets = cpu_to_le32(ec->rx_max_coalesced_frames);
2771 sg_init_one(&sgs_rx, &coal_rx, sizeof(coal_rx));
2773 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2774 VIRTIO_NET_CTRL_NOTF_COAL_RX_SET,
2778 /* Save parameters */
2779 vi->rx_usecs = ec->rx_coalesce_usecs;
2780 vi->rx_max_packets = ec->rx_max_coalesced_frames;
2785 static int virtnet_coal_params_supported(struct ethtool_coalesce *ec)
2787 /* usecs coalescing is supported only if VIRTIO_NET_F_NOTF_COAL
2788 * feature is negotiated.
2790 if (ec->rx_coalesce_usecs || ec->tx_coalesce_usecs)
2793 if (ec->tx_max_coalesced_frames > 1 ||
2794 ec->rx_max_coalesced_frames != 1)
2800 static int virtnet_set_coalesce(struct net_device *dev,
2801 struct ethtool_coalesce *ec,
2802 struct kernel_ethtool_coalesce *kernel_coal,
2803 struct netlink_ext_ack *extack)
2805 struct virtnet_info *vi = netdev_priv(dev);
2806 int ret, i, napi_weight;
2807 bool update_napi = false;
2809 /* Can't change NAPI weight if the link is up */
2810 napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
2811 if (napi_weight ^ vi->sq[0].napi.weight) {
2812 if (dev->flags & IFF_UP)
2818 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL))
2819 ret = virtnet_send_notf_coal_cmds(vi, ec);
2821 ret = virtnet_coal_params_supported(ec);
2827 for (i = 0; i < vi->max_queue_pairs; i++)
2828 vi->sq[i].napi.weight = napi_weight;
2834 static int virtnet_get_coalesce(struct net_device *dev,
2835 struct ethtool_coalesce *ec,
2836 struct kernel_ethtool_coalesce *kernel_coal,
2837 struct netlink_ext_ack *extack)
2839 struct virtnet_info *vi = netdev_priv(dev);
2841 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
2842 ec->rx_coalesce_usecs = vi->rx_usecs;
2843 ec->tx_coalesce_usecs = vi->tx_usecs;
2844 ec->tx_max_coalesced_frames = vi->tx_max_packets;
2845 ec->rx_max_coalesced_frames = vi->rx_max_packets;
2847 ec->rx_max_coalesced_frames = 1;
2849 if (vi->sq[0].napi.weight)
2850 ec->tx_max_coalesced_frames = 1;
2856 static void virtnet_init_settings(struct net_device *dev)
2858 struct virtnet_info *vi = netdev_priv(dev);
2860 vi->speed = SPEED_UNKNOWN;
2861 vi->duplex = DUPLEX_UNKNOWN;
2864 static void virtnet_update_settings(struct virtnet_info *vi)
2869 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
2872 virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
2874 if (ethtool_validate_speed(speed))
2877 virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
2879 if (ethtool_validate_duplex(duplex))
2880 vi->duplex = duplex;
2883 static u32 virtnet_get_rxfh_key_size(struct net_device *dev)
2885 return ((struct virtnet_info *)netdev_priv(dev))->rss_key_size;
2888 static u32 virtnet_get_rxfh_indir_size(struct net_device *dev)
2890 return ((struct virtnet_info *)netdev_priv(dev))->rss_indir_table_size;
2893 static int virtnet_get_rxfh(struct net_device *dev, u32 *indir, u8 *key, u8 *hfunc)
2895 struct virtnet_info *vi = netdev_priv(dev);
2899 for (i = 0; i < vi->rss_indir_table_size; ++i)
2900 indir[i] = vi->ctrl->rss.indirection_table[i];
2904 memcpy(key, vi->ctrl->rss.key, vi->rss_key_size);
2907 *hfunc = ETH_RSS_HASH_TOP;
2912 static int virtnet_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key, const u8 hfunc)
2914 struct virtnet_info *vi = netdev_priv(dev);
2917 if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
2921 for (i = 0; i < vi->rss_indir_table_size; ++i)
2922 vi->ctrl->rss.indirection_table[i] = indir[i];
2925 memcpy(vi->ctrl->rss.key, key, vi->rss_key_size);
2927 virtnet_commit_rss_command(vi);
2932 static int virtnet_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rule_locs)
2934 struct virtnet_info *vi = netdev_priv(dev);
2937 switch (info->cmd) {
2938 case ETHTOOL_GRXRINGS:
2939 info->data = vi->curr_queue_pairs;
2942 virtnet_get_hashflow(vi, info);
2951 static int virtnet_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info)
2953 struct virtnet_info *vi = netdev_priv(dev);
2956 switch (info->cmd) {
2958 if (!virtnet_set_hashflow(vi, info))
2969 static const struct ethtool_ops virtnet_ethtool_ops = {
2970 .supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES |
2971 ETHTOOL_COALESCE_USECS,
2972 .get_drvinfo = virtnet_get_drvinfo,
2973 .get_link = ethtool_op_get_link,
2974 .get_ringparam = virtnet_get_ringparam,
2975 .set_ringparam = virtnet_set_ringparam,
2976 .get_strings = virtnet_get_strings,
2977 .get_sset_count = virtnet_get_sset_count,
2978 .get_ethtool_stats = virtnet_get_ethtool_stats,
2979 .set_channels = virtnet_set_channels,
2980 .get_channels = virtnet_get_channels,
2981 .get_ts_info = ethtool_op_get_ts_info,
2982 .get_link_ksettings = virtnet_get_link_ksettings,
2983 .set_link_ksettings = virtnet_set_link_ksettings,
2984 .set_coalesce = virtnet_set_coalesce,
2985 .get_coalesce = virtnet_get_coalesce,
2986 .get_rxfh_key_size = virtnet_get_rxfh_key_size,
2987 .get_rxfh_indir_size = virtnet_get_rxfh_indir_size,
2988 .get_rxfh = virtnet_get_rxfh,
2989 .set_rxfh = virtnet_set_rxfh,
2990 .get_rxnfc = virtnet_get_rxnfc,
2991 .set_rxnfc = virtnet_set_rxnfc,
2994 static void virtnet_freeze_down(struct virtio_device *vdev)
2996 struct virtnet_info *vi = vdev->priv;
2998 /* Make sure no work handler is accessing the device */
2999 flush_work(&vi->config_work);
3001 netif_tx_lock_bh(vi->dev);
3002 netif_device_detach(vi->dev);
3003 netif_tx_unlock_bh(vi->dev);
3004 if (netif_running(vi->dev))
3005 virtnet_close(vi->dev);
3008 static int init_vqs(struct virtnet_info *vi);
3010 static int virtnet_restore_up(struct virtio_device *vdev)
3012 struct virtnet_info *vi = vdev->priv;
3019 virtio_device_ready(vdev);
3021 enable_delayed_refill(vi);
3023 if (netif_running(vi->dev)) {
3024 err = virtnet_open(vi->dev);
3029 netif_tx_lock_bh(vi->dev);
3030 netif_device_attach(vi->dev);
3031 netif_tx_unlock_bh(vi->dev);
3035 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
3037 struct scatterlist sg;
3038 vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
3040 sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
3042 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
3043 VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
3044 dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
3051 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
3055 if (!vi->guest_offloads)
3058 return virtnet_set_guest_offloads(vi, offloads);
3061 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
3063 u64 offloads = vi->guest_offloads;
3065 if (!vi->guest_offloads)
3068 return virtnet_set_guest_offloads(vi, offloads);
3071 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
3072 struct netlink_ext_ack *extack)
3074 unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
3075 struct virtnet_info *vi = netdev_priv(dev);
3076 struct bpf_prog *old_prog;
3077 u16 xdp_qp = 0, curr_qp;
3080 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
3081 && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3082 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3083 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3084 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3085 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM))) {
3086 NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
3090 if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
3091 NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
3095 if (dev->mtu > max_sz) {
3096 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
3097 netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
3101 curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
3103 xdp_qp = nr_cpu_ids;
3105 /* XDP requires extra queues for XDP_TX */
3106 if (curr_qp + xdp_qp > vi->max_queue_pairs) {
3107 netdev_warn_once(dev, "XDP request %i queues but max is %i. XDP_TX and XDP_REDIRECT will operate in a slower locked tx mode.\n",
3108 curr_qp + xdp_qp, vi->max_queue_pairs);
3112 old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
3113 if (!prog && !old_prog)
3117 bpf_prog_add(prog, vi->max_queue_pairs - 1);
3119 /* Make sure NAPI is not using any XDP TX queues for RX. */
3120 if (netif_running(dev)) {
3121 for (i = 0; i < vi->max_queue_pairs; i++) {
3122 napi_disable(&vi->rq[i].napi);
3123 virtnet_napi_tx_disable(&vi->sq[i].napi);
3128 for (i = 0; i < vi->max_queue_pairs; i++) {
3129 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3131 virtnet_restore_guest_offloads(vi);
3136 err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
3139 netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
3140 vi->xdp_queue_pairs = xdp_qp;
3143 vi->xdp_enabled = true;
3144 for (i = 0; i < vi->max_queue_pairs; i++) {
3145 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3146 if (i == 0 && !old_prog)
3147 virtnet_clear_guest_offloads(vi);
3150 vi->xdp_enabled = false;
3153 for (i = 0; i < vi->max_queue_pairs; i++) {
3155 bpf_prog_put(old_prog);
3156 if (netif_running(dev)) {
3157 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3158 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3167 virtnet_clear_guest_offloads(vi);
3168 for (i = 0; i < vi->max_queue_pairs; i++)
3169 rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
3172 if (netif_running(dev)) {
3173 for (i = 0; i < vi->max_queue_pairs; i++) {
3174 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3175 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3180 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
3184 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
3186 switch (xdp->command) {
3187 case XDP_SETUP_PROG:
3188 return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
3194 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
3197 struct virtnet_info *vi = netdev_priv(dev);
3200 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
3203 ret = snprintf(buf, len, "sby");
3210 static int virtnet_set_features(struct net_device *dev,
3211 netdev_features_t features)
3213 struct virtnet_info *vi = netdev_priv(dev);
3217 if ((dev->features ^ features) & NETIF_F_GRO_HW) {
3218 if (vi->xdp_enabled)
3221 if (features & NETIF_F_GRO_HW)
3222 offloads = vi->guest_offloads_capable;
3224 offloads = vi->guest_offloads_capable &
3225 ~GUEST_OFFLOAD_GRO_HW_MASK;
3227 err = virtnet_set_guest_offloads(vi, offloads);
3230 vi->guest_offloads = offloads;
3233 if ((dev->features ^ features) & NETIF_F_RXHASH) {
3234 if (features & NETIF_F_RXHASH)
3235 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
3237 vi->ctrl->rss.hash_types = VIRTIO_NET_HASH_REPORT_NONE;
3239 if (!virtnet_commit_rss_command(vi))
3246 static void virtnet_tx_timeout(struct net_device *dev, unsigned int txqueue)
3248 struct virtnet_info *priv = netdev_priv(dev);
3249 struct send_queue *sq = &priv->sq[txqueue];
3250 struct netdev_queue *txq = netdev_get_tx_queue(dev, txqueue);
3252 u64_stats_update_begin(&sq->stats.syncp);
3253 sq->stats.tx_timeouts++;
3254 u64_stats_update_end(&sq->stats.syncp);
3256 netdev_err(dev, "TX timeout on queue: %u, sq: %s, vq: 0x%x, name: %s, %u usecs ago\n",
3257 txqueue, sq->name, sq->vq->index, sq->vq->name,
3258 jiffies_to_usecs(jiffies - READ_ONCE(txq->trans_start)));
3261 static const struct net_device_ops virtnet_netdev = {
3262 .ndo_open = virtnet_open,
3263 .ndo_stop = virtnet_close,
3264 .ndo_start_xmit = start_xmit,
3265 .ndo_validate_addr = eth_validate_addr,
3266 .ndo_set_mac_address = virtnet_set_mac_address,
3267 .ndo_set_rx_mode = virtnet_set_rx_mode,
3268 .ndo_get_stats64 = virtnet_stats,
3269 .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
3270 .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
3271 .ndo_bpf = virtnet_xdp,
3272 .ndo_xdp_xmit = virtnet_xdp_xmit,
3273 .ndo_features_check = passthru_features_check,
3274 .ndo_get_phys_port_name = virtnet_get_phys_port_name,
3275 .ndo_set_features = virtnet_set_features,
3276 .ndo_tx_timeout = virtnet_tx_timeout,
3279 static void virtnet_config_changed_work(struct work_struct *work)
3281 struct virtnet_info *vi =
3282 container_of(work, struct virtnet_info, config_work);
3285 if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
3286 struct virtio_net_config, status, &v) < 0)
3289 if (v & VIRTIO_NET_S_ANNOUNCE) {
3290 netdev_notify_peers(vi->dev);
3291 virtnet_ack_link_announce(vi);
3294 /* Ignore unknown (future) status bits */
3295 v &= VIRTIO_NET_S_LINK_UP;
3297 if (vi->status == v)
3302 if (vi->status & VIRTIO_NET_S_LINK_UP) {
3303 virtnet_update_settings(vi);
3304 netif_carrier_on(vi->dev);
3305 netif_tx_wake_all_queues(vi->dev);
3307 netif_carrier_off(vi->dev);
3308 netif_tx_stop_all_queues(vi->dev);
3312 static void virtnet_config_changed(struct virtio_device *vdev)
3314 struct virtnet_info *vi = vdev->priv;
3316 schedule_work(&vi->config_work);
3319 static void virtnet_free_queues(struct virtnet_info *vi)
3323 for (i = 0; i < vi->max_queue_pairs; i++) {
3324 __netif_napi_del(&vi->rq[i].napi);
3325 __netif_napi_del(&vi->sq[i].napi);
3328 /* We called __netif_napi_del(),
3329 * we need to respect an RCU grace period before freeing vi->rq
3338 static void _free_receive_bufs(struct virtnet_info *vi)
3340 struct bpf_prog *old_prog;
3343 for (i = 0; i < vi->max_queue_pairs; i++) {
3344 while (vi->rq[i].pages)
3345 __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
3347 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
3348 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
3350 bpf_prog_put(old_prog);
3354 static void free_receive_bufs(struct virtnet_info *vi)
3357 _free_receive_bufs(vi);
3361 static void free_receive_page_frags(struct virtnet_info *vi)
3364 for (i = 0; i < vi->max_queue_pairs; i++)
3365 if (vi->rq[i].alloc_frag.page)
3366 put_page(vi->rq[i].alloc_frag.page);
3369 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf)
3371 if (!is_xdp_frame(buf))
3374 xdp_return_frame(ptr_to_xdp(buf));
3377 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf)
3379 struct virtnet_info *vi = vq->vdev->priv;
3382 if (vi->mergeable_rx_bufs)
3383 put_page(virt_to_head_page(buf));
3384 else if (vi->big_packets)
3385 give_pages(&vi->rq[i], buf);
3387 put_page(virt_to_head_page(buf));
3390 static void free_unused_bufs(struct virtnet_info *vi)
3395 for (i = 0; i < vi->max_queue_pairs; i++) {
3396 struct virtqueue *vq = vi->sq[i].vq;
3397 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3398 virtnet_sq_free_unused_buf(vq, buf);
3401 for (i = 0; i < vi->max_queue_pairs; i++) {
3402 struct virtqueue *vq = vi->rq[i].vq;
3403 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3404 virtnet_rq_free_unused_buf(vq, buf);
3408 static void virtnet_del_vqs(struct virtnet_info *vi)
3410 struct virtio_device *vdev = vi->vdev;
3412 virtnet_clean_affinity(vi);
3414 vdev->config->del_vqs(vdev);
3416 virtnet_free_queues(vi);
3419 /* How large should a single buffer be so a queue full of these can fit at
3420 * least one full packet?
3421 * Logic below assumes the mergeable buffer header is used.
3423 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
3425 const unsigned int hdr_len = vi->hdr_len;
3426 unsigned int rq_size = virtqueue_get_vring_size(vq);
3427 unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
3428 unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
3429 unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
3431 return max(max(min_buf_len, hdr_len) - hdr_len,
3432 (unsigned int)GOOD_PACKET_LEN);
3435 static int virtnet_find_vqs(struct virtnet_info *vi)
3437 vq_callback_t **callbacks;
3438 struct virtqueue **vqs;
3444 /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
3445 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
3446 * possible control vq.
3448 total_vqs = vi->max_queue_pairs * 2 +
3449 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
3451 /* Allocate space for find_vqs parameters */
3452 vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
3455 callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
3458 names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
3461 if (!vi->big_packets || vi->mergeable_rx_bufs) {
3462 ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
3469 /* Parameters for control virtqueue, if any */
3471 callbacks[total_vqs - 1] = NULL;
3472 names[total_vqs - 1] = "control";
3475 /* Allocate/initialize parameters for send/receive virtqueues */
3476 for (i = 0; i < vi->max_queue_pairs; i++) {
3477 callbacks[rxq2vq(i)] = skb_recv_done;
3478 callbacks[txq2vq(i)] = skb_xmit_done;
3479 sprintf(vi->rq[i].name, "input.%d", i);
3480 sprintf(vi->sq[i].name, "output.%d", i);
3481 names[rxq2vq(i)] = vi->rq[i].name;
3482 names[txq2vq(i)] = vi->sq[i].name;
3484 ctx[rxq2vq(i)] = true;
3487 ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
3493 vi->cvq = vqs[total_vqs - 1];
3494 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
3495 vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
3498 for (i = 0; i < vi->max_queue_pairs; i++) {
3499 vi->rq[i].vq = vqs[rxq2vq(i)];
3500 vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
3501 vi->sq[i].vq = vqs[txq2vq(i)];
3504 /* run here: ret == 0. */
3519 static int virtnet_alloc_queues(struct virtnet_info *vi)
3524 vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
3530 vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
3533 vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
3537 INIT_DELAYED_WORK(&vi->refill, refill_work);
3538 for (i = 0; i < vi->max_queue_pairs; i++) {
3539 vi->rq[i].pages = NULL;
3540 netif_napi_add_weight(vi->dev, &vi->rq[i].napi, virtnet_poll,
3542 netif_napi_add_tx_weight(vi->dev, &vi->sq[i].napi,
3544 napi_tx ? napi_weight : 0);
3546 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
3547 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
3548 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
3550 u64_stats_init(&vi->rq[i].stats.syncp);
3551 u64_stats_init(&vi->sq[i].stats.syncp);
3564 static int init_vqs(struct virtnet_info *vi)
3568 /* Allocate send & receive queues */
3569 ret = virtnet_alloc_queues(vi);
3573 ret = virtnet_find_vqs(vi);
3578 virtnet_set_affinity(vi);
3584 virtnet_free_queues(vi);
3590 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
3593 struct virtnet_info *vi = netdev_priv(queue->dev);
3594 unsigned int queue_index = get_netdev_rx_queue_index(queue);
3595 unsigned int headroom = virtnet_get_headroom(vi);
3596 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
3597 struct ewma_pkt_len *avg;
3599 BUG_ON(queue_index >= vi->max_queue_pairs);
3600 avg = &vi->rq[queue_index].mrg_avg_pkt_len;
3601 return sprintf(buf, "%u\n",
3602 get_mergeable_buf_len(&vi->rq[queue_index], avg,
3603 SKB_DATA_ALIGN(headroom + tailroom)));
3606 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
3607 __ATTR_RO(mergeable_rx_buffer_size);
3609 static struct attribute *virtio_net_mrg_rx_attrs[] = {
3610 &mergeable_rx_buffer_size_attribute.attr,
3614 static const struct attribute_group virtio_net_mrg_rx_group = {
3615 .name = "virtio_net",
3616 .attrs = virtio_net_mrg_rx_attrs
3620 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
3622 const char *fname, const char *dname)
3624 if (!virtio_has_feature(vdev, fbit))
3627 dev_err(&vdev->dev, "device advertises feature %s but not %s",
3633 #define VIRTNET_FAIL_ON(vdev, fbit, dbit) \
3634 virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
3636 static bool virtnet_validate_features(struct virtio_device *vdev)
3638 if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
3639 (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
3640 "VIRTIO_NET_F_CTRL_VQ") ||
3641 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
3642 "VIRTIO_NET_F_CTRL_VQ") ||
3643 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
3644 "VIRTIO_NET_F_CTRL_VQ") ||
3645 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
3646 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
3647 "VIRTIO_NET_F_CTRL_VQ") ||
3648 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_RSS,
3649 "VIRTIO_NET_F_CTRL_VQ") ||
3650 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_HASH_REPORT,
3651 "VIRTIO_NET_F_CTRL_VQ") ||
3652 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_NOTF_COAL,
3653 "VIRTIO_NET_F_CTRL_VQ"))) {
3660 #define MIN_MTU ETH_MIN_MTU
3661 #define MAX_MTU ETH_MAX_MTU
3663 static int virtnet_validate(struct virtio_device *vdev)
3665 if (!vdev->config->get) {
3666 dev_err(&vdev->dev, "%s failure: config access disabled\n",
3671 if (!virtnet_validate_features(vdev))
3674 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3675 int mtu = virtio_cread16(vdev,
3676 offsetof(struct virtio_net_config,
3679 __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3685 static bool virtnet_check_guest_gso(const struct virtnet_info *vi)
3687 return virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3688 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3689 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3690 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO);
3693 static int virtnet_probe(struct virtio_device *vdev)
3695 int i, err = -ENOMEM;
3696 struct net_device *dev;
3697 struct virtnet_info *vi;
3698 u16 max_queue_pairs;
3701 /* Find if host supports multiqueue/rss virtio_net device */
3702 max_queue_pairs = 1;
3703 if (virtio_has_feature(vdev, VIRTIO_NET_F_MQ) || virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3705 virtio_cread16(vdev, offsetof(struct virtio_net_config, max_virtqueue_pairs));
3707 /* We need at least 2 queue's */
3708 if (max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
3709 max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
3710 !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3711 max_queue_pairs = 1;
3713 /* Allocate ourselves a network device with room for our info */
3714 dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
3718 /* Set up network device as normal. */
3719 dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
3720 IFF_TX_SKB_NO_LINEAR;
3721 dev->netdev_ops = &virtnet_netdev;
3722 dev->features = NETIF_F_HIGHDMA;
3724 dev->ethtool_ops = &virtnet_ethtool_ops;
3725 SET_NETDEV_DEV(dev, &vdev->dev);
3727 /* Do we support "hardware" checksums? */
3728 if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
3729 /* This opens up the world of extra features. */
3730 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3732 dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3734 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
3735 dev->hw_features |= NETIF_F_TSO
3736 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
3738 /* Individual feature bits: what can host handle? */
3739 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
3740 dev->hw_features |= NETIF_F_TSO;
3741 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
3742 dev->hw_features |= NETIF_F_TSO6;
3743 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
3744 dev->hw_features |= NETIF_F_TSO_ECN;
3746 dev->features |= NETIF_F_GSO_ROBUST;
3749 dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
3750 /* (!csum && gso) case will be fixed by register_netdev() */
3752 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
3753 dev->features |= NETIF_F_RXCSUM;
3754 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3755 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3756 dev->features |= NETIF_F_GRO_HW;
3757 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3758 dev->hw_features |= NETIF_F_GRO_HW;
3760 dev->vlan_features = dev->features;
3762 /* MTU range: 68 - 65535 */
3763 dev->min_mtu = MIN_MTU;
3764 dev->max_mtu = MAX_MTU;
3766 /* Configuration may specify what MAC to use. Otherwise random. */
3767 if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3770 virtio_cread_bytes(vdev,
3771 offsetof(struct virtio_net_config, mac),
3773 eth_hw_addr_set(dev, addr);
3775 eth_hw_addr_random(dev);
3778 /* Set up our device-specific information */
3779 vi = netdev_priv(dev);
3784 INIT_WORK(&vi->config_work, virtnet_config_changed_work);
3785 spin_lock_init(&vi->refill_lock);
3787 /* If we can receive ANY GSO packets, we must allocate large ones. */
3788 if (virtnet_check_guest_gso(vi))
3789 vi->big_packets = true;
3791 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
3792 vi->mergeable_rx_bufs = true;
3794 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
3797 vi->tx_max_packets = 0;
3798 vi->rx_max_packets = 0;
3801 if (virtio_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT))
3802 vi->has_rss_hash_report = true;
3804 if (virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3807 if (vi->has_rss || vi->has_rss_hash_report) {
3808 vi->rss_indir_table_size =
3809 virtio_cread16(vdev, offsetof(struct virtio_net_config,
3810 rss_max_indirection_table_length));
3812 virtio_cread8(vdev, offsetof(struct virtio_net_config, rss_max_key_size));
3814 vi->rss_hash_types_supported =
3815 virtio_cread32(vdev, offsetof(struct virtio_net_config, supported_hash_types));
3816 vi->rss_hash_types_supported &=
3817 ~(VIRTIO_NET_RSS_HASH_TYPE_IP_EX |
3818 VIRTIO_NET_RSS_HASH_TYPE_TCP_EX |
3819 VIRTIO_NET_RSS_HASH_TYPE_UDP_EX);
3821 dev->hw_features |= NETIF_F_RXHASH;
3824 if (vi->has_rss_hash_report)
3825 vi->hdr_len = sizeof(struct virtio_net_hdr_v1_hash);
3826 else if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
3827 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3828 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
3830 vi->hdr_len = sizeof(struct virtio_net_hdr);
3832 if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
3833 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3834 vi->any_header_sg = true;
3836 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3839 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3840 mtu = virtio_cread16(vdev,
3841 offsetof(struct virtio_net_config,
3843 if (mtu < dev->min_mtu) {
3844 /* Should never trigger: MTU was previously validated
3845 * in virtnet_validate.
3848 "device MTU appears to have changed it is now %d < %d",
3857 /* TODO: size buffers correctly in this case. */
3858 if (dev->mtu > ETH_DATA_LEN)
3859 vi->big_packets = true;
3862 if (vi->any_header_sg)
3863 dev->needed_headroom = vi->hdr_len;
3865 /* Enable multiqueue by default */
3866 if (num_online_cpus() >= max_queue_pairs)
3867 vi->curr_queue_pairs = max_queue_pairs;
3869 vi->curr_queue_pairs = num_online_cpus();
3870 vi->max_queue_pairs = max_queue_pairs;
3872 /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
3878 if (vi->mergeable_rx_bufs)
3879 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
3881 netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
3882 netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
3884 virtnet_init_settings(dev);
3886 if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
3887 vi->failover = net_failover_create(vi->dev);
3888 if (IS_ERR(vi->failover)) {
3889 err = PTR_ERR(vi->failover);
3894 if (vi->has_rss || vi->has_rss_hash_report)
3895 virtnet_init_default_rss(vi);
3897 /* serialize netdev register + virtio_device_ready() with ndo_open() */
3900 err = register_netdevice(dev);
3902 pr_debug("virtio_net: registering device failed\n");
3907 virtio_device_ready(vdev);
3911 err = virtnet_cpu_notif_add(vi);
3913 pr_debug("virtio_net: registering cpu notifier failed\n");
3914 goto free_unregister_netdev;
3917 virtnet_set_queues(vi, vi->curr_queue_pairs);
3919 /* Assume link up if device can't report link status,
3920 otherwise get link status from config. */
3921 netif_carrier_off(dev);
3922 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
3923 schedule_work(&vi->config_work);
3925 vi->status = VIRTIO_NET_S_LINK_UP;
3926 virtnet_update_settings(vi);
3927 netif_carrier_on(dev);
3930 for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
3931 if (virtio_has_feature(vi->vdev, guest_offloads[i]))
3932 set_bit(guest_offloads[i], &vi->guest_offloads);
3933 vi->guest_offloads_capable = vi->guest_offloads;
3935 pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
3936 dev->name, max_queue_pairs);
3940 free_unregister_netdev:
3941 virtio_reset_device(vdev);
3943 unregister_netdev(dev);
3945 net_failover_destroy(vi->failover);
3947 cancel_delayed_work_sync(&vi->refill);
3948 free_receive_page_frags(vi);
3949 virtnet_del_vqs(vi);
3955 static void remove_vq_common(struct virtnet_info *vi)
3957 virtio_reset_device(vi->vdev);
3959 /* Free unused buffers in both send and recv, if any. */
3960 free_unused_bufs(vi);
3962 free_receive_bufs(vi);
3964 free_receive_page_frags(vi);
3966 virtnet_del_vqs(vi);
3969 static void virtnet_remove(struct virtio_device *vdev)
3971 struct virtnet_info *vi = vdev->priv;
3973 virtnet_cpu_notif_remove(vi);
3975 /* Make sure no work handler is accessing the device. */
3976 flush_work(&vi->config_work);
3978 unregister_netdev(vi->dev);
3980 net_failover_destroy(vi->failover);
3982 remove_vq_common(vi);
3984 free_netdev(vi->dev);
3987 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
3989 struct virtnet_info *vi = vdev->priv;
3991 virtnet_cpu_notif_remove(vi);
3992 virtnet_freeze_down(vdev);
3993 remove_vq_common(vi);
3998 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
4000 struct virtnet_info *vi = vdev->priv;
4003 err = virtnet_restore_up(vdev);
4006 virtnet_set_queues(vi, vi->curr_queue_pairs);
4008 err = virtnet_cpu_notif_add(vi);
4010 virtnet_freeze_down(vdev);
4011 remove_vq_common(vi);
4018 static struct virtio_device_id id_table[] = {
4019 { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
4023 #define VIRTNET_FEATURES \
4024 VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
4026 VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
4027 VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
4028 VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
4029 VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
4030 VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
4031 VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
4032 VIRTIO_NET_F_CTRL_MAC_ADDR, \
4033 VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
4034 VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY, \
4035 VIRTIO_NET_F_RSS, VIRTIO_NET_F_HASH_REPORT, VIRTIO_NET_F_NOTF_COAL
4037 static unsigned int features[] = {
4041 static unsigned int features_legacy[] = {
4044 VIRTIO_F_ANY_LAYOUT,
4047 static struct virtio_driver virtio_net_driver = {
4048 .feature_table = features,
4049 .feature_table_size = ARRAY_SIZE(features),
4050 .feature_table_legacy = features_legacy,
4051 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
4052 .driver.name = KBUILD_MODNAME,
4053 .driver.owner = THIS_MODULE,
4054 .id_table = id_table,
4055 .validate = virtnet_validate,
4056 .probe = virtnet_probe,
4057 .remove = virtnet_remove,
4058 .config_changed = virtnet_config_changed,
4059 #ifdef CONFIG_PM_SLEEP
4060 .freeze = virtnet_freeze,
4061 .restore = virtnet_restore,
4065 static __init int virtio_net_driver_init(void)
4069 ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
4071 virtnet_cpu_down_prep);
4074 virtionet_online = ret;
4075 ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
4076 NULL, virtnet_cpu_dead);
4079 ret = register_virtio_driver(&virtio_net_driver);
4084 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4086 cpuhp_remove_multi_state(virtionet_online);
4090 module_init(virtio_net_driver_init);
4092 static __exit void virtio_net_driver_exit(void)
4094 unregister_virtio_driver(&virtio_net_driver);
4095 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4096 cpuhp_remove_multi_state(virtionet_online);
4098 module_exit(virtio_net_driver_exit);
4100 MODULE_DEVICE_TABLE(virtio, id_table);
4101 MODULE_DESCRIPTION("Virtio network driver");
4102 MODULE_LICENSE("GPL");