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 if (xdp_xmit & VIRTIO_XDP_REDIR)
1679 /* Out of packets? */
1680 if (received < budget)
1681 virtqueue_napi_complete(napi, rq->vq, received);
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 if (unlikely(!virtqueue_enable_cb_delayed(sq->vq)))
1878 virtqueue_napi_schedule(&sq->napi, sq->vq);
1879 } else if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1880 /* More just got used, free them then recheck. */
1881 free_old_xmit_skbs(sq, false);
1882 if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1883 netif_start_subqueue(dev, qnum);
1884 virtqueue_disable_cb(sq->vq);
1889 if (kick || netif_xmit_stopped(txq)) {
1890 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1891 u64_stats_update_begin(&sq->stats.syncp);
1893 u64_stats_update_end(&sq->stats.syncp);
1897 return NETDEV_TX_OK;
1900 static int virtnet_rx_resize(struct virtnet_info *vi,
1901 struct receive_queue *rq, u32 ring_num)
1903 bool running = netif_running(vi->dev);
1906 qindex = rq - vi->rq;
1909 napi_disable(&rq->napi);
1911 err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_free_unused_buf);
1913 netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
1915 if (!try_fill_recv(vi, rq, GFP_KERNEL))
1916 schedule_delayed_work(&vi->refill, 0);
1919 virtnet_napi_enable(rq->vq, &rq->napi);
1923 static int virtnet_tx_resize(struct virtnet_info *vi,
1924 struct send_queue *sq, u32 ring_num)
1926 bool running = netif_running(vi->dev);
1927 struct netdev_queue *txq;
1930 qindex = sq - vi->sq;
1933 virtnet_napi_tx_disable(&sq->napi);
1935 txq = netdev_get_tx_queue(vi->dev, qindex);
1937 /* 1. wait all ximt complete
1938 * 2. fix the race of netif_stop_subqueue() vs netif_start_subqueue()
1940 __netif_tx_lock_bh(txq);
1942 /* Prevent rx poll from accessing sq. */
1945 /* Prevent the upper layer from trying to send packets. */
1946 netif_stop_subqueue(vi->dev, qindex);
1948 __netif_tx_unlock_bh(txq);
1950 err = virtqueue_resize(sq->vq, ring_num, virtnet_sq_free_unused_buf);
1952 netdev_err(vi->dev, "resize tx fail: tx queue index: %d err: %d\n", qindex, err);
1954 __netif_tx_lock_bh(txq);
1956 netif_tx_wake_queue(txq);
1957 __netif_tx_unlock_bh(txq);
1960 virtnet_napi_tx_enable(vi, sq->vq, &sq->napi);
1965 * Send command via the control virtqueue and check status. Commands
1966 * supported by the hypervisor, as indicated by feature bits, should
1967 * never fail unless improperly formatted.
1969 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1970 struct scatterlist *out)
1972 struct scatterlist *sgs[4], hdr, stat;
1973 unsigned out_num = 0, tmp;
1976 /* Caller should know better */
1977 BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1979 vi->ctrl->status = ~0;
1980 vi->ctrl->hdr.class = class;
1981 vi->ctrl->hdr.cmd = cmd;
1983 sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
1984 sgs[out_num++] = &hdr;
1987 sgs[out_num++] = out;
1989 /* Add return status. */
1990 sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
1991 sgs[out_num] = &stat;
1993 BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1994 ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1996 dev_warn(&vi->vdev->dev,
1997 "Failed to add sgs for command vq: %d\n.", ret);
2001 if (unlikely(!virtqueue_kick(vi->cvq)))
2002 return vi->ctrl->status == VIRTIO_NET_OK;
2004 /* Spin for a response, the kick causes an ioport write, trapping
2005 * into the hypervisor, so the request should be handled immediately.
2007 while (!virtqueue_get_buf(vi->cvq, &tmp) &&
2008 !virtqueue_is_broken(vi->cvq))
2011 return vi->ctrl->status == VIRTIO_NET_OK;
2014 static int virtnet_set_mac_address(struct net_device *dev, void *p)
2016 struct virtnet_info *vi = netdev_priv(dev);
2017 struct virtio_device *vdev = vi->vdev;
2019 struct sockaddr *addr;
2020 struct scatterlist sg;
2022 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2025 addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
2029 ret = eth_prepare_mac_addr_change(dev, addr);
2033 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
2034 sg_init_one(&sg, addr->sa_data, dev->addr_len);
2035 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2036 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
2037 dev_warn(&vdev->dev,
2038 "Failed to set mac address by vq command.\n");
2042 } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
2043 !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2046 /* Naturally, this has an atomicity problem. */
2047 for (i = 0; i < dev->addr_len; i++)
2048 virtio_cwrite8(vdev,
2049 offsetof(struct virtio_net_config, mac) +
2050 i, addr->sa_data[i]);
2053 eth_commit_mac_addr_change(dev, p);
2061 static void virtnet_stats(struct net_device *dev,
2062 struct rtnl_link_stats64 *tot)
2064 struct virtnet_info *vi = netdev_priv(dev);
2068 for (i = 0; i < vi->max_queue_pairs; i++) {
2069 u64 tpackets, tbytes, terrors, rpackets, rbytes, rdrops;
2070 struct receive_queue *rq = &vi->rq[i];
2071 struct send_queue *sq = &vi->sq[i];
2074 start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2075 tpackets = sq->stats.packets;
2076 tbytes = sq->stats.bytes;
2077 terrors = sq->stats.tx_timeouts;
2078 } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2081 start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2082 rpackets = rq->stats.packets;
2083 rbytes = rq->stats.bytes;
2084 rdrops = rq->stats.drops;
2085 } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2087 tot->rx_packets += rpackets;
2088 tot->tx_packets += tpackets;
2089 tot->rx_bytes += rbytes;
2090 tot->tx_bytes += tbytes;
2091 tot->rx_dropped += rdrops;
2092 tot->tx_errors += terrors;
2095 tot->tx_dropped = dev->stats.tx_dropped;
2096 tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
2097 tot->rx_length_errors = dev->stats.rx_length_errors;
2098 tot->rx_frame_errors = dev->stats.rx_frame_errors;
2101 static void virtnet_ack_link_announce(struct virtnet_info *vi)
2104 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
2105 VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
2106 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
2110 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2112 struct scatterlist sg;
2113 struct net_device *dev = vi->dev;
2115 if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
2118 vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
2119 sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
2121 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2122 VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
2123 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
2127 vi->curr_queue_pairs = queue_pairs;
2128 /* virtnet_open() will refill when device is going to up. */
2129 if (dev->flags & IFF_UP)
2130 schedule_delayed_work(&vi->refill, 0);
2136 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2141 err = _virtnet_set_queues(vi, queue_pairs);
2146 static int virtnet_close(struct net_device *dev)
2148 struct virtnet_info *vi = netdev_priv(dev);
2151 /* Make sure NAPI doesn't schedule refill work */
2152 disable_delayed_refill(vi);
2153 /* Make sure refill_work doesn't re-enable napi! */
2154 cancel_delayed_work_sync(&vi->refill);
2156 for (i = 0; i < vi->max_queue_pairs; i++) {
2157 napi_disable(&vi->rq[i].napi);
2158 xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
2159 virtnet_napi_tx_disable(&vi->sq[i].napi);
2165 static void virtnet_set_rx_mode(struct net_device *dev)
2167 struct virtnet_info *vi = netdev_priv(dev);
2168 struct scatterlist sg[2];
2169 struct virtio_net_ctrl_mac *mac_data;
2170 struct netdev_hw_addr *ha;
2176 /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
2177 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
2180 vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
2181 vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
2183 sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
2185 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2186 VIRTIO_NET_CTRL_RX_PROMISC, sg))
2187 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
2188 vi->ctrl->promisc ? "en" : "dis");
2190 sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
2192 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2193 VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
2194 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
2195 vi->ctrl->allmulti ? "en" : "dis");
2197 uc_count = netdev_uc_count(dev);
2198 mc_count = netdev_mc_count(dev);
2199 /* MAC filter - use one buffer for both lists */
2200 buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
2201 (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
2206 sg_init_table(sg, 2);
2208 /* Store the unicast list and count in the front of the buffer */
2209 mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2211 netdev_for_each_uc_addr(ha, dev)
2212 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2214 sg_set_buf(&sg[0], mac_data,
2215 sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2217 /* multicast list and count fill the end */
2218 mac_data = (void *)&mac_data->macs[uc_count][0];
2220 mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2222 netdev_for_each_mc_addr(ha, dev)
2223 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2225 sg_set_buf(&sg[1], mac_data,
2226 sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2228 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2229 VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2230 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2235 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
2236 __be16 proto, u16 vid)
2238 struct virtnet_info *vi = netdev_priv(dev);
2239 struct scatterlist sg;
2241 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2242 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2244 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2245 VIRTIO_NET_CTRL_VLAN_ADD, &sg))
2246 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
2250 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
2251 __be16 proto, u16 vid)
2253 struct virtnet_info *vi = netdev_priv(dev);
2254 struct scatterlist sg;
2256 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2257 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2259 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2260 VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2261 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2265 static void virtnet_clean_affinity(struct virtnet_info *vi)
2269 if (vi->affinity_hint_set) {
2270 for (i = 0; i < vi->max_queue_pairs; i++) {
2271 virtqueue_set_affinity(vi->rq[i].vq, NULL);
2272 virtqueue_set_affinity(vi->sq[i].vq, NULL);
2275 vi->affinity_hint_set = false;
2279 static void virtnet_set_affinity(struct virtnet_info *vi)
2288 if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2289 virtnet_clean_affinity(vi);
2293 num_cpu = num_online_cpus();
2294 stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2295 stragglers = num_cpu >= vi->curr_queue_pairs ?
2296 num_cpu % vi->curr_queue_pairs :
2298 cpu = cpumask_first(cpu_online_mask);
2300 for (i = 0; i < vi->curr_queue_pairs; i++) {
2301 group_size = stride + (i < stragglers ? 1 : 0);
2303 for (j = 0; j < group_size; j++) {
2304 cpumask_set_cpu(cpu, mask);
2305 cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2308 virtqueue_set_affinity(vi->rq[i].vq, mask);
2309 virtqueue_set_affinity(vi->sq[i].vq, mask);
2310 __netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2311 cpumask_clear(mask);
2314 vi->affinity_hint_set = true;
2315 free_cpumask_var(mask);
2318 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2320 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2322 virtnet_set_affinity(vi);
2326 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2328 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2330 virtnet_set_affinity(vi);
2334 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2336 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2339 virtnet_clean_affinity(vi);
2343 static enum cpuhp_state virtionet_online;
2345 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2349 ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2352 ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2356 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2360 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2362 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2363 cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2367 static void virtnet_get_ringparam(struct net_device *dev,
2368 struct ethtool_ringparam *ring,
2369 struct kernel_ethtool_ringparam *kernel_ring,
2370 struct netlink_ext_ack *extack)
2372 struct virtnet_info *vi = netdev_priv(dev);
2374 ring->rx_max_pending = vi->rq[0].vq->num_max;
2375 ring->tx_max_pending = vi->sq[0].vq->num_max;
2376 ring->rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2377 ring->tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2380 static int virtnet_set_ringparam(struct net_device *dev,
2381 struct ethtool_ringparam *ring,
2382 struct kernel_ethtool_ringparam *kernel_ring,
2383 struct netlink_ext_ack *extack)
2385 struct virtnet_info *vi = netdev_priv(dev);
2386 u32 rx_pending, tx_pending;
2387 struct receive_queue *rq;
2388 struct send_queue *sq;
2391 if (ring->rx_mini_pending || ring->rx_jumbo_pending)
2394 rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2395 tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2397 if (ring->rx_pending == rx_pending &&
2398 ring->tx_pending == tx_pending)
2401 if (ring->rx_pending > vi->rq[0].vq->num_max)
2404 if (ring->tx_pending > vi->sq[0].vq->num_max)
2407 for (i = 0; i < vi->max_queue_pairs; i++) {
2411 if (ring->tx_pending != tx_pending) {
2412 err = virtnet_tx_resize(vi, sq, ring->tx_pending);
2417 if (ring->rx_pending != rx_pending) {
2418 err = virtnet_rx_resize(vi, rq, ring->rx_pending);
2427 static bool virtnet_commit_rss_command(struct virtnet_info *vi)
2429 struct net_device *dev = vi->dev;
2430 struct scatterlist sgs[4];
2431 unsigned int sg_buf_size;
2434 sg_init_table(sgs, 4);
2436 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, indirection_table);
2437 sg_set_buf(&sgs[0], &vi->ctrl->rss, sg_buf_size);
2439 sg_buf_size = sizeof(uint16_t) * (vi->ctrl->rss.indirection_table_mask + 1);
2440 sg_set_buf(&sgs[1], vi->ctrl->rss.indirection_table, sg_buf_size);
2442 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, key)
2443 - offsetof(struct virtio_net_ctrl_rss, max_tx_vq);
2444 sg_set_buf(&sgs[2], &vi->ctrl->rss.max_tx_vq, sg_buf_size);
2446 sg_buf_size = vi->rss_key_size;
2447 sg_set_buf(&sgs[3], vi->ctrl->rss.key, sg_buf_size);
2449 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2450 vi->has_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG
2451 : VIRTIO_NET_CTRL_MQ_HASH_CONFIG, sgs)) {
2452 dev_warn(&dev->dev, "VIRTIONET issue with committing RSS sgs\n");
2458 static void virtnet_init_default_rss(struct virtnet_info *vi)
2463 vi->ctrl->rss.hash_types = vi->rss_hash_types_supported;
2464 vi->rss_hash_types_saved = vi->rss_hash_types_supported;
2465 vi->ctrl->rss.indirection_table_mask = vi->rss_indir_table_size
2466 ? vi->rss_indir_table_size - 1 : 0;
2467 vi->ctrl->rss.unclassified_queue = 0;
2469 for (; i < vi->rss_indir_table_size; ++i) {
2470 indir_val = ethtool_rxfh_indir_default(i, vi->curr_queue_pairs);
2471 vi->ctrl->rss.indirection_table[i] = indir_val;
2474 vi->ctrl->rss.max_tx_vq = vi->curr_queue_pairs;
2475 vi->ctrl->rss.hash_key_length = vi->rss_key_size;
2477 netdev_rss_key_fill(vi->ctrl->rss.key, vi->rss_key_size);
2480 static void virtnet_get_hashflow(const struct virtnet_info *vi, struct ethtool_rxnfc *info)
2483 switch (info->flow_type) {
2485 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
2486 info->data = RXH_IP_SRC | RXH_IP_DST |
2487 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2488 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2489 info->data = RXH_IP_SRC | RXH_IP_DST;
2493 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
2494 info->data = RXH_IP_SRC | RXH_IP_DST |
2495 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2496 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2497 info->data = RXH_IP_SRC | RXH_IP_DST;
2501 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
2502 info->data = RXH_IP_SRC | RXH_IP_DST |
2503 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2504 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2505 info->data = RXH_IP_SRC | RXH_IP_DST;
2509 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
2510 info->data = RXH_IP_SRC | RXH_IP_DST |
2511 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2512 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2513 info->data = RXH_IP_SRC | RXH_IP_DST;
2517 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4)
2518 info->data = RXH_IP_SRC | RXH_IP_DST;
2522 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6)
2523 info->data = RXH_IP_SRC | RXH_IP_DST;
2532 static bool virtnet_set_hashflow(struct virtnet_info *vi, struct ethtool_rxnfc *info)
2534 u32 new_hashtypes = vi->rss_hash_types_saved;
2535 bool is_disable = info->data & RXH_DISCARD;
2536 bool is_l4 = info->data == (RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3);
2538 /* supports only 'sd', 'sdfn' and 'r' */
2539 if (!((info->data == (RXH_IP_SRC | RXH_IP_DST)) | is_l4 | is_disable))
2542 switch (info->flow_type) {
2544 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_TCPv4);
2546 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2547 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0);
2550 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_UDPv4);
2552 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2553 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0);
2556 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2558 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2561 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_TCPv6);
2563 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2564 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0);
2567 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_UDPv6);
2569 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2570 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0);
2573 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2575 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2578 /* unsupported flow */
2582 /* if unsupported hashtype was set */
2583 if (new_hashtypes != (new_hashtypes & vi->rss_hash_types_supported))
2586 if (new_hashtypes != vi->rss_hash_types_saved) {
2587 vi->rss_hash_types_saved = new_hashtypes;
2588 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
2589 if (vi->dev->features & NETIF_F_RXHASH)
2590 return virtnet_commit_rss_command(vi);
2596 static void virtnet_get_drvinfo(struct net_device *dev,
2597 struct ethtool_drvinfo *info)
2599 struct virtnet_info *vi = netdev_priv(dev);
2600 struct virtio_device *vdev = vi->vdev;
2602 strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2603 strscpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2604 strscpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2608 /* TODO: Eliminate OOO packets during switching */
2609 static int virtnet_set_channels(struct net_device *dev,
2610 struct ethtool_channels *channels)
2612 struct virtnet_info *vi = netdev_priv(dev);
2613 u16 queue_pairs = channels->combined_count;
2616 /* We don't support separate rx/tx channels.
2617 * We don't allow setting 'other' channels.
2619 if (channels->rx_count || channels->tx_count || channels->other_count)
2622 if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2625 /* For now we don't support modifying channels while XDP is loaded
2626 * also when XDP is loaded all RX queues have XDP programs so we only
2627 * need to check a single RX queue.
2629 if (vi->rq[0].xdp_prog)
2633 err = _virtnet_set_queues(vi, queue_pairs);
2638 virtnet_set_affinity(vi);
2641 netif_set_real_num_tx_queues(dev, queue_pairs);
2642 netif_set_real_num_rx_queues(dev, queue_pairs);
2647 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2649 struct virtnet_info *vi = netdev_priv(dev);
2653 switch (stringset) {
2655 for (i = 0; i < vi->curr_queue_pairs; i++) {
2656 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
2657 ethtool_sprintf(&p, "rx_queue_%u_%s", i,
2658 virtnet_rq_stats_desc[j].desc);
2661 for (i = 0; i < vi->curr_queue_pairs; i++) {
2662 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
2663 ethtool_sprintf(&p, "tx_queue_%u_%s", i,
2664 virtnet_sq_stats_desc[j].desc);
2670 static int virtnet_get_sset_count(struct net_device *dev, int sset)
2672 struct virtnet_info *vi = netdev_priv(dev);
2676 return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2677 VIRTNET_SQ_STATS_LEN);
2683 static void virtnet_get_ethtool_stats(struct net_device *dev,
2684 struct ethtool_stats *stats, u64 *data)
2686 struct virtnet_info *vi = netdev_priv(dev);
2687 unsigned int idx = 0, start, i, j;
2688 const u8 *stats_base;
2691 for (i = 0; i < vi->curr_queue_pairs; i++) {
2692 struct receive_queue *rq = &vi->rq[i];
2694 stats_base = (u8 *)&rq->stats;
2696 start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2697 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2698 offset = virtnet_rq_stats_desc[j].offset;
2699 data[idx + j] = *(u64 *)(stats_base + offset);
2701 } while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2702 idx += VIRTNET_RQ_STATS_LEN;
2705 for (i = 0; i < vi->curr_queue_pairs; i++) {
2706 struct send_queue *sq = &vi->sq[i];
2708 stats_base = (u8 *)&sq->stats;
2710 start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2711 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2712 offset = virtnet_sq_stats_desc[j].offset;
2713 data[idx + j] = *(u64 *)(stats_base + offset);
2715 } while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2716 idx += VIRTNET_SQ_STATS_LEN;
2720 static void virtnet_get_channels(struct net_device *dev,
2721 struct ethtool_channels *channels)
2723 struct virtnet_info *vi = netdev_priv(dev);
2725 channels->combined_count = vi->curr_queue_pairs;
2726 channels->max_combined = vi->max_queue_pairs;
2727 channels->max_other = 0;
2728 channels->rx_count = 0;
2729 channels->tx_count = 0;
2730 channels->other_count = 0;
2733 static int virtnet_set_link_ksettings(struct net_device *dev,
2734 const struct ethtool_link_ksettings *cmd)
2736 struct virtnet_info *vi = netdev_priv(dev);
2738 return ethtool_virtdev_set_link_ksettings(dev, cmd,
2739 &vi->speed, &vi->duplex);
2742 static int virtnet_get_link_ksettings(struct net_device *dev,
2743 struct ethtool_link_ksettings *cmd)
2745 struct virtnet_info *vi = netdev_priv(dev);
2747 cmd->base.speed = vi->speed;
2748 cmd->base.duplex = vi->duplex;
2749 cmd->base.port = PORT_OTHER;
2754 static int virtnet_send_notf_coal_cmds(struct virtnet_info *vi,
2755 struct ethtool_coalesce *ec)
2757 struct scatterlist sgs_tx, sgs_rx;
2758 struct virtio_net_ctrl_coal_tx coal_tx;
2759 struct virtio_net_ctrl_coal_rx coal_rx;
2761 coal_tx.tx_usecs = cpu_to_le32(ec->tx_coalesce_usecs);
2762 coal_tx.tx_max_packets = cpu_to_le32(ec->tx_max_coalesced_frames);
2763 sg_init_one(&sgs_tx, &coal_tx, sizeof(coal_tx));
2765 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2766 VIRTIO_NET_CTRL_NOTF_COAL_TX_SET,
2770 /* Save parameters */
2771 vi->tx_usecs = ec->tx_coalesce_usecs;
2772 vi->tx_max_packets = ec->tx_max_coalesced_frames;
2774 coal_rx.rx_usecs = cpu_to_le32(ec->rx_coalesce_usecs);
2775 coal_rx.rx_max_packets = cpu_to_le32(ec->rx_max_coalesced_frames);
2776 sg_init_one(&sgs_rx, &coal_rx, sizeof(coal_rx));
2778 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2779 VIRTIO_NET_CTRL_NOTF_COAL_RX_SET,
2783 /* Save parameters */
2784 vi->rx_usecs = ec->rx_coalesce_usecs;
2785 vi->rx_max_packets = ec->rx_max_coalesced_frames;
2790 static int virtnet_coal_params_supported(struct ethtool_coalesce *ec)
2792 /* usecs coalescing is supported only if VIRTIO_NET_F_NOTF_COAL
2793 * feature is negotiated.
2795 if (ec->rx_coalesce_usecs || ec->tx_coalesce_usecs)
2798 if (ec->tx_max_coalesced_frames > 1 ||
2799 ec->rx_max_coalesced_frames != 1)
2805 static int virtnet_set_coalesce(struct net_device *dev,
2806 struct ethtool_coalesce *ec,
2807 struct kernel_ethtool_coalesce *kernel_coal,
2808 struct netlink_ext_ack *extack)
2810 struct virtnet_info *vi = netdev_priv(dev);
2811 int ret, i, napi_weight;
2812 bool update_napi = false;
2814 /* Can't change NAPI weight if the link is up */
2815 napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
2816 if (napi_weight ^ vi->sq[0].napi.weight) {
2817 if (dev->flags & IFF_UP)
2823 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL))
2824 ret = virtnet_send_notf_coal_cmds(vi, ec);
2826 ret = virtnet_coal_params_supported(ec);
2832 for (i = 0; i < vi->max_queue_pairs; i++)
2833 vi->sq[i].napi.weight = napi_weight;
2839 static int virtnet_get_coalesce(struct net_device *dev,
2840 struct ethtool_coalesce *ec,
2841 struct kernel_ethtool_coalesce *kernel_coal,
2842 struct netlink_ext_ack *extack)
2844 struct virtnet_info *vi = netdev_priv(dev);
2846 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
2847 ec->rx_coalesce_usecs = vi->rx_usecs;
2848 ec->tx_coalesce_usecs = vi->tx_usecs;
2849 ec->tx_max_coalesced_frames = vi->tx_max_packets;
2850 ec->rx_max_coalesced_frames = vi->rx_max_packets;
2852 ec->rx_max_coalesced_frames = 1;
2854 if (vi->sq[0].napi.weight)
2855 ec->tx_max_coalesced_frames = 1;
2861 static void virtnet_init_settings(struct net_device *dev)
2863 struct virtnet_info *vi = netdev_priv(dev);
2865 vi->speed = SPEED_UNKNOWN;
2866 vi->duplex = DUPLEX_UNKNOWN;
2869 static void virtnet_update_settings(struct virtnet_info *vi)
2874 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
2877 virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
2879 if (ethtool_validate_speed(speed))
2882 virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
2884 if (ethtool_validate_duplex(duplex))
2885 vi->duplex = duplex;
2888 static u32 virtnet_get_rxfh_key_size(struct net_device *dev)
2890 return ((struct virtnet_info *)netdev_priv(dev))->rss_key_size;
2893 static u32 virtnet_get_rxfh_indir_size(struct net_device *dev)
2895 return ((struct virtnet_info *)netdev_priv(dev))->rss_indir_table_size;
2898 static int virtnet_get_rxfh(struct net_device *dev, u32 *indir, u8 *key, u8 *hfunc)
2900 struct virtnet_info *vi = netdev_priv(dev);
2904 for (i = 0; i < vi->rss_indir_table_size; ++i)
2905 indir[i] = vi->ctrl->rss.indirection_table[i];
2909 memcpy(key, vi->ctrl->rss.key, vi->rss_key_size);
2912 *hfunc = ETH_RSS_HASH_TOP;
2917 static int virtnet_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key, const u8 hfunc)
2919 struct virtnet_info *vi = netdev_priv(dev);
2922 if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
2926 for (i = 0; i < vi->rss_indir_table_size; ++i)
2927 vi->ctrl->rss.indirection_table[i] = indir[i];
2930 memcpy(vi->ctrl->rss.key, key, vi->rss_key_size);
2932 virtnet_commit_rss_command(vi);
2937 static int virtnet_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rule_locs)
2939 struct virtnet_info *vi = netdev_priv(dev);
2942 switch (info->cmd) {
2943 case ETHTOOL_GRXRINGS:
2944 info->data = vi->curr_queue_pairs;
2947 virtnet_get_hashflow(vi, info);
2956 static int virtnet_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info)
2958 struct virtnet_info *vi = netdev_priv(dev);
2961 switch (info->cmd) {
2963 if (!virtnet_set_hashflow(vi, info))
2974 static const struct ethtool_ops virtnet_ethtool_ops = {
2975 .supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES |
2976 ETHTOOL_COALESCE_USECS,
2977 .get_drvinfo = virtnet_get_drvinfo,
2978 .get_link = ethtool_op_get_link,
2979 .get_ringparam = virtnet_get_ringparam,
2980 .set_ringparam = virtnet_set_ringparam,
2981 .get_strings = virtnet_get_strings,
2982 .get_sset_count = virtnet_get_sset_count,
2983 .get_ethtool_stats = virtnet_get_ethtool_stats,
2984 .set_channels = virtnet_set_channels,
2985 .get_channels = virtnet_get_channels,
2986 .get_ts_info = ethtool_op_get_ts_info,
2987 .get_link_ksettings = virtnet_get_link_ksettings,
2988 .set_link_ksettings = virtnet_set_link_ksettings,
2989 .set_coalesce = virtnet_set_coalesce,
2990 .get_coalesce = virtnet_get_coalesce,
2991 .get_rxfh_key_size = virtnet_get_rxfh_key_size,
2992 .get_rxfh_indir_size = virtnet_get_rxfh_indir_size,
2993 .get_rxfh = virtnet_get_rxfh,
2994 .set_rxfh = virtnet_set_rxfh,
2995 .get_rxnfc = virtnet_get_rxnfc,
2996 .set_rxnfc = virtnet_set_rxnfc,
2999 static void virtnet_freeze_down(struct virtio_device *vdev)
3001 struct virtnet_info *vi = vdev->priv;
3003 /* Make sure no work handler is accessing the device */
3004 flush_work(&vi->config_work);
3006 netif_tx_lock_bh(vi->dev);
3007 netif_device_detach(vi->dev);
3008 netif_tx_unlock_bh(vi->dev);
3009 if (netif_running(vi->dev))
3010 virtnet_close(vi->dev);
3013 static int init_vqs(struct virtnet_info *vi);
3015 static int virtnet_restore_up(struct virtio_device *vdev)
3017 struct virtnet_info *vi = vdev->priv;
3024 virtio_device_ready(vdev);
3026 enable_delayed_refill(vi);
3028 if (netif_running(vi->dev)) {
3029 err = virtnet_open(vi->dev);
3034 netif_tx_lock_bh(vi->dev);
3035 netif_device_attach(vi->dev);
3036 netif_tx_unlock_bh(vi->dev);
3040 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
3042 struct scatterlist sg;
3043 vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
3045 sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
3047 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
3048 VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
3049 dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
3056 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
3060 if (!vi->guest_offloads)
3063 return virtnet_set_guest_offloads(vi, offloads);
3066 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
3068 u64 offloads = vi->guest_offloads;
3070 if (!vi->guest_offloads)
3073 return virtnet_set_guest_offloads(vi, offloads);
3076 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
3077 struct netlink_ext_ack *extack)
3079 unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
3080 struct virtnet_info *vi = netdev_priv(dev);
3081 struct bpf_prog *old_prog;
3082 u16 xdp_qp = 0, curr_qp;
3085 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
3086 && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3087 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3088 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3089 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3090 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM))) {
3091 NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
3095 if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
3096 NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
3100 if (dev->mtu > max_sz) {
3101 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
3102 netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
3106 curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
3108 xdp_qp = nr_cpu_ids;
3110 /* XDP requires extra queues for XDP_TX */
3111 if (curr_qp + xdp_qp > vi->max_queue_pairs) {
3112 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",
3113 curr_qp + xdp_qp, vi->max_queue_pairs);
3117 old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
3118 if (!prog && !old_prog)
3122 bpf_prog_add(prog, vi->max_queue_pairs - 1);
3124 /* Make sure NAPI is not using any XDP TX queues for RX. */
3125 if (netif_running(dev)) {
3126 for (i = 0; i < vi->max_queue_pairs; i++) {
3127 napi_disable(&vi->rq[i].napi);
3128 virtnet_napi_tx_disable(&vi->sq[i].napi);
3133 for (i = 0; i < vi->max_queue_pairs; i++) {
3134 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3136 virtnet_restore_guest_offloads(vi);
3141 err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
3144 netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
3145 vi->xdp_queue_pairs = xdp_qp;
3148 vi->xdp_enabled = true;
3149 for (i = 0; i < vi->max_queue_pairs; i++) {
3150 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3151 if (i == 0 && !old_prog)
3152 virtnet_clear_guest_offloads(vi);
3155 vi->xdp_enabled = false;
3158 for (i = 0; i < vi->max_queue_pairs; i++) {
3160 bpf_prog_put(old_prog);
3161 if (netif_running(dev)) {
3162 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3163 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3172 virtnet_clear_guest_offloads(vi);
3173 for (i = 0; i < vi->max_queue_pairs; i++)
3174 rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
3177 if (netif_running(dev)) {
3178 for (i = 0; i < vi->max_queue_pairs; i++) {
3179 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3180 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3185 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
3189 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
3191 switch (xdp->command) {
3192 case XDP_SETUP_PROG:
3193 return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
3199 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
3202 struct virtnet_info *vi = netdev_priv(dev);
3205 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
3208 ret = snprintf(buf, len, "sby");
3215 static int virtnet_set_features(struct net_device *dev,
3216 netdev_features_t features)
3218 struct virtnet_info *vi = netdev_priv(dev);
3222 if ((dev->features ^ features) & NETIF_F_GRO_HW) {
3223 if (vi->xdp_enabled)
3226 if (features & NETIF_F_GRO_HW)
3227 offloads = vi->guest_offloads_capable;
3229 offloads = vi->guest_offloads_capable &
3230 ~GUEST_OFFLOAD_GRO_HW_MASK;
3232 err = virtnet_set_guest_offloads(vi, offloads);
3235 vi->guest_offloads = offloads;
3238 if ((dev->features ^ features) & NETIF_F_RXHASH) {
3239 if (features & NETIF_F_RXHASH)
3240 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
3242 vi->ctrl->rss.hash_types = VIRTIO_NET_HASH_REPORT_NONE;
3244 if (!virtnet_commit_rss_command(vi))
3251 static void virtnet_tx_timeout(struct net_device *dev, unsigned int txqueue)
3253 struct virtnet_info *priv = netdev_priv(dev);
3254 struct send_queue *sq = &priv->sq[txqueue];
3255 struct netdev_queue *txq = netdev_get_tx_queue(dev, txqueue);
3257 u64_stats_update_begin(&sq->stats.syncp);
3258 sq->stats.tx_timeouts++;
3259 u64_stats_update_end(&sq->stats.syncp);
3261 netdev_err(dev, "TX timeout on queue: %u, sq: %s, vq: 0x%x, name: %s, %u usecs ago\n",
3262 txqueue, sq->name, sq->vq->index, sq->vq->name,
3263 jiffies_to_usecs(jiffies - READ_ONCE(txq->trans_start)));
3266 static const struct net_device_ops virtnet_netdev = {
3267 .ndo_open = virtnet_open,
3268 .ndo_stop = virtnet_close,
3269 .ndo_start_xmit = start_xmit,
3270 .ndo_validate_addr = eth_validate_addr,
3271 .ndo_set_mac_address = virtnet_set_mac_address,
3272 .ndo_set_rx_mode = virtnet_set_rx_mode,
3273 .ndo_get_stats64 = virtnet_stats,
3274 .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
3275 .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
3276 .ndo_bpf = virtnet_xdp,
3277 .ndo_xdp_xmit = virtnet_xdp_xmit,
3278 .ndo_features_check = passthru_features_check,
3279 .ndo_get_phys_port_name = virtnet_get_phys_port_name,
3280 .ndo_set_features = virtnet_set_features,
3281 .ndo_tx_timeout = virtnet_tx_timeout,
3284 static void virtnet_config_changed_work(struct work_struct *work)
3286 struct virtnet_info *vi =
3287 container_of(work, struct virtnet_info, config_work);
3290 if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
3291 struct virtio_net_config, status, &v) < 0)
3294 if (v & VIRTIO_NET_S_ANNOUNCE) {
3295 netdev_notify_peers(vi->dev);
3296 virtnet_ack_link_announce(vi);
3299 /* Ignore unknown (future) status bits */
3300 v &= VIRTIO_NET_S_LINK_UP;
3302 if (vi->status == v)
3307 if (vi->status & VIRTIO_NET_S_LINK_UP) {
3308 virtnet_update_settings(vi);
3309 netif_carrier_on(vi->dev);
3310 netif_tx_wake_all_queues(vi->dev);
3312 netif_carrier_off(vi->dev);
3313 netif_tx_stop_all_queues(vi->dev);
3317 static void virtnet_config_changed(struct virtio_device *vdev)
3319 struct virtnet_info *vi = vdev->priv;
3321 schedule_work(&vi->config_work);
3324 static void virtnet_free_queues(struct virtnet_info *vi)
3328 for (i = 0; i < vi->max_queue_pairs; i++) {
3329 __netif_napi_del(&vi->rq[i].napi);
3330 __netif_napi_del(&vi->sq[i].napi);
3333 /* We called __netif_napi_del(),
3334 * we need to respect an RCU grace period before freeing vi->rq
3343 static void _free_receive_bufs(struct virtnet_info *vi)
3345 struct bpf_prog *old_prog;
3348 for (i = 0; i < vi->max_queue_pairs; i++) {
3349 while (vi->rq[i].pages)
3350 __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
3352 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
3353 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
3355 bpf_prog_put(old_prog);
3359 static void free_receive_bufs(struct virtnet_info *vi)
3362 _free_receive_bufs(vi);
3366 static void free_receive_page_frags(struct virtnet_info *vi)
3369 for (i = 0; i < vi->max_queue_pairs; i++)
3370 if (vi->rq[i].alloc_frag.page)
3371 put_page(vi->rq[i].alloc_frag.page);
3374 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf)
3376 if (!is_xdp_frame(buf))
3379 xdp_return_frame(ptr_to_xdp(buf));
3382 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf)
3384 struct virtnet_info *vi = vq->vdev->priv;
3387 if (vi->mergeable_rx_bufs)
3388 put_page(virt_to_head_page(buf));
3389 else if (vi->big_packets)
3390 give_pages(&vi->rq[i], buf);
3392 put_page(virt_to_head_page(buf));
3395 static void free_unused_bufs(struct virtnet_info *vi)
3400 for (i = 0; i < vi->max_queue_pairs; i++) {
3401 struct virtqueue *vq = vi->sq[i].vq;
3402 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3403 virtnet_sq_free_unused_buf(vq, buf);
3406 for (i = 0; i < vi->max_queue_pairs; i++) {
3407 struct virtqueue *vq = vi->rq[i].vq;
3408 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3409 virtnet_rq_free_unused_buf(vq, buf);
3413 static void virtnet_del_vqs(struct virtnet_info *vi)
3415 struct virtio_device *vdev = vi->vdev;
3417 virtnet_clean_affinity(vi);
3419 vdev->config->del_vqs(vdev);
3421 virtnet_free_queues(vi);
3424 /* How large should a single buffer be so a queue full of these can fit at
3425 * least one full packet?
3426 * Logic below assumes the mergeable buffer header is used.
3428 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
3430 const unsigned int hdr_len = vi->hdr_len;
3431 unsigned int rq_size = virtqueue_get_vring_size(vq);
3432 unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
3433 unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
3434 unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
3436 return max(max(min_buf_len, hdr_len) - hdr_len,
3437 (unsigned int)GOOD_PACKET_LEN);
3440 static int virtnet_find_vqs(struct virtnet_info *vi)
3442 vq_callback_t **callbacks;
3443 struct virtqueue **vqs;
3449 /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
3450 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
3451 * possible control vq.
3453 total_vqs = vi->max_queue_pairs * 2 +
3454 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
3456 /* Allocate space for find_vqs parameters */
3457 vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
3460 callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
3463 names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
3466 if (!vi->big_packets || vi->mergeable_rx_bufs) {
3467 ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
3474 /* Parameters for control virtqueue, if any */
3476 callbacks[total_vqs - 1] = NULL;
3477 names[total_vqs - 1] = "control";
3480 /* Allocate/initialize parameters for send/receive virtqueues */
3481 for (i = 0; i < vi->max_queue_pairs; i++) {
3482 callbacks[rxq2vq(i)] = skb_recv_done;
3483 callbacks[txq2vq(i)] = skb_xmit_done;
3484 sprintf(vi->rq[i].name, "input.%d", i);
3485 sprintf(vi->sq[i].name, "output.%d", i);
3486 names[rxq2vq(i)] = vi->rq[i].name;
3487 names[txq2vq(i)] = vi->sq[i].name;
3489 ctx[rxq2vq(i)] = true;
3492 ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
3498 vi->cvq = vqs[total_vqs - 1];
3499 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
3500 vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
3503 for (i = 0; i < vi->max_queue_pairs; i++) {
3504 vi->rq[i].vq = vqs[rxq2vq(i)];
3505 vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
3506 vi->sq[i].vq = vqs[txq2vq(i)];
3509 /* run here: ret == 0. */
3524 static int virtnet_alloc_queues(struct virtnet_info *vi)
3529 vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
3535 vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
3538 vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
3542 INIT_DELAYED_WORK(&vi->refill, refill_work);
3543 for (i = 0; i < vi->max_queue_pairs; i++) {
3544 vi->rq[i].pages = NULL;
3545 netif_napi_add_weight(vi->dev, &vi->rq[i].napi, virtnet_poll,
3547 netif_napi_add_tx_weight(vi->dev, &vi->sq[i].napi,
3549 napi_tx ? napi_weight : 0);
3551 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
3552 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
3553 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
3555 u64_stats_init(&vi->rq[i].stats.syncp);
3556 u64_stats_init(&vi->sq[i].stats.syncp);
3569 static int init_vqs(struct virtnet_info *vi)
3573 /* Allocate send & receive queues */
3574 ret = virtnet_alloc_queues(vi);
3578 ret = virtnet_find_vqs(vi);
3583 virtnet_set_affinity(vi);
3589 virtnet_free_queues(vi);
3595 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
3598 struct virtnet_info *vi = netdev_priv(queue->dev);
3599 unsigned int queue_index = get_netdev_rx_queue_index(queue);
3600 unsigned int headroom = virtnet_get_headroom(vi);
3601 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
3602 struct ewma_pkt_len *avg;
3604 BUG_ON(queue_index >= vi->max_queue_pairs);
3605 avg = &vi->rq[queue_index].mrg_avg_pkt_len;
3606 return sprintf(buf, "%u\n",
3607 get_mergeable_buf_len(&vi->rq[queue_index], avg,
3608 SKB_DATA_ALIGN(headroom + tailroom)));
3611 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
3612 __ATTR_RO(mergeable_rx_buffer_size);
3614 static struct attribute *virtio_net_mrg_rx_attrs[] = {
3615 &mergeable_rx_buffer_size_attribute.attr,
3619 static const struct attribute_group virtio_net_mrg_rx_group = {
3620 .name = "virtio_net",
3621 .attrs = virtio_net_mrg_rx_attrs
3625 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
3627 const char *fname, const char *dname)
3629 if (!virtio_has_feature(vdev, fbit))
3632 dev_err(&vdev->dev, "device advertises feature %s but not %s",
3638 #define VIRTNET_FAIL_ON(vdev, fbit, dbit) \
3639 virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
3641 static bool virtnet_validate_features(struct virtio_device *vdev)
3643 if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
3644 (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
3645 "VIRTIO_NET_F_CTRL_VQ") ||
3646 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
3647 "VIRTIO_NET_F_CTRL_VQ") ||
3648 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
3649 "VIRTIO_NET_F_CTRL_VQ") ||
3650 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
3651 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
3652 "VIRTIO_NET_F_CTRL_VQ") ||
3653 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_RSS,
3654 "VIRTIO_NET_F_CTRL_VQ") ||
3655 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_HASH_REPORT,
3656 "VIRTIO_NET_F_CTRL_VQ") ||
3657 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_NOTF_COAL,
3658 "VIRTIO_NET_F_CTRL_VQ"))) {
3665 #define MIN_MTU ETH_MIN_MTU
3666 #define MAX_MTU ETH_MAX_MTU
3668 static int virtnet_validate(struct virtio_device *vdev)
3670 if (!vdev->config->get) {
3671 dev_err(&vdev->dev, "%s failure: config access disabled\n",
3676 if (!virtnet_validate_features(vdev))
3679 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3680 int mtu = virtio_cread16(vdev,
3681 offsetof(struct virtio_net_config,
3684 __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3690 static bool virtnet_check_guest_gso(const struct virtnet_info *vi)
3692 return virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3693 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3694 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3695 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO);
3698 static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu)
3700 bool guest_gso = virtnet_check_guest_gso(vi);
3702 /* If device can receive ANY guest GSO packets, regardless of mtu,
3703 * allocate packets of maximum size, otherwise limit it to only
3704 * mtu size worth only.
3706 if (mtu > ETH_DATA_LEN || guest_gso) {
3707 vi->big_packets = true;
3708 vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE);
3712 static int virtnet_probe(struct virtio_device *vdev)
3714 int i, err = -ENOMEM;
3715 struct net_device *dev;
3716 struct virtnet_info *vi;
3717 u16 max_queue_pairs;
3720 /* Find if host supports multiqueue/rss virtio_net device */
3721 max_queue_pairs = 1;
3722 if (virtio_has_feature(vdev, VIRTIO_NET_F_MQ) || virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3724 virtio_cread16(vdev, offsetof(struct virtio_net_config, max_virtqueue_pairs));
3726 /* We need at least 2 queue's */
3727 if (max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
3728 max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
3729 !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3730 max_queue_pairs = 1;
3732 /* Allocate ourselves a network device with room for our info */
3733 dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
3737 /* Set up network device as normal. */
3738 dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
3739 IFF_TX_SKB_NO_LINEAR;
3740 dev->netdev_ops = &virtnet_netdev;
3741 dev->features = NETIF_F_HIGHDMA;
3743 dev->ethtool_ops = &virtnet_ethtool_ops;
3744 SET_NETDEV_DEV(dev, &vdev->dev);
3746 /* Do we support "hardware" checksums? */
3747 if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
3748 /* This opens up the world of extra features. */
3749 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3751 dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3753 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
3754 dev->hw_features |= NETIF_F_TSO
3755 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
3757 /* Individual feature bits: what can host handle? */
3758 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
3759 dev->hw_features |= NETIF_F_TSO;
3760 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
3761 dev->hw_features |= NETIF_F_TSO6;
3762 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
3763 dev->hw_features |= NETIF_F_TSO_ECN;
3765 dev->features |= NETIF_F_GSO_ROBUST;
3768 dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
3769 /* (!csum && gso) case will be fixed by register_netdev() */
3771 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
3772 dev->features |= NETIF_F_RXCSUM;
3773 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3774 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3775 dev->features |= NETIF_F_GRO_HW;
3776 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3777 dev->hw_features |= NETIF_F_GRO_HW;
3779 dev->vlan_features = dev->features;
3781 /* MTU range: 68 - 65535 */
3782 dev->min_mtu = MIN_MTU;
3783 dev->max_mtu = MAX_MTU;
3785 /* Configuration may specify what MAC to use. Otherwise random. */
3786 if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3789 virtio_cread_bytes(vdev,
3790 offsetof(struct virtio_net_config, mac),
3792 eth_hw_addr_set(dev, addr);
3794 eth_hw_addr_random(dev);
3797 /* Set up our device-specific information */
3798 vi = netdev_priv(dev);
3803 INIT_WORK(&vi->config_work, virtnet_config_changed_work);
3804 spin_lock_init(&vi->refill_lock);
3806 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
3807 vi->mergeable_rx_bufs = true;
3809 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
3812 vi->tx_max_packets = 0;
3813 vi->rx_max_packets = 0;
3816 if (virtio_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT))
3817 vi->has_rss_hash_report = true;
3819 if (virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3822 if (vi->has_rss || vi->has_rss_hash_report) {
3823 vi->rss_indir_table_size =
3824 virtio_cread16(vdev, offsetof(struct virtio_net_config,
3825 rss_max_indirection_table_length));
3827 virtio_cread8(vdev, offsetof(struct virtio_net_config, rss_max_key_size));
3829 vi->rss_hash_types_supported =
3830 virtio_cread32(vdev, offsetof(struct virtio_net_config, supported_hash_types));
3831 vi->rss_hash_types_supported &=
3832 ~(VIRTIO_NET_RSS_HASH_TYPE_IP_EX |
3833 VIRTIO_NET_RSS_HASH_TYPE_TCP_EX |
3834 VIRTIO_NET_RSS_HASH_TYPE_UDP_EX);
3836 dev->hw_features |= NETIF_F_RXHASH;
3839 if (vi->has_rss_hash_report)
3840 vi->hdr_len = sizeof(struct virtio_net_hdr_v1_hash);
3841 else if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
3842 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3843 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
3845 vi->hdr_len = sizeof(struct virtio_net_hdr);
3847 if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
3848 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3849 vi->any_header_sg = true;
3851 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3854 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3855 mtu = virtio_cread16(vdev,
3856 offsetof(struct virtio_net_config,
3858 if (mtu < dev->min_mtu) {
3859 /* Should never trigger: MTU was previously validated
3860 * in virtnet_validate.
3863 "device MTU appears to have changed it is now %d < %d",
3873 virtnet_set_big_packets(vi, mtu);
3875 if (vi->any_header_sg)
3876 dev->needed_headroom = vi->hdr_len;
3878 /* Enable multiqueue by default */
3879 if (num_online_cpus() >= max_queue_pairs)
3880 vi->curr_queue_pairs = max_queue_pairs;
3882 vi->curr_queue_pairs = num_online_cpus();
3883 vi->max_queue_pairs = max_queue_pairs;
3885 /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
3891 if (vi->mergeable_rx_bufs)
3892 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
3894 netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
3895 netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
3897 virtnet_init_settings(dev);
3899 if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
3900 vi->failover = net_failover_create(vi->dev);
3901 if (IS_ERR(vi->failover)) {
3902 err = PTR_ERR(vi->failover);
3907 if (vi->has_rss || vi->has_rss_hash_report)
3908 virtnet_init_default_rss(vi);
3910 /* serialize netdev register + virtio_device_ready() with ndo_open() */
3913 err = register_netdevice(dev);
3915 pr_debug("virtio_net: registering device failed\n");
3920 virtio_device_ready(vdev);
3924 err = virtnet_cpu_notif_add(vi);
3926 pr_debug("virtio_net: registering cpu notifier failed\n");
3927 goto free_unregister_netdev;
3930 virtnet_set_queues(vi, vi->curr_queue_pairs);
3932 /* Assume link up if device can't report link status,
3933 otherwise get link status from config. */
3934 netif_carrier_off(dev);
3935 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
3936 schedule_work(&vi->config_work);
3938 vi->status = VIRTIO_NET_S_LINK_UP;
3939 virtnet_update_settings(vi);
3940 netif_carrier_on(dev);
3943 for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
3944 if (virtio_has_feature(vi->vdev, guest_offloads[i]))
3945 set_bit(guest_offloads[i], &vi->guest_offloads);
3946 vi->guest_offloads_capable = vi->guest_offloads;
3948 pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
3949 dev->name, max_queue_pairs);
3953 free_unregister_netdev:
3954 unregister_netdev(dev);
3956 net_failover_destroy(vi->failover);
3958 virtio_reset_device(vdev);
3959 cancel_delayed_work_sync(&vi->refill);
3960 free_receive_page_frags(vi);
3961 virtnet_del_vqs(vi);
3967 static void remove_vq_common(struct virtnet_info *vi)
3969 virtio_reset_device(vi->vdev);
3971 /* Free unused buffers in both send and recv, if any. */
3972 free_unused_bufs(vi);
3974 free_receive_bufs(vi);
3976 free_receive_page_frags(vi);
3978 virtnet_del_vqs(vi);
3981 static void virtnet_remove(struct virtio_device *vdev)
3983 struct virtnet_info *vi = vdev->priv;
3985 virtnet_cpu_notif_remove(vi);
3987 /* Make sure no work handler is accessing the device. */
3988 flush_work(&vi->config_work);
3990 unregister_netdev(vi->dev);
3992 net_failover_destroy(vi->failover);
3994 remove_vq_common(vi);
3996 free_netdev(vi->dev);
3999 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
4001 struct virtnet_info *vi = vdev->priv;
4003 virtnet_cpu_notif_remove(vi);
4004 virtnet_freeze_down(vdev);
4005 remove_vq_common(vi);
4010 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
4012 struct virtnet_info *vi = vdev->priv;
4015 err = virtnet_restore_up(vdev);
4018 virtnet_set_queues(vi, vi->curr_queue_pairs);
4020 err = virtnet_cpu_notif_add(vi);
4022 virtnet_freeze_down(vdev);
4023 remove_vq_common(vi);
4030 static struct virtio_device_id id_table[] = {
4031 { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
4035 #define VIRTNET_FEATURES \
4036 VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
4038 VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
4039 VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
4040 VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
4041 VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
4042 VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
4043 VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
4044 VIRTIO_NET_F_CTRL_MAC_ADDR, \
4045 VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
4046 VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY, \
4047 VIRTIO_NET_F_RSS, VIRTIO_NET_F_HASH_REPORT, VIRTIO_NET_F_NOTF_COAL
4049 static unsigned int features[] = {
4053 static unsigned int features_legacy[] = {
4056 VIRTIO_F_ANY_LAYOUT,
4059 static struct virtio_driver virtio_net_driver = {
4060 .feature_table = features,
4061 .feature_table_size = ARRAY_SIZE(features),
4062 .feature_table_legacy = features_legacy,
4063 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
4064 .driver.name = KBUILD_MODNAME,
4065 .driver.owner = THIS_MODULE,
4066 .id_table = id_table,
4067 .validate = virtnet_validate,
4068 .probe = virtnet_probe,
4069 .remove = virtnet_remove,
4070 .config_changed = virtnet_config_changed,
4071 #ifdef CONFIG_PM_SLEEP
4072 .freeze = virtnet_freeze,
4073 .restore = virtnet_restore,
4077 static __init int virtio_net_driver_init(void)
4081 ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
4083 virtnet_cpu_down_prep);
4086 virtionet_online = ret;
4087 ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
4088 NULL, virtnet_cpu_dead);
4091 ret = register_virtio_driver(&virtio_net_driver);
4096 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4098 cpuhp_remove_multi_state(virtionet_online);
4102 module_init(virtio_net_driver_init);
4104 static __exit void virtio_net_driver_exit(void)
4106 unregister_virtio_driver(&virtio_net_driver);
4107 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4108 cpuhp_remove_multi_state(virtionet_online);
4110 module_exit(virtio_net_driver_exit);
4112 MODULE_DEVICE_TABLE(virtio, id_table);
4113 MODULE_DESCRIPTION("Virtio network driver");
4114 MODULE_LICENSE("GPL");