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 /* number of sg entries allocated for big packets */
229 unsigned int big_packets_num_skbfrags;
231 /* Host will merge rx buffers for big packets (shake it! shake it!) */
232 bool mergeable_rx_bufs;
234 /* Host supports rss and/or hash report */
236 bool has_rss_hash_report;
238 u16 rss_indir_table_size;
239 u32 rss_hash_types_supported;
240 u32 rss_hash_types_saved;
242 /* Has control virtqueue */
245 /* Host can handle any s/g split between our header and packet data */
248 /* Packet virtio header size */
251 /* Work struct for delayed refilling if we run low on memory. */
252 struct delayed_work refill;
254 /* Is delayed refill enabled? */
257 /* The lock to synchronize the access to refill_enabled */
258 spinlock_t refill_lock;
260 /* Work struct for config space updates */
261 struct work_struct config_work;
263 /* Does the affinity hint is set for virtqueues? */
264 bool affinity_hint_set;
266 /* CPU hotplug instances for online & dead */
267 struct hlist_node node;
268 struct hlist_node node_dead;
270 struct control_buf *ctrl;
272 /* Ethtool settings */
276 /* Interrupt coalescing settings */
282 unsigned long guest_offloads;
283 unsigned long guest_offloads_capable;
285 /* failover when STANDBY feature enabled */
286 struct failover *failover;
289 struct padded_vnet_hdr {
290 struct virtio_net_hdr_v1_hash hdr;
292 * hdr is in a separate sg buffer, and data sg buffer shares same page
293 * with this header sg. This padding makes next sg 16 byte aligned
299 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf);
300 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf);
302 static bool is_xdp_frame(void *ptr)
304 return (unsigned long)ptr & VIRTIO_XDP_FLAG;
307 static void *xdp_to_ptr(struct xdp_frame *ptr)
309 return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
312 static struct xdp_frame *ptr_to_xdp(void *ptr)
314 return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
317 /* Converting between virtqueue no. and kernel tx/rx queue no.
318 * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
320 static int vq2txq(struct virtqueue *vq)
322 return (vq->index - 1) / 2;
325 static int txq2vq(int txq)
330 static int vq2rxq(struct virtqueue *vq)
332 return vq->index / 2;
335 static int rxq2vq(int rxq)
340 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
342 return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
346 * private is used to chain pages for big packets, put the whole
347 * most recent used list in the beginning for reuse
349 static void give_pages(struct receive_queue *rq, struct page *page)
353 /* Find end of list, sew whole thing into vi->rq.pages. */
354 for (end = page; end->private; end = (struct page *)end->private);
355 end->private = (unsigned long)rq->pages;
359 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
361 struct page *p = rq->pages;
364 rq->pages = (struct page *)p->private;
365 /* clear private here, it is used to chain pages */
368 p = alloc_page(gfp_mask);
372 static void enable_delayed_refill(struct virtnet_info *vi)
374 spin_lock_bh(&vi->refill_lock);
375 vi->refill_enabled = true;
376 spin_unlock_bh(&vi->refill_lock);
379 static void disable_delayed_refill(struct virtnet_info *vi)
381 spin_lock_bh(&vi->refill_lock);
382 vi->refill_enabled = false;
383 spin_unlock_bh(&vi->refill_lock);
386 static void virtqueue_napi_schedule(struct napi_struct *napi,
387 struct virtqueue *vq)
389 if (napi_schedule_prep(napi)) {
390 virtqueue_disable_cb(vq);
391 __napi_schedule(napi);
395 static void virtqueue_napi_complete(struct napi_struct *napi,
396 struct virtqueue *vq, int processed)
400 opaque = virtqueue_enable_cb_prepare(vq);
401 if (napi_complete_done(napi, processed)) {
402 if (unlikely(virtqueue_poll(vq, opaque)))
403 virtqueue_napi_schedule(napi, vq);
405 virtqueue_disable_cb(vq);
409 static void skb_xmit_done(struct virtqueue *vq)
411 struct virtnet_info *vi = vq->vdev->priv;
412 struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
414 /* Suppress further interrupts. */
415 virtqueue_disable_cb(vq);
418 virtqueue_napi_schedule(napi, vq);
420 /* We were probably waiting for more output buffers. */
421 netif_wake_subqueue(vi->dev, vq2txq(vq));
424 #define MRG_CTX_HEADER_SHIFT 22
425 static void *mergeable_len_to_ctx(unsigned int truesize,
426 unsigned int headroom)
428 return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
431 static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
433 return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
436 static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
438 return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
441 /* Called from bottom half context */
442 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
443 struct receive_queue *rq,
444 struct page *page, unsigned int offset,
445 unsigned int len, unsigned int truesize,
446 bool hdr_valid, unsigned int metasize,
447 unsigned int headroom)
450 struct virtio_net_hdr_mrg_rxbuf *hdr;
451 unsigned int copy, hdr_len, hdr_padded_len;
452 struct page *page_to_free = NULL;
453 int tailroom, shinfo_size;
454 char *p, *hdr_p, *buf;
456 p = page_address(page) + offset;
459 hdr_len = vi->hdr_len;
460 if (vi->mergeable_rx_bufs)
461 hdr_padded_len = hdr_len;
463 hdr_padded_len = sizeof(struct padded_vnet_hdr);
465 /* If headroom is not 0, there is an offset between the beginning of the
466 * data and the allocated space, otherwise the data and the allocated
469 * Buffers with headroom use PAGE_SIZE as alloc size, see
470 * add_recvbuf_mergeable() + get_mergeable_buf_len()
472 truesize = headroom ? PAGE_SIZE : truesize;
473 tailroom = truesize - headroom;
477 offset += hdr_padded_len;
479 tailroom -= hdr_padded_len + len;
481 shinfo_size = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
483 /* copy small packet so we can reuse these pages */
484 if (!NET_IP_ALIGN && len > GOOD_COPY_LEN && tailroom >= shinfo_size) {
485 skb = build_skb(buf, truesize);
489 skb_reserve(skb, p - buf);
492 page = (struct page *)page->private;
494 give_pages(rq, page);
498 /* copy small packet so we can reuse these pages for small data */
499 skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
503 /* Copy all frame if it fits skb->head, otherwise
504 * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
506 if (len <= skb_tailroom(skb))
509 copy = ETH_HLEN + metasize;
510 skb_put_data(skb, p, copy);
515 if (vi->mergeable_rx_bufs) {
517 skb_add_rx_frag(skb, 0, page, offset, len, truesize);
524 * Verify that we can indeed put this data into a skb.
525 * This is here to handle cases when the device erroneously
526 * tries to receive more than is possible. This is usually
527 * the case of a broken device.
529 if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
530 net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
534 BUG_ON(offset >= PAGE_SIZE);
536 unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
537 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
538 frag_size, truesize);
540 page = (struct page *)page->private;
545 give_pages(rq, page);
548 /* hdr_valid means no XDP, so we can copy the vnet header */
550 hdr = skb_vnet_hdr(skb);
551 memcpy(hdr, hdr_p, hdr_len);
554 put_page(page_to_free);
557 __skb_pull(skb, metasize);
558 skb_metadata_set(skb, metasize);
564 static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
565 struct send_queue *sq,
566 struct xdp_frame *xdpf)
568 struct virtio_net_hdr_mrg_rxbuf *hdr;
571 if (unlikely(xdpf->headroom < vi->hdr_len))
574 /* Make room for virtqueue hdr (also change xdpf->headroom?) */
575 xdpf->data -= vi->hdr_len;
576 /* Zero header and leave csum up to XDP layers */
578 memset(hdr, 0, vi->hdr_len);
579 xdpf->len += vi->hdr_len;
581 sg_init_one(sq->sg, xdpf->data, xdpf->len);
583 err = virtqueue_add_outbuf(sq->vq, sq->sg, 1, xdp_to_ptr(xdpf),
586 return -ENOSPC; /* Caller handle free/refcnt */
591 /* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
592 * the current cpu, so it does not need to be locked.
594 * Here we use marco instead of inline functions because we have to deal with
595 * three issues at the same time: 1. the choice of sq. 2. judge and execute the
596 * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
597 * functions to perfectly solve these three problems at the same time.
599 #define virtnet_xdp_get_sq(vi) ({ \
600 int cpu = smp_processor_id(); \
601 struct netdev_queue *txq; \
602 typeof(vi) v = (vi); \
605 if (v->curr_queue_pairs > nr_cpu_ids) { \
606 qp = v->curr_queue_pairs - v->xdp_queue_pairs; \
608 txq = netdev_get_tx_queue(v->dev, qp); \
609 __netif_tx_acquire(txq); \
611 qp = cpu % v->curr_queue_pairs; \
612 txq = netdev_get_tx_queue(v->dev, qp); \
613 __netif_tx_lock(txq, cpu); \
618 #define virtnet_xdp_put_sq(vi, q) { \
619 struct netdev_queue *txq; \
620 typeof(vi) v = (vi); \
622 txq = netdev_get_tx_queue(v->dev, (q) - v->sq); \
623 if (v->curr_queue_pairs > nr_cpu_ids) \
624 __netif_tx_release(txq); \
626 __netif_tx_unlock(txq); \
629 static int virtnet_xdp_xmit(struct net_device *dev,
630 int n, struct xdp_frame **frames, u32 flags)
632 struct virtnet_info *vi = netdev_priv(dev);
633 struct receive_queue *rq = vi->rq;
634 struct bpf_prog *xdp_prog;
635 struct send_queue *sq;
645 /* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
646 * indicate XDP resources have been successfully allocated.
648 xdp_prog = rcu_access_pointer(rq->xdp_prog);
652 sq = virtnet_xdp_get_sq(vi);
654 if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
659 /* Free up any pending old buffers before queueing new ones. */
660 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
661 if (likely(is_xdp_frame(ptr))) {
662 struct xdp_frame *frame = ptr_to_xdp(ptr);
665 xdp_return_frame(frame);
667 struct sk_buff *skb = ptr;
670 napi_consume_skb(skb, false);
675 for (i = 0; i < n; i++) {
676 struct xdp_frame *xdpf = frames[i];
678 if (__virtnet_xdp_xmit_one(vi, sq, xdpf))
684 if (flags & XDP_XMIT_FLUSH) {
685 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
689 u64_stats_update_begin(&sq->stats.syncp);
690 sq->stats.bytes += bytes;
691 sq->stats.packets += packets;
692 sq->stats.xdp_tx += n;
693 sq->stats.xdp_tx_drops += n - nxmit;
694 sq->stats.kicks += kicks;
695 u64_stats_update_end(&sq->stats.syncp);
697 virtnet_xdp_put_sq(vi, sq);
701 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
703 return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
706 /* We copy the packet for XDP in the following cases:
708 * 1) Packet is scattered across multiple rx buffers.
709 * 2) Headroom space is insufficient.
711 * This is inefficient but it's a temporary condition that
712 * we hit right after XDP is enabled and until queue is refilled
713 * with large buffers with sufficient headroom - so it should affect
714 * at most queue size packets.
715 * Afterwards, the conditions to enable
716 * XDP should preclude the underlying device from sending packets
717 * across multiple buffers (num_buf > 1), and we make sure buffers
718 * have enough headroom.
720 static struct page *xdp_linearize_page(struct receive_queue *rq,
727 struct page *page = alloc_page(GFP_ATOMIC);
732 memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
736 int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
741 buf = virtqueue_get_buf(rq->vq, &buflen);
745 p = virt_to_head_page(buf);
746 off = buf - page_address(p);
748 /* guard against a misconfigured or uncooperative backend that
749 * is sending packet larger than the MTU.
751 if ((page_off + buflen + tailroom) > PAGE_SIZE) {
756 memcpy(page_address(page) + page_off,
757 page_address(p) + off, buflen);
762 /* Headroom does not contribute to packet length */
763 *len = page_off - VIRTIO_XDP_HEADROOM;
766 __free_pages(page, 0);
770 static struct sk_buff *receive_small(struct net_device *dev,
771 struct virtnet_info *vi,
772 struct receive_queue *rq,
773 void *buf, void *ctx,
775 unsigned int *xdp_xmit,
776 struct virtnet_rq_stats *stats)
779 struct bpf_prog *xdp_prog;
780 unsigned int xdp_headroom = (unsigned long)ctx;
781 unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
782 unsigned int headroom = vi->hdr_len + header_offset;
783 unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
784 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
785 struct page *page = virt_to_head_page(buf);
786 unsigned int delta = 0;
787 struct page *xdp_page;
789 unsigned int metasize = 0;
794 if (unlikely(len > GOOD_PACKET_LEN)) {
795 pr_debug("%s: rx error: len %u exceeds max size %d\n",
796 dev->name, len, GOOD_PACKET_LEN);
797 dev->stats.rx_length_errors++;
801 if (likely(!vi->xdp_enabled)) {
807 xdp_prog = rcu_dereference(rq->xdp_prog);
809 struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
810 struct xdp_frame *xdpf;
815 if (unlikely(hdr->hdr.gso_type))
818 if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
819 int offset = buf - page_address(page) + header_offset;
820 unsigned int tlen = len + vi->hdr_len;
823 xdp_headroom = virtnet_get_headroom(vi);
824 header_offset = VIRTNET_RX_PAD + xdp_headroom;
825 headroom = vi->hdr_len + header_offset;
826 buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
827 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
828 xdp_page = xdp_linearize_page(rq, &num_buf, page,
829 offset, header_offset,
834 buf = page_address(xdp_page);
839 xdp_init_buff(&xdp, buflen, &rq->xdp_rxq);
840 xdp_prepare_buff(&xdp, buf + VIRTNET_RX_PAD + vi->hdr_len,
841 xdp_headroom, len, true);
842 orig_data = xdp.data;
843 act = bpf_prog_run_xdp(xdp_prog, &xdp);
844 stats->xdp_packets++;
848 /* Recalculate length in case bpf program changed it */
849 delta = orig_data - xdp.data;
850 len = xdp.data_end - xdp.data;
851 metasize = xdp.data - xdp.data_meta;
855 xdpf = xdp_convert_buff_to_frame(&xdp);
858 err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
859 if (unlikely(!err)) {
860 xdp_return_frame_rx_napi(xdpf);
861 } else if (unlikely(err < 0)) {
862 trace_xdp_exception(vi->dev, xdp_prog, act);
865 *xdp_xmit |= VIRTIO_XDP_TX;
869 stats->xdp_redirects++;
870 err = xdp_do_redirect(dev, &xdp, xdp_prog);
873 *xdp_xmit |= VIRTIO_XDP_REDIR;
877 bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
880 trace_xdp_exception(vi->dev, xdp_prog, act);
889 skb = build_skb(buf, buflen);
892 skb_reserve(skb, headroom - delta);
895 buf += header_offset;
896 memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
897 } /* keep zeroed vnet hdr since XDP is loaded */
900 skb_metadata_set(skb, metasize);
914 static struct sk_buff *receive_big(struct net_device *dev,
915 struct virtnet_info *vi,
916 struct receive_queue *rq,
919 struct virtnet_rq_stats *stats)
921 struct page *page = buf;
922 struct sk_buff *skb =
923 page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, true, 0, 0);
925 stats->bytes += len - vi->hdr_len;
933 give_pages(rq, page);
937 static struct sk_buff *receive_mergeable(struct net_device *dev,
938 struct virtnet_info *vi,
939 struct receive_queue *rq,
943 unsigned int *xdp_xmit,
944 struct virtnet_rq_stats *stats)
946 struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
947 u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
948 struct page *page = virt_to_head_page(buf);
949 int offset = buf - page_address(page);
950 struct sk_buff *head_skb, *curr_skb;
951 struct bpf_prog *xdp_prog;
952 unsigned int truesize = mergeable_ctx_to_truesize(ctx);
953 unsigned int headroom = mergeable_ctx_to_headroom(ctx);
954 unsigned int metasize = 0;
955 unsigned int frame_sz;
959 stats->bytes += len - vi->hdr_len;
961 if (unlikely(len > truesize)) {
962 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
963 dev->name, len, (unsigned long)ctx);
964 dev->stats.rx_length_errors++;
968 if (likely(!vi->xdp_enabled)) {
974 xdp_prog = rcu_dereference(rq->xdp_prog);
976 struct xdp_frame *xdpf;
977 struct page *xdp_page;
982 /* Transient failure which in theory could occur if
983 * in-flight packets from before XDP was enabled reach
984 * the receive path after XDP is loaded.
986 if (unlikely(hdr->hdr.gso_type))
989 /* Buffers with headroom use PAGE_SIZE as alloc size,
990 * see add_recvbuf_mergeable() + get_mergeable_buf_len()
992 frame_sz = headroom ? PAGE_SIZE : truesize;
994 /* This happens when rx buffer size is underestimated
995 * or headroom is not enough because of the buffer
996 * was refilled before XDP is set. This should only
997 * happen for the first several packets, so we don't
998 * care much about its performance.
1000 if (unlikely(num_buf > 1 ||
1001 headroom < virtnet_get_headroom(vi))) {
1002 /* linearize data for XDP */
1003 xdp_page = xdp_linearize_page(rq, &num_buf,
1005 VIRTIO_XDP_HEADROOM,
1007 frame_sz = PAGE_SIZE;
1011 offset = VIRTIO_XDP_HEADROOM;
1016 /* Allow consuming headroom but reserve enough space to push
1017 * the descriptor on if we get an XDP_TX return code.
1019 data = page_address(xdp_page) + offset;
1020 xdp_init_buff(&xdp, frame_sz - vi->hdr_len, &rq->xdp_rxq);
1021 xdp_prepare_buff(&xdp, data - VIRTIO_XDP_HEADROOM + vi->hdr_len,
1022 VIRTIO_XDP_HEADROOM, len - vi->hdr_len, true);
1024 act = bpf_prog_run_xdp(xdp_prog, &xdp);
1025 stats->xdp_packets++;
1029 metasize = xdp.data - xdp.data_meta;
1031 /* recalculate offset to account for any header
1032 * adjustments and minus the metasize to copy the
1033 * metadata in page_to_skb(). Note other cases do not
1034 * build an skb and avoid using offset
1036 offset = xdp.data - page_address(xdp_page) -
1037 vi->hdr_len - metasize;
1039 /* recalculate len if xdp.data, xdp.data_end or
1040 * xdp.data_meta were adjusted
1042 len = xdp.data_end - xdp.data + vi->hdr_len + metasize;
1044 /* recalculate headroom if xdp.data or xdp_data_meta
1045 * were adjusted, note that offset should always point
1046 * to the start of the reserved bytes for virtio_net
1047 * header which are followed by xdp.data, that means
1048 * that offset is equal to the headroom (when buf is
1049 * starting at the beginning of the page, otherwise
1050 * there is a base offset inside the page) but it's used
1051 * with a different starting point (buf start) than
1052 * xdp.data (buf start + vnet hdr size). If xdp.data or
1053 * data_meta were adjusted by the xdp prog then the
1054 * headroom size has changed and so has the offset, we
1055 * can use data_hard_start, which points at buf start +
1056 * vnet hdr size, to calculate the new headroom and use
1057 * it later to compute buf start in page_to_skb()
1059 headroom = xdp.data - xdp.data_hard_start - metasize;
1061 /* We can only create skb based on xdp_page. */
1062 if (unlikely(xdp_page != page)) {
1065 head_skb = page_to_skb(vi, rq, xdp_page, offset,
1066 len, PAGE_SIZE, false,
1074 xdpf = xdp_convert_buff_to_frame(&xdp);
1075 if (unlikely(!xdpf)) {
1076 if (unlikely(xdp_page != page))
1080 err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
1081 if (unlikely(!err)) {
1082 xdp_return_frame_rx_napi(xdpf);
1083 } else if (unlikely(err < 0)) {
1084 trace_xdp_exception(vi->dev, xdp_prog, act);
1085 if (unlikely(xdp_page != page))
1089 *xdp_xmit |= VIRTIO_XDP_TX;
1090 if (unlikely(xdp_page != page))
1095 stats->xdp_redirects++;
1096 err = xdp_do_redirect(dev, &xdp, xdp_prog);
1098 if (unlikely(xdp_page != page))
1102 *xdp_xmit |= VIRTIO_XDP_REDIR;
1103 if (unlikely(xdp_page != page))
1108 bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
1111 trace_xdp_exception(vi->dev, xdp_prog, act);
1114 if (unlikely(xdp_page != page))
1115 __free_pages(xdp_page, 0);
1122 head_skb = page_to_skb(vi, rq, page, offset, len, truesize, !xdp_prog,
1123 metasize, headroom);
1124 curr_skb = head_skb;
1126 if (unlikely(!curr_skb))
1131 buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1132 if (unlikely(!buf)) {
1133 pr_debug("%s: rx error: %d buffers out of %d missing\n",
1135 virtio16_to_cpu(vi->vdev,
1137 dev->stats.rx_length_errors++;
1141 stats->bytes += len;
1142 page = virt_to_head_page(buf);
1144 truesize = mergeable_ctx_to_truesize(ctx);
1145 if (unlikely(len > truesize)) {
1146 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1147 dev->name, len, (unsigned long)ctx);
1148 dev->stats.rx_length_errors++;
1152 num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1153 if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1154 struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1156 if (unlikely(!nskb))
1158 if (curr_skb == head_skb)
1159 skb_shinfo(curr_skb)->frag_list = nskb;
1161 curr_skb->next = nskb;
1163 head_skb->truesize += nskb->truesize;
1166 if (curr_skb != head_skb) {
1167 head_skb->data_len += len;
1168 head_skb->len += len;
1169 head_skb->truesize += truesize;
1171 offset = buf - page_address(page);
1172 if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1174 skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1177 skb_add_rx_frag(curr_skb, num_skb_frags, page,
1178 offset, len, truesize);
1182 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1190 while (num_buf-- > 1) {
1191 buf = virtqueue_get_buf(rq->vq, &len);
1192 if (unlikely(!buf)) {
1193 pr_debug("%s: rx error: %d buffers missing\n",
1194 dev->name, num_buf);
1195 dev->stats.rx_length_errors++;
1198 stats->bytes += len;
1199 page = virt_to_head_page(buf);
1204 dev_kfree_skb(head_skb);
1209 static void virtio_skb_set_hash(const struct virtio_net_hdr_v1_hash *hdr_hash,
1210 struct sk_buff *skb)
1212 enum pkt_hash_types rss_hash_type;
1214 if (!hdr_hash || !skb)
1217 switch (__le16_to_cpu(hdr_hash->hash_report)) {
1218 case VIRTIO_NET_HASH_REPORT_TCPv4:
1219 case VIRTIO_NET_HASH_REPORT_UDPv4:
1220 case VIRTIO_NET_HASH_REPORT_TCPv6:
1221 case VIRTIO_NET_HASH_REPORT_UDPv6:
1222 case VIRTIO_NET_HASH_REPORT_TCPv6_EX:
1223 case VIRTIO_NET_HASH_REPORT_UDPv6_EX:
1224 rss_hash_type = PKT_HASH_TYPE_L4;
1226 case VIRTIO_NET_HASH_REPORT_IPv4:
1227 case VIRTIO_NET_HASH_REPORT_IPv6:
1228 case VIRTIO_NET_HASH_REPORT_IPv6_EX:
1229 rss_hash_type = PKT_HASH_TYPE_L3;
1231 case VIRTIO_NET_HASH_REPORT_NONE:
1233 rss_hash_type = PKT_HASH_TYPE_NONE;
1235 skb_set_hash(skb, __le32_to_cpu(hdr_hash->hash_value), rss_hash_type);
1238 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1239 void *buf, unsigned int len, void **ctx,
1240 unsigned int *xdp_xmit,
1241 struct virtnet_rq_stats *stats)
1243 struct net_device *dev = vi->dev;
1244 struct sk_buff *skb;
1245 struct virtio_net_hdr_mrg_rxbuf *hdr;
1247 if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1248 pr_debug("%s: short packet %i\n", dev->name, len);
1249 dev->stats.rx_length_errors++;
1250 if (vi->mergeable_rx_bufs) {
1251 put_page(virt_to_head_page(buf));
1252 } else if (vi->big_packets) {
1253 give_pages(rq, buf);
1255 put_page(virt_to_head_page(buf));
1260 if (vi->mergeable_rx_bufs)
1261 skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1263 else if (vi->big_packets)
1264 skb = receive_big(dev, vi, rq, buf, len, stats);
1266 skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1271 hdr = skb_vnet_hdr(skb);
1272 if (dev->features & NETIF_F_RXHASH && vi->has_rss_hash_report)
1273 virtio_skb_set_hash((const struct virtio_net_hdr_v1_hash *)hdr, skb);
1275 if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
1276 skb->ip_summed = CHECKSUM_UNNECESSARY;
1278 if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1279 virtio_is_little_endian(vi->vdev))) {
1280 net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1281 dev->name, hdr->hdr.gso_type,
1286 skb_record_rx_queue(skb, vq2rxq(rq->vq));
1287 skb->protocol = eth_type_trans(skb, dev);
1288 pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1289 ntohs(skb->protocol), skb->len, skb->pkt_type);
1291 napi_gro_receive(&rq->napi, skb);
1295 dev->stats.rx_frame_errors++;
1299 /* Unlike mergeable buffers, all buffers are allocated to the
1300 * same size, except for the headroom. For this reason we do
1301 * not need to use mergeable_len_to_ctx here - it is enough
1302 * to store the headroom as the context ignoring the truesize.
1304 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1307 struct page_frag *alloc_frag = &rq->alloc_frag;
1309 unsigned int xdp_headroom = virtnet_get_headroom(vi);
1310 void *ctx = (void *)(unsigned long)xdp_headroom;
1311 int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1314 len = SKB_DATA_ALIGN(len) +
1315 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1316 if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
1319 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1320 get_page(alloc_frag->page);
1321 alloc_frag->offset += len;
1322 sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1323 vi->hdr_len + GOOD_PACKET_LEN);
1324 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1326 put_page(virt_to_head_page(buf));
1330 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1333 struct page *first, *list = NULL;
1337 sg_init_table(rq->sg, vi->big_packets_num_skbfrags + 2);
1339 /* page in rq->sg[vi->big_packets_num_skbfrags + 1] is list tail */
1340 for (i = vi->big_packets_num_skbfrags + 1; i > 1; --i) {
1341 first = get_a_page(rq, gfp);
1344 give_pages(rq, list);
1347 sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1349 /* chain new page in list head to match sg */
1350 first->private = (unsigned long)list;
1354 first = get_a_page(rq, gfp);
1356 give_pages(rq, list);
1359 p = page_address(first);
1361 /* rq->sg[0], rq->sg[1] share the same page */
1362 /* a separated rq->sg[0] for header - required in case !any_header_sg */
1363 sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1365 /* rq->sg[1] for data packet, from offset */
1366 offset = sizeof(struct padded_vnet_hdr);
1367 sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1369 /* chain first in list head */
1370 first->private = (unsigned long)list;
1371 err = virtqueue_add_inbuf(rq->vq, rq->sg, vi->big_packets_num_skbfrags + 2,
1374 give_pages(rq, first);
1379 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1380 struct ewma_pkt_len *avg_pkt_len,
1383 struct virtnet_info *vi = rq->vq->vdev->priv;
1384 const size_t hdr_len = vi->hdr_len;
1388 return PAGE_SIZE - room;
1390 len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1391 rq->min_buf_len, PAGE_SIZE - hdr_len);
1393 return ALIGN(len, L1_CACHE_BYTES);
1396 static int add_recvbuf_mergeable(struct virtnet_info *vi,
1397 struct receive_queue *rq, gfp_t gfp)
1399 struct page_frag *alloc_frag = &rq->alloc_frag;
1400 unsigned int headroom = virtnet_get_headroom(vi);
1401 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1402 unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1406 unsigned int len, hole;
1408 /* Extra tailroom is needed to satisfy XDP's assumption. This
1409 * means rx frags coalescing won't work, but consider we've
1410 * disabled GSO for XDP, it won't be a big issue.
1412 len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1413 if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
1416 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1417 buf += headroom; /* advance address leaving hole at front of pkt */
1418 get_page(alloc_frag->page);
1419 alloc_frag->offset += len + room;
1420 hole = alloc_frag->size - alloc_frag->offset;
1421 if (hole < len + room) {
1422 /* To avoid internal fragmentation, if there is very likely not
1423 * enough space for another buffer, add the remaining space to
1424 * the current buffer.
1427 alloc_frag->offset += hole;
1430 sg_init_one(rq->sg, buf, len);
1431 ctx = mergeable_len_to_ctx(len, headroom);
1432 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1434 put_page(virt_to_head_page(buf));
1440 * Returns false if we couldn't fill entirely (OOM).
1442 * Normally run in the receive path, but can also be run from ndo_open
1443 * before we're receiving packets, or from refill_work which is
1444 * careful to disable receiving (using napi_disable).
1446 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1453 if (vi->mergeable_rx_bufs)
1454 err = add_recvbuf_mergeable(vi, rq, gfp);
1455 else if (vi->big_packets)
1456 err = add_recvbuf_big(vi, rq, gfp);
1458 err = add_recvbuf_small(vi, rq, gfp);
1460 oom = err == -ENOMEM;
1463 } while (rq->vq->num_free);
1464 if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
1465 unsigned long flags;
1467 flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1469 u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1475 static void skb_recv_done(struct virtqueue *rvq)
1477 struct virtnet_info *vi = rvq->vdev->priv;
1478 struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1480 virtqueue_napi_schedule(&rq->napi, rvq);
1483 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
1487 /* If all buffers were filled by other side before we napi_enabled, we
1488 * won't get another interrupt, so process any outstanding packets now.
1489 * Call local_bh_enable after to trigger softIRQ processing.
1492 virtqueue_napi_schedule(napi, vq);
1496 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1497 struct virtqueue *vq,
1498 struct napi_struct *napi)
1503 /* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1504 * enable the feature if this is likely affine with the transmit path.
1506 if (!vi->affinity_hint_set) {
1511 return virtnet_napi_enable(vq, napi);
1514 static void virtnet_napi_tx_disable(struct napi_struct *napi)
1520 static void refill_work(struct work_struct *work)
1522 struct virtnet_info *vi =
1523 container_of(work, struct virtnet_info, refill.work);
1527 for (i = 0; i < vi->curr_queue_pairs; i++) {
1528 struct receive_queue *rq = &vi->rq[i];
1530 napi_disable(&rq->napi);
1531 still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1532 virtnet_napi_enable(rq->vq, &rq->napi);
1534 /* In theory, this can happen: if we don't get any buffers in
1535 * we will *never* try to fill again.
1538 schedule_delayed_work(&vi->refill, HZ/2);
1542 static int virtnet_receive(struct receive_queue *rq, int budget,
1543 unsigned int *xdp_xmit)
1545 struct virtnet_info *vi = rq->vq->vdev->priv;
1546 struct virtnet_rq_stats stats = {};
1551 if (!vi->big_packets || vi->mergeable_rx_bufs) {
1554 while (stats.packets < budget &&
1555 (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1556 receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1560 while (stats.packets < budget &&
1561 (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1562 receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1567 if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1568 if (!try_fill_recv(vi, rq, GFP_ATOMIC)) {
1569 spin_lock(&vi->refill_lock);
1570 if (vi->refill_enabled)
1571 schedule_delayed_work(&vi->refill, 0);
1572 spin_unlock(&vi->refill_lock);
1576 u64_stats_update_begin(&rq->stats.syncp);
1577 for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1578 size_t offset = virtnet_rq_stats_desc[i].offset;
1581 item = (u64 *)((u8 *)&rq->stats + offset);
1582 *item += *(u64 *)((u8 *)&stats + offset);
1584 u64_stats_update_end(&rq->stats.syncp);
1586 return stats.packets;
1589 static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
1592 unsigned int packets = 0;
1593 unsigned int bytes = 0;
1596 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
1597 if (likely(!is_xdp_frame(ptr))) {
1598 struct sk_buff *skb = ptr;
1600 pr_debug("Sent skb %p\n", skb);
1603 napi_consume_skb(skb, in_napi);
1605 struct xdp_frame *frame = ptr_to_xdp(ptr);
1607 bytes += frame->len;
1608 xdp_return_frame(frame);
1613 /* Avoid overhead when no packets have been processed
1614 * happens when called speculatively from start_xmit.
1619 u64_stats_update_begin(&sq->stats.syncp);
1620 sq->stats.bytes += bytes;
1621 sq->stats.packets += packets;
1622 u64_stats_update_end(&sq->stats.syncp);
1625 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
1627 if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
1629 else if (q < vi->curr_queue_pairs)
1635 static void virtnet_poll_cleantx(struct receive_queue *rq)
1637 struct virtnet_info *vi = rq->vq->vdev->priv;
1638 unsigned int index = vq2rxq(rq->vq);
1639 struct send_queue *sq = &vi->sq[index];
1640 struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
1642 if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
1645 if (__netif_tx_trylock(txq)) {
1647 __netif_tx_unlock(txq);
1652 virtqueue_disable_cb(sq->vq);
1653 free_old_xmit_skbs(sq, true);
1654 } while (unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1656 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1657 netif_tx_wake_queue(txq);
1659 __netif_tx_unlock(txq);
1663 static int virtnet_poll(struct napi_struct *napi, int budget)
1665 struct receive_queue *rq =
1666 container_of(napi, struct receive_queue, napi);
1667 struct virtnet_info *vi = rq->vq->vdev->priv;
1668 struct send_queue *sq;
1669 unsigned int received;
1670 unsigned int xdp_xmit = 0;
1672 virtnet_poll_cleantx(rq);
1674 received = virtnet_receive(rq, budget, &xdp_xmit);
1676 /* Out of packets? */
1677 if (received < budget)
1678 virtqueue_napi_complete(napi, rq->vq, received);
1680 if (xdp_xmit & VIRTIO_XDP_REDIR)
1683 if (xdp_xmit & VIRTIO_XDP_TX) {
1684 sq = virtnet_xdp_get_sq(vi);
1685 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1686 u64_stats_update_begin(&sq->stats.syncp);
1688 u64_stats_update_end(&sq->stats.syncp);
1690 virtnet_xdp_put_sq(vi, sq);
1696 static int virtnet_open(struct net_device *dev)
1698 struct virtnet_info *vi = netdev_priv(dev);
1701 enable_delayed_refill(vi);
1703 for (i = 0; i < vi->max_queue_pairs; i++) {
1704 if (i < vi->curr_queue_pairs)
1705 /* Make sure we have some buffers: if oom use wq. */
1706 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1707 schedule_delayed_work(&vi->refill, 0);
1709 err = xdp_rxq_info_reg(&vi->rq[i].xdp_rxq, dev, i, vi->rq[i].napi.napi_id);
1713 err = xdp_rxq_info_reg_mem_model(&vi->rq[i].xdp_rxq,
1714 MEM_TYPE_PAGE_SHARED, NULL);
1716 xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1720 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1721 virtnet_napi_tx_enable(vi, vi->sq[i].vq, &vi->sq[i].napi);
1727 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1729 struct send_queue *sq = container_of(napi, struct send_queue, napi);
1730 struct virtnet_info *vi = sq->vq->vdev->priv;
1731 unsigned int index = vq2txq(sq->vq);
1732 struct netdev_queue *txq;
1736 if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
1737 /* We don't need to enable cb for XDP */
1738 napi_complete_done(napi, 0);
1742 txq = netdev_get_tx_queue(vi->dev, index);
1743 __netif_tx_lock(txq, raw_smp_processor_id());
1744 virtqueue_disable_cb(sq->vq);
1745 free_old_xmit_skbs(sq, true);
1747 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1748 netif_tx_wake_queue(txq);
1750 opaque = virtqueue_enable_cb_prepare(sq->vq);
1752 done = napi_complete_done(napi, 0);
1755 virtqueue_disable_cb(sq->vq);
1757 __netif_tx_unlock(txq);
1760 if (unlikely(virtqueue_poll(sq->vq, opaque))) {
1761 if (napi_schedule_prep(napi)) {
1762 __netif_tx_lock(txq, raw_smp_processor_id());
1763 virtqueue_disable_cb(sq->vq);
1764 __netif_tx_unlock(txq);
1765 __napi_schedule(napi);
1773 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1775 struct virtio_net_hdr_mrg_rxbuf *hdr;
1776 const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1777 struct virtnet_info *vi = sq->vq->vdev->priv;
1779 unsigned hdr_len = vi->hdr_len;
1782 pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1784 can_push = vi->any_header_sg &&
1785 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1786 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1787 /* Even if we can, don't push here yet as this would skew
1788 * csum_start offset below. */
1790 hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1792 hdr = skb_vnet_hdr(skb);
1794 if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1795 virtio_is_little_endian(vi->vdev), false,
1799 if (vi->mergeable_rx_bufs)
1800 hdr->num_buffers = 0;
1802 sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1804 __skb_push(skb, hdr_len);
1805 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1806 if (unlikely(num_sg < 0))
1808 /* Pull header back to avoid skew in tx bytes calculations. */
1809 __skb_pull(skb, hdr_len);
1811 sg_set_buf(sq->sg, hdr, hdr_len);
1812 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
1813 if (unlikely(num_sg < 0))
1817 return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1820 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1822 struct virtnet_info *vi = netdev_priv(dev);
1823 int qnum = skb_get_queue_mapping(skb);
1824 struct send_queue *sq = &vi->sq[qnum];
1826 struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1827 bool kick = !netdev_xmit_more();
1828 bool use_napi = sq->napi.weight;
1830 /* Free up any pending old buffers before queueing new ones. */
1833 virtqueue_disable_cb(sq->vq);
1835 free_old_xmit_skbs(sq, false);
1837 } while (use_napi && kick &&
1838 unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1840 /* timestamp packet in software */
1841 skb_tx_timestamp(skb);
1843 /* Try to transmit */
1844 err = xmit_skb(sq, skb);
1846 /* This should not happen! */
1847 if (unlikely(err)) {
1848 dev->stats.tx_fifo_errors++;
1849 if (net_ratelimit())
1851 "Unexpected TXQ (%d) queue failure: %d\n",
1853 dev->stats.tx_dropped++;
1854 dev_kfree_skb_any(skb);
1855 return NETDEV_TX_OK;
1858 /* Don't wait up for transmitted skbs to be freed. */
1864 /* If running out of space, stop queue to avoid getting packets that we
1865 * are then unable to transmit.
1866 * An alternative would be to force queuing layer to requeue the skb by
1867 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
1868 * returned in a normal path of operation: it means that driver is not
1869 * maintaining the TX queue stop/start state properly, and causes
1870 * the stack to do a non-trivial amount of useless work.
1871 * Since most packets only take 1 or 2 ring slots, stopping the queue
1872 * early means 16 slots are typically wasted.
1874 if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1875 netif_stop_subqueue(dev, qnum);
1877 unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1878 /* More just got used, free them then recheck. */
1879 free_old_xmit_skbs(sq, false);
1880 if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1881 netif_start_subqueue(dev, qnum);
1882 virtqueue_disable_cb(sq->vq);
1887 if (kick || netif_xmit_stopped(txq)) {
1888 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1889 u64_stats_update_begin(&sq->stats.syncp);
1891 u64_stats_update_end(&sq->stats.syncp);
1895 return NETDEV_TX_OK;
1898 static int virtnet_rx_resize(struct virtnet_info *vi,
1899 struct receive_queue *rq, u32 ring_num)
1901 bool running = netif_running(vi->dev);
1904 qindex = rq - vi->rq;
1907 napi_disable(&rq->napi);
1909 err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_free_unused_buf);
1911 netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
1913 if (!try_fill_recv(vi, rq, GFP_KERNEL))
1914 schedule_delayed_work(&vi->refill, 0);
1917 virtnet_napi_enable(rq->vq, &rq->napi);
1921 static int virtnet_tx_resize(struct virtnet_info *vi,
1922 struct send_queue *sq, u32 ring_num)
1924 bool running = netif_running(vi->dev);
1925 struct netdev_queue *txq;
1928 qindex = sq - vi->sq;
1931 virtnet_napi_tx_disable(&sq->napi);
1933 txq = netdev_get_tx_queue(vi->dev, qindex);
1935 /* 1. wait all ximt complete
1936 * 2. fix the race of netif_stop_subqueue() vs netif_start_subqueue()
1938 __netif_tx_lock_bh(txq);
1940 /* Prevent rx poll from accessing sq. */
1943 /* Prevent the upper layer from trying to send packets. */
1944 netif_stop_subqueue(vi->dev, qindex);
1946 __netif_tx_unlock_bh(txq);
1948 err = virtqueue_resize(sq->vq, ring_num, virtnet_sq_free_unused_buf);
1950 netdev_err(vi->dev, "resize tx fail: tx queue index: %d err: %d\n", qindex, err);
1952 __netif_tx_lock_bh(txq);
1954 netif_tx_wake_queue(txq);
1955 __netif_tx_unlock_bh(txq);
1958 virtnet_napi_tx_enable(vi, sq->vq, &sq->napi);
1963 * Send command via the control virtqueue and check status. Commands
1964 * supported by the hypervisor, as indicated by feature bits, should
1965 * never fail unless improperly formatted.
1967 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1968 struct scatterlist *out)
1970 struct scatterlist *sgs[4], hdr, stat;
1971 unsigned out_num = 0, tmp;
1974 /* Caller should know better */
1975 BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1977 vi->ctrl->status = ~0;
1978 vi->ctrl->hdr.class = class;
1979 vi->ctrl->hdr.cmd = cmd;
1981 sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
1982 sgs[out_num++] = &hdr;
1985 sgs[out_num++] = out;
1987 /* Add return status. */
1988 sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
1989 sgs[out_num] = &stat;
1991 BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1992 ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1994 dev_warn(&vi->vdev->dev,
1995 "Failed to add sgs for command vq: %d\n.", ret);
1999 if (unlikely(!virtqueue_kick(vi->cvq)))
2000 return vi->ctrl->status == VIRTIO_NET_OK;
2002 /* Spin for a response, the kick causes an ioport write, trapping
2003 * into the hypervisor, so the request should be handled immediately.
2005 while (!virtqueue_get_buf(vi->cvq, &tmp) &&
2006 !virtqueue_is_broken(vi->cvq))
2009 return vi->ctrl->status == VIRTIO_NET_OK;
2012 static int virtnet_set_mac_address(struct net_device *dev, void *p)
2014 struct virtnet_info *vi = netdev_priv(dev);
2015 struct virtio_device *vdev = vi->vdev;
2017 struct sockaddr *addr;
2018 struct scatterlist sg;
2020 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2023 addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
2027 ret = eth_prepare_mac_addr_change(dev, addr);
2031 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
2032 sg_init_one(&sg, addr->sa_data, dev->addr_len);
2033 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2034 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
2035 dev_warn(&vdev->dev,
2036 "Failed to set mac address by vq command.\n");
2040 } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
2041 !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2044 /* Naturally, this has an atomicity problem. */
2045 for (i = 0; i < dev->addr_len; i++)
2046 virtio_cwrite8(vdev,
2047 offsetof(struct virtio_net_config, mac) +
2048 i, addr->sa_data[i]);
2051 eth_commit_mac_addr_change(dev, p);
2059 static void virtnet_stats(struct net_device *dev,
2060 struct rtnl_link_stats64 *tot)
2062 struct virtnet_info *vi = netdev_priv(dev);
2066 for (i = 0; i < vi->max_queue_pairs; i++) {
2067 u64 tpackets, tbytes, terrors, rpackets, rbytes, rdrops;
2068 struct receive_queue *rq = &vi->rq[i];
2069 struct send_queue *sq = &vi->sq[i];
2072 start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2073 tpackets = sq->stats.packets;
2074 tbytes = sq->stats.bytes;
2075 terrors = sq->stats.tx_timeouts;
2076 } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2079 start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2080 rpackets = rq->stats.packets;
2081 rbytes = rq->stats.bytes;
2082 rdrops = rq->stats.drops;
2083 } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2085 tot->rx_packets += rpackets;
2086 tot->tx_packets += tpackets;
2087 tot->rx_bytes += rbytes;
2088 tot->tx_bytes += tbytes;
2089 tot->rx_dropped += rdrops;
2090 tot->tx_errors += terrors;
2093 tot->tx_dropped = dev->stats.tx_dropped;
2094 tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
2095 tot->rx_length_errors = dev->stats.rx_length_errors;
2096 tot->rx_frame_errors = dev->stats.rx_frame_errors;
2099 static void virtnet_ack_link_announce(struct virtnet_info *vi)
2102 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
2103 VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
2104 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
2108 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2110 struct scatterlist sg;
2111 struct net_device *dev = vi->dev;
2113 if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
2116 vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
2117 sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
2119 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2120 VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
2121 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
2125 vi->curr_queue_pairs = queue_pairs;
2126 /* virtnet_open() will refill when device is going to up. */
2127 if (dev->flags & IFF_UP)
2128 schedule_delayed_work(&vi->refill, 0);
2134 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2139 err = _virtnet_set_queues(vi, queue_pairs);
2144 static int virtnet_close(struct net_device *dev)
2146 struct virtnet_info *vi = netdev_priv(dev);
2149 /* Make sure NAPI doesn't schedule refill work */
2150 disable_delayed_refill(vi);
2151 /* Make sure refill_work doesn't re-enable napi! */
2152 cancel_delayed_work_sync(&vi->refill);
2154 for (i = 0; i < vi->max_queue_pairs; i++) {
2155 xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
2156 napi_disable(&vi->rq[i].napi);
2157 virtnet_napi_tx_disable(&vi->sq[i].napi);
2163 static void virtnet_set_rx_mode(struct net_device *dev)
2165 struct virtnet_info *vi = netdev_priv(dev);
2166 struct scatterlist sg[2];
2167 struct virtio_net_ctrl_mac *mac_data;
2168 struct netdev_hw_addr *ha;
2174 /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
2175 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
2178 vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
2179 vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
2181 sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
2183 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2184 VIRTIO_NET_CTRL_RX_PROMISC, sg))
2185 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
2186 vi->ctrl->promisc ? "en" : "dis");
2188 sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
2190 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2191 VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
2192 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
2193 vi->ctrl->allmulti ? "en" : "dis");
2195 uc_count = netdev_uc_count(dev);
2196 mc_count = netdev_mc_count(dev);
2197 /* MAC filter - use one buffer for both lists */
2198 buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
2199 (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
2204 sg_init_table(sg, 2);
2206 /* Store the unicast list and count in the front of the buffer */
2207 mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2209 netdev_for_each_uc_addr(ha, dev)
2210 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2212 sg_set_buf(&sg[0], mac_data,
2213 sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2215 /* multicast list and count fill the end */
2216 mac_data = (void *)&mac_data->macs[uc_count][0];
2218 mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2220 netdev_for_each_mc_addr(ha, dev)
2221 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2223 sg_set_buf(&sg[1], mac_data,
2224 sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2226 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2227 VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2228 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2233 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
2234 __be16 proto, u16 vid)
2236 struct virtnet_info *vi = netdev_priv(dev);
2237 struct scatterlist sg;
2239 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2240 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2242 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2243 VIRTIO_NET_CTRL_VLAN_ADD, &sg))
2244 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
2248 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
2249 __be16 proto, u16 vid)
2251 struct virtnet_info *vi = netdev_priv(dev);
2252 struct scatterlist sg;
2254 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2255 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2257 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2258 VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2259 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2263 static void virtnet_clean_affinity(struct virtnet_info *vi)
2267 if (vi->affinity_hint_set) {
2268 for (i = 0; i < vi->max_queue_pairs; i++) {
2269 virtqueue_set_affinity(vi->rq[i].vq, NULL);
2270 virtqueue_set_affinity(vi->sq[i].vq, NULL);
2273 vi->affinity_hint_set = false;
2277 static void virtnet_set_affinity(struct virtnet_info *vi)
2286 if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2287 virtnet_clean_affinity(vi);
2291 num_cpu = num_online_cpus();
2292 stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2293 stragglers = num_cpu >= vi->curr_queue_pairs ?
2294 num_cpu % vi->curr_queue_pairs :
2296 cpu = cpumask_first(cpu_online_mask);
2298 for (i = 0; i < vi->curr_queue_pairs; i++) {
2299 group_size = stride + (i < stragglers ? 1 : 0);
2301 for (j = 0; j < group_size; j++) {
2302 cpumask_set_cpu(cpu, mask);
2303 cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2306 virtqueue_set_affinity(vi->rq[i].vq, mask);
2307 virtqueue_set_affinity(vi->sq[i].vq, mask);
2308 __netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2309 cpumask_clear(mask);
2312 vi->affinity_hint_set = true;
2313 free_cpumask_var(mask);
2316 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2318 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2320 virtnet_set_affinity(vi);
2324 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2326 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2328 virtnet_set_affinity(vi);
2332 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2334 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2337 virtnet_clean_affinity(vi);
2341 static enum cpuhp_state virtionet_online;
2343 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2347 ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2350 ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2354 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2358 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2360 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2361 cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2365 static void virtnet_get_ringparam(struct net_device *dev,
2366 struct ethtool_ringparam *ring,
2367 struct kernel_ethtool_ringparam *kernel_ring,
2368 struct netlink_ext_ack *extack)
2370 struct virtnet_info *vi = netdev_priv(dev);
2372 ring->rx_max_pending = vi->rq[0].vq->num_max;
2373 ring->tx_max_pending = vi->sq[0].vq->num_max;
2374 ring->rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2375 ring->tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2378 static int virtnet_set_ringparam(struct net_device *dev,
2379 struct ethtool_ringparam *ring,
2380 struct kernel_ethtool_ringparam *kernel_ring,
2381 struct netlink_ext_ack *extack)
2383 struct virtnet_info *vi = netdev_priv(dev);
2384 u32 rx_pending, tx_pending;
2385 struct receive_queue *rq;
2386 struct send_queue *sq;
2389 if (ring->rx_mini_pending || ring->rx_jumbo_pending)
2392 rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2393 tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2395 if (ring->rx_pending == rx_pending &&
2396 ring->tx_pending == tx_pending)
2399 if (ring->rx_pending > vi->rq[0].vq->num_max)
2402 if (ring->tx_pending > vi->sq[0].vq->num_max)
2405 for (i = 0; i < vi->max_queue_pairs; i++) {
2409 if (ring->tx_pending != tx_pending) {
2410 err = virtnet_tx_resize(vi, sq, ring->tx_pending);
2415 if (ring->rx_pending != rx_pending) {
2416 err = virtnet_rx_resize(vi, rq, ring->rx_pending);
2425 static bool virtnet_commit_rss_command(struct virtnet_info *vi)
2427 struct net_device *dev = vi->dev;
2428 struct scatterlist sgs[4];
2429 unsigned int sg_buf_size;
2432 sg_init_table(sgs, 4);
2434 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, indirection_table);
2435 sg_set_buf(&sgs[0], &vi->ctrl->rss, sg_buf_size);
2437 sg_buf_size = sizeof(uint16_t) * (vi->ctrl->rss.indirection_table_mask + 1);
2438 sg_set_buf(&sgs[1], vi->ctrl->rss.indirection_table, sg_buf_size);
2440 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, key)
2441 - offsetof(struct virtio_net_ctrl_rss, max_tx_vq);
2442 sg_set_buf(&sgs[2], &vi->ctrl->rss.max_tx_vq, sg_buf_size);
2444 sg_buf_size = vi->rss_key_size;
2445 sg_set_buf(&sgs[3], vi->ctrl->rss.key, sg_buf_size);
2447 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2448 vi->has_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG
2449 : VIRTIO_NET_CTRL_MQ_HASH_CONFIG, sgs)) {
2450 dev_warn(&dev->dev, "VIRTIONET issue with committing RSS sgs\n");
2456 static void virtnet_init_default_rss(struct virtnet_info *vi)
2461 vi->ctrl->rss.hash_types = vi->rss_hash_types_supported;
2462 vi->rss_hash_types_saved = vi->rss_hash_types_supported;
2463 vi->ctrl->rss.indirection_table_mask = vi->rss_indir_table_size
2464 ? vi->rss_indir_table_size - 1 : 0;
2465 vi->ctrl->rss.unclassified_queue = 0;
2467 for (; i < vi->rss_indir_table_size; ++i) {
2468 indir_val = ethtool_rxfh_indir_default(i, vi->curr_queue_pairs);
2469 vi->ctrl->rss.indirection_table[i] = indir_val;
2472 vi->ctrl->rss.max_tx_vq = vi->curr_queue_pairs;
2473 vi->ctrl->rss.hash_key_length = vi->rss_key_size;
2475 netdev_rss_key_fill(vi->ctrl->rss.key, vi->rss_key_size);
2478 static void virtnet_get_hashflow(const struct virtnet_info *vi, struct ethtool_rxnfc *info)
2481 switch (info->flow_type) {
2483 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
2484 info->data = RXH_IP_SRC | RXH_IP_DST |
2485 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2486 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2487 info->data = RXH_IP_SRC | RXH_IP_DST;
2491 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
2492 info->data = RXH_IP_SRC | RXH_IP_DST |
2493 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2494 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2495 info->data = RXH_IP_SRC | RXH_IP_DST;
2499 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
2500 info->data = RXH_IP_SRC | RXH_IP_DST |
2501 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2502 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2503 info->data = RXH_IP_SRC | RXH_IP_DST;
2507 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
2508 info->data = RXH_IP_SRC | RXH_IP_DST |
2509 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2510 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2511 info->data = RXH_IP_SRC | RXH_IP_DST;
2515 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4)
2516 info->data = RXH_IP_SRC | RXH_IP_DST;
2520 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6)
2521 info->data = RXH_IP_SRC | RXH_IP_DST;
2530 static bool virtnet_set_hashflow(struct virtnet_info *vi, struct ethtool_rxnfc *info)
2532 u32 new_hashtypes = vi->rss_hash_types_saved;
2533 bool is_disable = info->data & RXH_DISCARD;
2534 bool is_l4 = info->data == (RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3);
2536 /* supports only 'sd', 'sdfn' and 'r' */
2537 if (!((info->data == (RXH_IP_SRC | RXH_IP_DST)) | is_l4 | is_disable))
2540 switch (info->flow_type) {
2542 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_TCPv4);
2544 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2545 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0);
2548 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_UDPv4);
2550 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2551 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0);
2554 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2556 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2559 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_TCPv6);
2561 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2562 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0);
2565 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_UDPv6);
2567 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2568 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0);
2571 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2573 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2576 /* unsupported flow */
2580 /* if unsupported hashtype was set */
2581 if (new_hashtypes != (new_hashtypes & vi->rss_hash_types_supported))
2584 if (new_hashtypes != vi->rss_hash_types_saved) {
2585 vi->rss_hash_types_saved = new_hashtypes;
2586 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
2587 if (vi->dev->features & NETIF_F_RXHASH)
2588 return virtnet_commit_rss_command(vi);
2594 static void virtnet_get_drvinfo(struct net_device *dev,
2595 struct ethtool_drvinfo *info)
2597 struct virtnet_info *vi = netdev_priv(dev);
2598 struct virtio_device *vdev = vi->vdev;
2600 strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2601 strscpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2602 strscpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2606 /* TODO: Eliminate OOO packets during switching */
2607 static int virtnet_set_channels(struct net_device *dev,
2608 struct ethtool_channels *channels)
2610 struct virtnet_info *vi = netdev_priv(dev);
2611 u16 queue_pairs = channels->combined_count;
2614 /* We don't support separate rx/tx channels.
2615 * We don't allow setting 'other' channels.
2617 if (channels->rx_count || channels->tx_count || channels->other_count)
2620 if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2623 /* For now we don't support modifying channels while XDP is loaded
2624 * also when XDP is loaded all RX queues have XDP programs so we only
2625 * need to check a single RX queue.
2627 if (vi->rq[0].xdp_prog)
2631 err = _virtnet_set_queues(vi, queue_pairs);
2636 virtnet_set_affinity(vi);
2639 netif_set_real_num_tx_queues(dev, queue_pairs);
2640 netif_set_real_num_rx_queues(dev, queue_pairs);
2645 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2647 struct virtnet_info *vi = netdev_priv(dev);
2651 switch (stringset) {
2653 for (i = 0; i < vi->curr_queue_pairs; i++) {
2654 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
2655 ethtool_sprintf(&p, "rx_queue_%u_%s", i,
2656 virtnet_rq_stats_desc[j].desc);
2659 for (i = 0; i < vi->curr_queue_pairs; i++) {
2660 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
2661 ethtool_sprintf(&p, "tx_queue_%u_%s", i,
2662 virtnet_sq_stats_desc[j].desc);
2668 static int virtnet_get_sset_count(struct net_device *dev, int sset)
2670 struct virtnet_info *vi = netdev_priv(dev);
2674 return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2675 VIRTNET_SQ_STATS_LEN);
2681 static void virtnet_get_ethtool_stats(struct net_device *dev,
2682 struct ethtool_stats *stats, u64 *data)
2684 struct virtnet_info *vi = netdev_priv(dev);
2685 unsigned int idx = 0, start, i, j;
2686 const u8 *stats_base;
2689 for (i = 0; i < vi->curr_queue_pairs; i++) {
2690 struct receive_queue *rq = &vi->rq[i];
2692 stats_base = (u8 *)&rq->stats;
2694 start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2695 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2696 offset = virtnet_rq_stats_desc[j].offset;
2697 data[idx + j] = *(u64 *)(stats_base + offset);
2699 } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2700 idx += VIRTNET_RQ_STATS_LEN;
2703 for (i = 0; i < vi->curr_queue_pairs; i++) {
2704 struct send_queue *sq = &vi->sq[i];
2706 stats_base = (u8 *)&sq->stats;
2708 start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2709 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2710 offset = virtnet_sq_stats_desc[j].offset;
2711 data[idx + j] = *(u64 *)(stats_base + offset);
2713 } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2714 idx += VIRTNET_SQ_STATS_LEN;
2718 static void virtnet_get_channels(struct net_device *dev,
2719 struct ethtool_channels *channels)
2721 struct virtnet_info *vi = netdev_priv(dev);
2723 channels->combined_count = vi->curr_queue_pairs;
2724 channels->max_combined = vi->max_queue_pairs;
2725 channels->max_other = 0;
2726 channels->rx_count = 0;
2727 channels->tx_count = 0;
2728 channels->other_count = 0;
2731 static int virtnet_set_link_ksettings(struct net_device *dev,
2732 const struct ethtool_link_ksettings *cmd)
2734 struct virtnet_info *vi = netdev_priv(dev);
2736 return ethtool_virtdev_set_link_ksettings(dev, cmd,
2737 &vi->speed, &vi->duplex);
2740 static int virtnet_get_link_ksettings(struct net_device *dev,
2741 struct ethtool_link_ksettings *cmd)
2743 struct virtnet_info *vi = netdev_priv(dev);
2745 cmd->base.speed = vi->speed;
2746 cmd->base.duplex = vi->duplex;
2747 cmd->base.port = PORT_OTHER;
2752 static int virtnet_send_notf_coal_cmds(struct virtnet_info *vi,
2753 struct ethtool_coalesce *ec)
2755 struct scatterlist sgs_tx, sgs_rx;
2756 struct virtio_net_ctrl_coal_tx coal_tx;
2757 struct virtio_net_ctrl_coal_rx coal_rx;
2759 coal_tx.tx_usecs = cpu_to_le32(ec->tx_coalesce_usecs);
2760 coal_tx.tx_max_packets = cpu_to_le32(ec->tx_max_coalesced_frames);
2761 sg_init_one(&sgs_tx, &coal_tx, sizeof(coal_tx));
2763 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2764 VIRTIO_NET_CTRL_NOTF_COAL_TX_SET,
2768 /* Save parameters */
2769 vi->tx_usecs = ec->tx_coalesce_usecs;
2770 vi->tx_max_packets = ec->tx_max_coalesced_frames;
2772 coal_rx.rx_usecs = cpu_to_le32(ec->rx_coalesce_usecs);
2773 coal_rx.rx_max_packets = cpu_to_le32(ec->rx_max_coalesced_frames);
2774 sg_init_one(&sgs_rx, &coal_rx, sizeof(coal_rx));
2776 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2777 VIRTIO_NET_CTRL_NOTF_COAL_RX_SET,
2781 /* Save parameters */
2782 vi->rx_usecs = ec->rx_coalesce_usecs;
2783 vi->rx_max_packets = ec->rx_max_coalesced_frames;
2788 static int virtnet_coal_params_supported(struct ethtool_coalesce *ec)
2790 /* usecs coalescing is supported only if VIRTIO_NET_F_NOTF_COAL
2791 * feature is negotiated.
2793 if (ec->rx_coalesce_usecs || ec->tx_coalesce_usecs)
2796 if (ec->tx_max_coalesced_frames > 1 ||
2797 ec->rx_max_coalesced_frames != 1)
2803 static int virtnet_set_coalesce(struct net_device *dev,
2804 struct ethtool_coalesce *ec,
2805 struct kernel_ethtool_coalesce *kernel_coal,
2806 struct netlink_ext_ack *extack)
2808 struct virtnet_info *vi = netdev_priv(dev);
2809 int ret, i, napi_weight;
2810 bool update_napi = false;
2812 /* Can't change NAPI weight if the link is up */
2813 napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
2814 if (napi_weight ^ vi->sq[0].napi.weight) {
2815 if (dev->flags & IFF_UP)
2821 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL))
2822 ret = virtnet_send_notf_coal_cmds(vi, ec);
2824 ret = virtnet_coal_params_supported(ec);
2830 for (i = 0; i < vi->max_queue_pairs; i++)
2831 vi->sq[i].napi.weight = napi_weight;
2837 static int virtnet_get_coalesce(struct net_device *dev,
2838 struct ethtool_coalesce *ec,
2839 struct kernel_ethtool_coalesce *kernel_coal,
2840 struct netlink_ext_ack *extack)
2842 struct virtnet_info *vi = netdev_priv(dev);
2844 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
2845 ec->rx_coalesce_usecs = vi->rx_usecs;
2846 ec->tx_coalesce_usecs = vi->tx_usecs;
2847 ec->tx_max_coalesced_frames = vi->tx_max_packets;
2848 ec->rx_max_coalesced_frames = vi->rx_max_packets;
2850 ec->rx_max_coalesced_frames = 1;
2852 if (vi->sq[0].napi.weight)
2853 ec->tx_max_coalesced_frames = 1;
2859 static void virtnet_init_settings(struct net_device *dev)
2861 struct virtnet_info *vi = netdev_priv(dev);
2863 vi->speed = SPEED_UNKNOWN;
2864 vi->duplex = DUPLEX_UNKNOWN;
2867 static void virtnet_update_settings(struct virtnet_info *vi)
2872 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
2875 virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
2877 if (ethtool_validate_speed(speed))
2880 virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
2882 if (ethtool_validate_duplex(duplex))
2883 vi->duplex = duplex;
2886 static u32 virtnet_get_rxfh_key_size(struct net_device *dev)
2888 return ((struct virtnet_info *)netdev_priv(dev))->rss_key_size;
2891 static u32 virtnet_get_rxfh_indir_size(struct net_device *dev)
2893 return ((struct virtnet_info *)netdev_priv(dev))->rss_indir_table_size;
2896 static int virtnet_get_rxfh(struct net_device *dev, u32 *indir, u8 *key, u8 *hfunc)
2898 struct virtnet_info *vi = netdev_priv(dev);
2902 for (i = 0; i < vi->rss_indir_table_size; ++i)
2903 indir[i] = vi->ctrl->rss.indirection_table[i];
2907 memcpy(key, vi->ctrl->rss.key, vi->rss_key_size);
2910 *hfunc = ETH_RSS_HASH_TOP;
2915 static int virtnet_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key, const u8 hfunc)
2917 struct virtnet_info *vi = netdev_priv(dev);
2920 if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
2924 for (i = 0; i < vi->rss_indir_table_size; ++i)
2925 vi->ctrl->rss.indirection_table[i] = indir[i];
2928 memcpy(vi->ctrl->rss.key, key, vi->rss_key_size);
2930 virtnet_commit_rss_command(vi);
2935 static int virtnet_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rule_locs)
2937 struct virtnet_info *vi = netdev_priv(dev);
2940 switch (info->cmd) {
2941 case ETHTOOL_GRXRINGS:
2942 info->data = vi->curr_queue_pairs;
2945 virtnet_get_hashflow(vi, info);
2954 static int virtnet_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info)
2956 struct virtnet_info *vi = netdev_priv(dev);
2959 switch (info->cmd) {
2961 if (!virtnet_set_hashflow(vi, info))
2972 static const struct ethtool_ops virtnet_ethtool_ops = {
2973 .supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES |
2974 ETHTOOL_COALESCE_USECS,
2975 .get_drvinfo = virtnet_get_drvinfo,
2976 .get_link = ethtool_op_get_link,
2977 .get_ringparam = virtnet_get_ringparam,
2978 .set_ringparam = virtnet_set_ringparam,
2979 .get_strings = virtnet_get_strings,
2980 .get_sset_count = virtnet_get_sset_count,
2981 .get_ethtool_stats = virtnet_get_ethtool_stats,
2982 .set_channels = virtnet_set_channels,
2983 .get_channels = virtnet_get_channels,
2984 .get_ts_info = ethtool_op_get_ts_info,
2985 .get_link_ksettings = virtnet_get_link_ksettings,
2986 .set_link_ksettings = virtnet_set_link_ksettings,
2987 .set_coalesce = virtnet_set_coalesce,
2988 .get_coalesce = virtnet_get_coalesce,
2989 .get_rxfh_key_size = virtnet_get_rxfh_key_size,
2990 .get_rxfh_indir_size = virtnet_get_rxfh_indir_size,
2991 .get_rxfh = virtnet_get_rxfh,
2992 .set_rxfh = virtnet_set_rxfh,
2993 .get_rxnfc = virtnet_get_rxnfc,
2994 .set_rxnfc = virtnet_set_rxnfc,
2997 static void virtnet_freeze_down(struct virtio_device *vdev)
2999 struct virtnet_info *vi = vdev->priv;
3001 /* Make sure no work handler is accessing the device */
3002 flush_work(&vi->config_work);
3004 netif_tx_lock_bh(vi->dev);
3005 netif_device_detach(vi->dev);
3006 netif_tx_unlock_bh(vi->dev);
3007 if (netif_running(vi->dev))
3008 virtnet_close(vi->dev);
3011 static int init_vqs(struct virtnet_info *vi);
3013 static int virtnet_restore_up(struct virtio_device *vdev)
3015 struct virtnet_info *vi = vdev->priv;
3022 virtio_device_ready(vdev);
3024 enable_delayed_refill(vi);
3026 if (netif_running(vi->dev)) {
3027 err = virtnet_open(vi->dev);
3032 netif_tx_lock_bh(vi->dev);
3033 netif_device_attach(vi->dev);
3034 netif_tx_unlock_bh(vi->dev);
3038 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
3040 struct scatterlist sg;
3041 vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
3043 sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
3045 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
3046 VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
3047 dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
3054 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
3058 if (!vi->guest_offloads)
3061 return virtnet_set_guest_offloads(vi, offloads);
3064 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
3066 u64 offloads = vi->guest_offloads;
3068 if (!vi->guest_offloads)
3071 return virtnet_set_guest_offloads(vi, offloads);
3074 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
3075 struct netlink_ext_ack *extack)
3077 unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
3078 struct virtnet_info *vi = netdev_priv(dev);
3079 struct bpf_prog *old_prog;
3080 u16 xdp_qp = 0, curr_qp;
3083 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
3084 && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3085 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3086 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3087 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3088 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM))) {
3089 NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
3093 if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
3094 NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
3098 if (dev->mtu > max_sz) {
3099 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
3100 netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
3104 curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
3106 xdp_qp = nr_cpu_ids;
3108 /* XDP requires extra queues for XDP_TX */
3109 if (curr_qp + xdp_qp > vi->max_queue_pairs) {
3110 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",
3111 curr_qp + xdp_qp, vi->max_queue_pairs);
3115 old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
3116 if (!prog && !old_prog)
3120 bpf_prog_add(prog, vi->max_queue_pairs - 1);
3122 /* Make sure NAPI is not using any XDP TX queues for RX. */
3123 if (netif_running(dev)) {
3124 for (i = 0; i < vi->max_queue_pairs; i++) {
3125 napi_disable(&vi->rq[i].napi);
3126 virtnet_napi_tx_disable(&vi->sq[i].napi);
3131 for (i = 0; i < vi->max_queue_pairs; i++) {
3132 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3134 virtnet_restore_guest_offloads(vi);
3139 err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
3142 netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
3143 vi->xdp_queue_pairs = xdp_qp;
3146 vi->xdp_enabled = true;
3147 for (i = 0; i < vi->max_queue_pairs; i++) {
3148 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3149 if (i == 0 && !old_prog)
3150 virtnet_clear_guest_offloads(vi);
3153 vi->xdp_enabled = false;
3156 for (i = 0; i < vi->max_queue_pairs; i++) {
3158 bpf_prog_put(old_prog);
3159 if (netif_running(dev)) {
3160 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3161 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3170 virtnet_clear_guest_offloads(vi);
3171 for (i = 0; i < vi->max_queue_pairs; i++)
3172 rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
3175 if (netif_running(dev)) {
3176 for (i = 0; i < vi->max_queue_pairs; i++) {
3177 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3178 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3183 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
3187 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
3189 switch (xdp->command) {
3190 case XDP_SETUP_PROG:
3191 return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
3197 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
3200 struct virtnet_info *vi = netdev_priv(dev);
3203 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
3206 ret = snprintf(buf, len, "sby");
3213 static int virtnet_set_features(struct net_device *dev,
3214 netdev_features_t features)
3216 struct virtnet_info *vi = netdev_priv(dev);
3220 if ((dev->features ^ features) & NETIF_F_GRO_HW) {
3221 if (vi->xdp_enabled)
3224 if (features & NETIF_F_GRO_HW)
3225 offloads = vi->guest_offloads_capable;
3227 offloads = vi->guest_offloads_capable &
3228 ~GUEST_OFFLOAD_GRO_HW_MASK;
3230 err = virtnet_set_guest_offloads(vi, offloads);
3233 vi->guest_offloads = offloads;
3236 if ((dev->features ^ features) & NETIF_F_RXHASH) {
3237 if (features & NETIF_F_RXHASH)
3238 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
3240 vi->ctrl->rss.hash_types = VIRTIO_NET_HASH_REPORT_NONE;
3242 if (!virtnet_commit_rss_command(vi))
3249 static void virtnet_tx_timeout(struct net_device *dev, unsigned int txqueue)
3251 struct virtnet_info *priv = netdev_priv(dev);
3252 struct send_queue *sq = &priv->sq[txqueue];
3253 struct netdev_queue *txq = netdev_get_tx_queue(dev, txqueue);
3255 u64_stats_update_begin(&sq->stats.syncp);
3256 sq->stats.tx_timeouts++;
3257 u64_stats_update_end(&sq->stats.syncp);
3259 netdev_err(dev, "TX timeout on queue: %u, sq: %s, vq: 0x%x, name: %s, %u usecs ago\n",
3260 txqueue, sq->name, sq->vq->index, sq->vq->name,
3261 jiffies_to_usecs(jiffies - READ_ONCE(txq->trans_start)));
3264 static const struct net_device_ops virtnet_netdev = {
3265 .ndo_open = virtnet_open,
3266 .ndo_stop = virtnet_close,
3267 .ndo_start_xmit = start_xmit,
3268 .ndo_validate_addr = eth_validate_addr,
3269 .ndo_set_mac_address = virtnet_set_mac_address,
3270 .ndo_set_rx_mode = virtnet_set_rx_mode,
3271 .ndo_get_stats64 = virtnet_stats,
3272 .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
3273 .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
3274 .ndo_bpf = virtnet_xdp,
3275 .ndo_xdp_xmit = virtnet_xdp_xmit,
3276 .ndo_features_check = passthru_features_check,
3277 .ndo_get_phys_port_name = virtnet_get_phys_port_name,
3278 .ndo_set_features = virtnet_set_features,
3279 .ndo_tx_timeout = virtnet_tx_timeout,
3282 static void virtnet_config_changed_work(struct work_struct *work)
3284 struct virtnet_info *vi =
3285 container_of(work, struct virtnet_info, config_work);
3288 if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
3289 struct virtio_net_config, status, &v) < 0)
3292 if (v & VIRTIO_NET_S_ANNOUNCE) {
3293 netdev_notify_peers(vi->dev);
3294 virtnet_ack_link_announce(vi);
3297 /* Ignore unknown (future) status bits */
3298 v &= VIRTIO_NET_S_LINK_UP;
3300 if (vi->status == v)
3305 if (vi->status & VIRTIO_NET_S_LINK_UP) {
3306 virtnet_update_settings(vi);
3307 netif_carrier_on(vi->dev);
3308 netif_tx_wake_all_queues(vi->dev);
3310 netif_carrier_off(vi->dev);
3311 netif_tx_stop_all_queues(vi->dev);
3315 static void virtnet_config_changed(struct virtio_device *vdev)
3317 struct virtnet_info *vi = vdev->priv;
3319 schedule_work(&vi->config_work);
3322 static void virtnet_free_queues(struct virtnet_info *vi)
3326 for (i = 0; i < vi->max_queue_pairs; i++) {
3327 __netif_napi_del(&vi->rq[i].napi);
3328 __netif_napi_del(&vi->sq[i].napi);
3331 /* We called __netif_napi_del(),
3332 * we need to respect an RCU grace period before freeing vi->rq
3341 static void _free_receive_bufs(struct virtnet_info *vi)
3343 struct bpf_prog *old_prog;
3346 for (i = 0; i < vi->max_queue_pairs; i++) {
3347 while (vi->rq[i].pages)
3348 __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
3350 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
3351 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
3353 bpf_prog_put(old_prog);
3357 static void free_receive_bufs(struct virtnet_info *vi)
3360 _free_receive_bufs(vi);
3364 static void free_receive_page_frags(struct virtnet_info *vi)
3367 for (i = 0; i < vi->max_queue_pairs; i++)
3368 if (vi->rq[i].alloc_frag.page)
3369 put_page(vi->rq[i].alloc_frag.page);
3372 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf)
3374 if (!is_xdp_frame(buf))
3377 xdp_return_frame(ptr_to_xdp(buf));
3380 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf)
3382 struct virtnet_info *vi = vq->vdev->priv;
3385 if (vi->mergeable_rx_bufs)
3386 put_page(virt_to_head_page(buf));
3387 else if (vi->big_packets)
3388 give_pages(&vi->rq[i], buf);
3390 put_page(virt_to_head_page(buf));
3393 static void free_unused_bufs(struct virtnet_info *vi)
3398 for (i = 0; i < vi->max_queue_pairs; i++) {
3399 struct virtqueue *vq = vi->sq[i].vq;
3400 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3401 virtnet_sq_free_unused_buf(vq, buf);
3404 for (i = 0; i < vi->max_queue_pairs; i++) {
3405 struct virtqueue *vq = vi->rq[i].vq;
3406 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3407 virtnet_rq_free_unused_buf(vq, buf);
3411 static void virtnet_del_vqs(struct virtnet_info *vi)
3413 struct virtio_device *vdev = vi->vdev;
3415 virtnet_clean_affinity(vi);
3417 vdev->config->del_vqs(vdev);
3419 virtnet_free_queues(vi);
3422 /* How large should a single buffer be so a queue full of these can fit at
3423 * least one full packet?
3424 * Logic below assumes the mergeable buffer header is used.
3426 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
3428 const unsigned int hdr_len = vi->hdr_len;
3429 unsigned int rq_size = virtqueue_get_vring_size(vq);
3430 unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
3431 unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
3432 unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
3434 return max(max(min_buf_len, hdr_len) - hdr_len,
3435 (unsigned int)GOOD_PACKET_LEN);
3438 static int virtnet_find_vqs(struct virtnet_info *vi)
3440 vq_callback_t **callbacks;
3441 struct virtqueue **vqs;
3447 /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
3448 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
3449 * possible control vq.
3451 total_vqs = vi->max_queue_pairs * 2 +
3452 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
3454 /* Allocate space for find_vqs parameters */
3455 vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
3458 callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
3461 names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
3464 if (!vi->big_packets || vi->mergeable_rx_bufs) {
3465 ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
3472 /* Parameters for control virtqueue, if any */
3474 callbacks[total_vqs - 1] = NULL;
3475 names[total_vqs - 1] = "control";
3478 /* Allocate/initialize parameters for send/receive virtqueues */
3479 for (i = 0; i < vi->max_queue_pairs; i++) {
3480 callbacks[rxq2vq(i)] = skb_recv_done;
3481 callbacks[txq2vq(i)] = skb_xmit_done;
3482 sprintf(vi->rq[i].name, "input.%d", i);
3483 sprintf(vi->sq[i].name, "output.%d", i);
3484 names[rxq2vq(i)] = vi->rq[i].name;
3485 names[txq2vq(i)] = vi->sq[i].name;
3487 ctx[rxq2vq(i)] = true;
3490 ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
3496 vi->cvq = vqs[total_vqs - 1];
3497 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
3498 vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
3501 for (i = 0; i < vi->max_queue_pairs; i++) {
3502 vi->rq[i].vq = vqs[rxq2vq(i)];
3503 vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
3504 vi->sq[i].vq = vqs[txq2vq(i)];
3507 /* run here: ret == 0. */
3522 static int virtnet_alloc_queues(struct virtnet_info *vi)
3527 vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
3533 vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
3536 vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
3540 INIT_DELAYED_WORK(&vi->refill, refill_work);
3541 for (i = 0; i < vi->max_queue_pairs; i++) {
3542 vi->rq[i].pages = NULL;
3543 netif_napi_add_weight(vi->dev, &vi->rq[i].napi, virtnet_poll,
3545 netif_napi_add_tx_weight(vi->dev, &vi->sq[i].napi,
3547 napi_tx ? napi_weight : 0);
3549 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
3550 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
3551 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
3553 u64_stats_init(&vi->rq[i].stats.syncp);
3554 u64_stats_init(&vi->sq[i].stats.syncp);
3567 static int init_vqs(struct virtnet_info *vi)
3571 /* Allocate send & receive queues */
3572 ret = virtnet_alloc_queues(vi);
3576 ret = virtnet_find_vqs(vi);
3581 virtnet_set_affinity(vi);
3587 virtnet_free_queues(vi);
3593 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
3596 struct virtnet_info *vi = netdev_priv(queue->dev);
3597 unsigned int queue_index = get_netdev_rx_queue_index(queue);
3598 unsigned int headroom = virtnet_get_headroom(vi);
3599 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
3600 struct ewma_pkt_len *avg;
3602 BUG_ON(queue_index >= vi->max_queue_pairs);
3603 avg = &vi->rq[queue_index].mrg_avg_pkt_len;
3604 return sprintf(buf, "%u\n",
3605 get_mergeable_buf_len(&vi->rq[queue_index], avg,
3606 SKB_DATA_ALIGN(headroom + tailroom)));
3609 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
3610 __ATTR_RO(mergeable_rx_buffer_size);
3612 static struct attribute *virtio_net_mrg_rx_attrs[] = {
3613 &mergeable_rx_buffer_size_attribute.attr,
3617 static const struct attribute_group virtio_net_mrg_rx_group = {
3618 .name = "virtio_net",
3619 .attrs = virtio_net_mrg_rx_attrs
3623 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
3625 const char *fname, const char *dname)
3627 if (!virtio_has_feature(vdev, fbit))
3630 dev_err(&vdev->dev, "device advertises feature %s but not %s",
3636 #define VIRTNET_FAIL_ON(vdev, fbit, dbit) \
3637 virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
3639 static bool virtnet_validate_features(struct virtio_device *vdev)
3641 if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
3642 (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
3643 "VIRTIO_NET_F_CTRL_VQ") ||
3644 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
3645 "VIRTIO_NET_F_CTRL_VQ") ||
3646 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
3647 "VIRTIO_NET_F_CTRL_VQ") ||
3648 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
3649 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
3650 "VIRTIO_NET_F_CTRL_VQ") ||
3651 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_RSS,
3652 "VIRTIO_NET_F_CTRL_VQ") ||
3653 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_HASH_REPORT,
3654 "VIRTIO_NET_F_CTRL_VQ") ||
3655 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_NOTF_COAL,
3656 "VIRTIO_NET_F_CTRL_VQ"))) {
3663 #define MIN_MTU ETH_MIN_MTU
3664 #define MAX_MTU ETH_MAX_MTU
3666 static int virtnet_validate(struct virtio_device *vdev)
3668 if (!vdev->config->get) {
3669 dev_err(&vdev->dev, "%s failure: config access disabled\n",
3674 if (!virtnet_validate_features(vdev))
3677 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3678 int mtu = virtio_cread16(vdev,
3679 offsetof(struct virtio_net_config,
3682 __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3688 static bool virtnet_check_guest_gso(const struct virtnet_info *vi)
3690 return virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3691 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3692 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3693 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO);
3696 static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu)
3698 bool guest_gso = virtnet_check_guest_gso(vi);
3700 /* If device can receive ANY guest GSO packets, regardless of mtu,
3701 * allocate packets of maximum size, otherwise limit it to only
3702 * mtu size worth only.
3704 if (mtu > ETH_DATA_LEN || guest_gso) {
3705 vi->big_packets = true;
3706 vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE);
3710 static int virtnet_probe(struct virtio_device *vdev)
3712 int i, err = -ENOMEM;
3713 struct net_device *dev;
3714 struct virtnet_info *vi;
3715 u16 max_queue_pairs;
3718 /* Find if host supports multiqueue/rss virtio_net device */
3719 max_queue_pairs = 1;
3720 if (virtio_has_feature(vdev, VIRTIO_NET_F_MQ) || virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3722 virtio_cread16(vdev, offsetof(struct virtio_net_config, max_virtqueue_pairs));
3724 /* We need at least 2 queue's */
3725 if (max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
3726 max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
3727 !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3728 max_queue_pairs = 1;
3730 /* Allocate ourselves a network device with room for our info */
3731 dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
3735 /* Set up network device as normal. */
3736 dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
3737 IFF_TX_SKB_NO_LINEAR;
3738 dev->netdev_ops = &virtnet_netdev;
3739 dev->features = NETIF_F_HIGHDMA;
3741 dev->ethtool_ops = &virtnet_ethtool_ops;
3742 SET_NETDEV_DEV(dev, &vdev->dev);
3744 /* Do we support "hardware" checksums? */
3745 if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
3746 /* This opens up the world of extra features. */
3747 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3749 dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3751 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
3752 dev->hw_features |= NETIF_F_TSO
3753 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
3755 /* Individual feature bits: what can host handle? */
3756 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
3757 dev->hw_features |= NETIF_F_TSO;
3758 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
3759 dev->hw_features |= NETIF_F_TSO6;
3760 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
3761 dev->hw_features |= NETIF_F_TSO_ECN;
3763 dev->features |= NETIF_F_GSO_ROBUST;
3766 dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
3767 /* (!csum && gso) case will be fixed by register_netdev() */
3769 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
3770 dev->features |= NETIF_F_RXCSUM;
3771 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3772 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3773 dev->features |= NETIF_F_GRO_HW;
3774 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3775 dev->hw_features |= NETIF_F_GRO_HW;
3777 dev->vlan_features = dev->features;
3779 /* MTU range: 68 - 65535 */
3780 dev->min_mtu = MIN_MTU;
3781 dev->max_mtu = MAX_MTU;
3783 /* Configuration may specify what MAC to use. Otherwise random. */
3784 if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3787 virtio_cread_bytes(vdev,
3788 offsetof(struct virtio_net_config, mac),
3790 eth_hw_addr_set(dev, addr);
3792 eth_hw_addr_random(dev);
3795 /* Set up our device-specific information */
3796 vi = netdev_priv(dev);
3801 INIT_WORK(&vi->config_work, virtnet_config_changed_work);
3802 spin_lock_init(&vi->refill_lock);
3804 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
3805 vi->mergeable_rx_bufs = true;
3807 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
3810 vi->tx_max_packets = 0;
3811 vi->rx_max_packets = 0;
3814 if (virtio_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT))
3815 vi->has_rss_hash_report = true;
3817 if (virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3820 if (vi->has_rss || vi->has_rss_hash_report) {
3821 vi->rss_indir_table_size =
3822 virtio_cread16(vdev, offsetof(struct virtio_net_config,
3823 rss_max_indirection_table_length));
3825 virtio_cread8(vdev, offsetof(struct virtio_net_config, rss_max_key_size));
3827 vi->rss_hash_types_supported =
3828 virtio_cread32(vdev, offsetof(struct virtio_net_config, supported_hash_types));
3829 vi->rss_hash_types_supported &=
3830 ~(VIRTIO_NET_RSS_HASH_TYPE_IP_EX |
3831 VIRTIO_NET_RSS_HASH_TYPE_TCP_EX |
3832 VIRTIO_NET_RSS_HASH_TYPE_UDP_EX);
3834 dev->hw_features |= NETIF_F_RXHASH;
3837 if (vi->has_rss_hash_report)
3838 vi->hdr_len = sizeof(struct virtio_net_hdr_v1_hash);
3839 else if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
3840 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3841 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
3843 vi->hdr_len = sizeof(struct virtio_net_hdr);
3845 if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
3846 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3847 vi->any_header_sg = true;
3849 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3852 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3853 mtu = virtio_cread16(vdev,
3854 offsetof(struct virtio_net_config,
3856 if (mtu < dev->min_mtu) {
3857 /* Should never trigger: MTU was previously validated
3858 * in virtnet_validate.
3861 "device MTU appears to have changed it is now %d < %d",
3871 virtnet_set_big_packets(vi, mtu);
3873 if (vi->any_header_sg)
3874 dev->needed_headroom = vi->hdr_len;
3876 /* Enable multiqueue by default */
3877 if (num_online_cpus() >= max_queue_pairs)
3878 vi->curr_queue_pairs = max_queue_pairs;
3880 vi->curr_queue_pairs = num_online_cpus();
3881 vi->max_queue_pairs = max_queue_pairs;
3883 /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
3889 if (vi->mergeable_rx_bufs)
3890 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
3892 netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
3893 netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
3895 virtnet_init_settings(dev);
3897 if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
3898 vi->failover = net_failover_create(vi->dev);
3899 if (IS_ERR(vi->failover)) {
3900 err = PTR_ERR(vi->failover);
3905 if (vi->has_rss || vi->has_rss_hash_report)
3906 virtnet_init_default_rss(vi);
3908 /* serialize netdev register + virtio_device_ready() with ndo_open() */
3911 err = register_netdevice(dev);
3913 pr_debug("virtio_net: registering device failed\n");
3918 virtio_device_ready(vdev);
3922 err = virtnet_cpu_notif_add(vi);
3924 pr_debug("virtio_net: registering cpu notifier failed\n");
3925 goto free_unregister_netdev;
3928 virtnet_set_queues(vi, vi->curr_queue_pairs);
3930 /* Assume link up if device can't report link status,
3931 otherwise get link status from config. */
3932 netif_carrier_off(dev);
3933 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
3934 schedule_work(&vi->config_work);
3936 vi->status = VIRTIO_NET_S_LINK_UP;
3937 virtnet_update_settings(vi);
3938 netif_carrier_on(dev);
3941 for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
3942 if (virtio_has_feature(vi->vdev, guest_offloads[i]))
3943 set_bit(guest_offloads[i], &vi->guest_offloads);
3944 vi->guest_offloads_capable = vi->guest_offloads;
3946 pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
3947 dev->name, max_queue_pairs);
3951 free_unregister_netdev:
3952 unregister_netdev(dev);
3954 net_failover_destroy(vi->failover);
3956 virtio_reset_device(vdev);
3957 cancel_delayed_work_sync(&vi->refill);
3958 free_receive_page_frags(vi);
3959 virtnet_del_vqs(vi);
3965 static void remove_vq_common(struct virtnet_info *vi)
3967 virtio_reset_device(vi->vdev);
3969 /* Free unused buffers in both send and recv, if any. */
3970 free_unused_bufs(vi);
3972 free_receive_bufs(vi);
3974 free_receive_page_frags(vi);
3976 virtnet_del_vqs(vi);
3979 static void virtnet_remove(struct virtio_device *vdev)
3981 struct virtnet_info *vi = vdev->priv;
3983 virtnet_cpu_notif_remove(vi);
3985 /* Make sure no work handler is accessing the device. */
3986 flush_work(&vi->config_work);
3988 unregister_netdev(vi->dev);
3990 net_failover_destroy(vi->failover);
3992 remove_vq_common(vi);
3994 free_netdev(vi->dev);
3997 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
3999 struct virtnet_info *vi = vdev->priv;
4001 virtnet_cpu_notif_remove(vi);
4002 virtnet_freeze_down(vdev);
4003 remove_vq_common(vi);
4008 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
4010 struct virtnet_info *vi = vdev->priv;
4013 err = virtnet_restore_up(vdev);
4016 virtnet_set_queues(vi, vi->curr_queue_pairs);
4018 err = virtnet_cpu_notif_add(vi);
4020 virtnet_freeze_down(vdev);
4021 remove_vq_common(vi);
4028 static struct virtio_device_id id_table[] = {
4029 { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
4033 #define VIRTNET_FEATURES \
4034 VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
4036 VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
4037 VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
4038 VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
4039 VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
4040 VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
4041 VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
4042 VIRTIO_NET_F_CTRL_MAC_ADDR, \
4043 VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
4044 VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY, \
4045 VIRTIO_NET_F_RSS, VIRTIO_NET_F_HASH_REPORT, VIRTIO_NET_F_NOTF_COAL
4047 static unsigned int features[] = {
4051 static unsigned int features_legacy[] = {
4054 VIRTIO_F_ANY_LAYOUT,
4057 static struct virtio_driver virtio_net_driver = {
4058 .feature_table = features,
4059 .feature_table_size = ARRAY_SIZE(features),
4060 .feature_table_legacy = features_legacy,
4061 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
4062 .driver.name = KBUILD_MODNAME,
4063 .driver.owner = THIS_MODULE,
4064 .id_table = id_table,
4065 .validate = virtnet_validate,
4066 .probe = virtnet_probe,
4067 .remove = virtnet_remove,
4068 .config_changed = virtnet_config_changed,
4069 #ifdef CONFIG_PM_SLEEP
4070 .freeze = virtnet_freeze,
4071 .restore = virtnet_restore,
4075 static __init int virtio_net_driver_init(void)
4079 ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
4081 virtnet_cpu_down_prep);
4084 virtionet_online = ret;
4085 ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
4086 NULL, virtnet_cpu_dead);
4089 ret = register_virtio_driver(&virtio_net_driver);
4094 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4096 cpuhp_remove_multi_state(virtionet_online);
4100 module_init(virtio_net_driver_init);
4102 static __exit void virtio_net_driver_exit(void)
4104 unregister_virtio_driver(&virtio_net_driver);
4105 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4106 cpuhp_remove_multi_state(virtionet_online);
4108 module_exit(virtio_net_driver_exit);
4110 MODULE_DEVICE_TABLE(virtio, id_table);
4111 MODULE_DESCRIPTION("Virtio network driver");
4112 MODULE_LICENSE("GPL");