1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* A network driver using virtio.
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,
64 VIRTIO_NET_F_GUEST_USO4,
65 VIRTIO_NET_F_GUEST_USO6,
66 VIRTIO_NET_F_GUEST_HDRLEN
69 #define GUEST_OFFLOAD_GRO_HW_MASK ((1ULL << VIRTIO_NET_F_GUEST_TSO4) | \
70 (1ULL << VIRTIO_NET_F_GUEST_TSO6) | \
71 (1ULL << VIRTIO_NET_F_GUEST_ECN) | \
72 (1ULL << VIRTIO_NET_F_GUEST_UFO) | \
73 (1ULL << VIRTIO_NET_F_GUEST_USO4) | \
74 (1ULL << VIRTIO_NET_F_GUEST_USO6))
76 struct virtnet_stat_desc {
77 char desc[ETH_GSTRING_LEN];
81 struct virtnet_sq_stats {
82 struct u64_stats_sync syncp;
91 struct virtnet_rq_stats {
92 struct u64_stats_sync syncp;
103 #define VIRTNET_SQ_STAT(m) offsetof(struct virtnet_sq_stats, m)
104 #define VIRTNET_RQ_STAT(m) offsetof(struct virtnet_rq_stats, m)
106 static const struct virtnet_stat_desc virtnet_sq_stats_desc[] = {
107 { "packets", VIRTNET_SQ_STAT(packets) },
108 { "bytes", VIRTNET_SQ_STAT(bytes) },
109 { "xdp_tx", VIRTNET_SQ_STAT(xdp_tx) },
110 { "xdp_tx_drops", VIRTNET_SQ_STAT(xdp_tx_drops) },
111 { "kicks", VIRTNET_SQ_STAT(kicks) },
112 { "tx_timeouts", VIRTNET_SQ_STAT(tx_timeouts) },
115 static const struct virtnet_stat_desc virtnet_rq_stats_desc[] = {
116 { "packets", VIRTNET_RQ_STAT(packets) },
117 { "bytes", VIRTNET_RQ_STAT(bytes) },
118 { "drops", VIRTNET_RQ_STAT(drops) },
119 { "xdp_packets", VIRTNET_RQ_STAT(xdp_packets) },
120 { "xdp_tx", VIRTNET_RQ_STAT(xdp_tx) },
121 { "xdp_redirects", VIRTNET_RQ_STAT(xdp_redirects) },
122 { "xdp_drops", VIRTNET_RQ_STAT(xdp_drops) },
123 { "kicks", VIRTNET_RQ_STAT(kicks) },
126 #define VIRTNET_SQ_STATS_LEN ARRAY_SIZE(virtnet_sq_stats_desc)
127 #define VIRTNET_RQ_STATS_LEN ARRAY_SIZE(virtnet_rq_stats_desc)
129 /* Internal representation of a send virtqueue */
131 /* Virtqueue associated with this send _queue */
132 struct virtqueue *vq;
134 /* TX: fragments + linear part + virtio header */
135 struct scatterlist sg[MAX_SKB_FRAGS + 2];
137 /* Name of the send queue: output.$index */
140 struct virtnet_sq_stats stats;
142 struct napi_struct napi;
144 /* Record whether sq is in reset state. */
148 /* Internal representation of a receive virtqueue */
149 struct receive_queue {
150 /* Virtqueue associated with this receive_queue */
151 struct virtqueue *vq;
153 struct napi_struct napi;
155 struct bpf_prog __rcu *xdp_prog;
157 struct virtnet_rq_stats stats;
159 /* Chain pages by the private ptr. */
162 /* Average packet length for mergeable receive buffers. */
163 struct ewma_pkt_len mrg_avg_pkt_len;
165 /* Page frag for packet buffer allocation. */
166 struct page_frag alloc_frag;
168 /* RX: fragments + linear part + virtio header */
169 struct scatterlist sg[MAX_SKB_FRAGS + 2];
171 /* Min single buffer size for mergeable buffers case. */
172 unsigned int min_buf_len;
174 /* Name of this receive queue: input.$index */
177 struct xdp_rxq_info xdp_rxq;
180 /* This structure can contain rss message with maximum settings for indirection table and keysize
181 * Note, that default structure that describes RSS configuration virtio_net_rss_config
182 * contains same info but can't handle table values.
183 * In any case, structure would be passed to virtio hw through sg_buf split by parts
184 * because table sizes may be differ according to the device configuration.
186 #define VIRTIO_NET_RSS_MAX_KEY_SIZE 40
187 #define VIRTIO_NET_RSS_MAX_TABLE_LEN 128
188 struct virtio_net_ctrl_rss {
190 u16 indirection_table_mask;
191 u16 unclassified_queue;
192 u16 indirection_table[VIRTIO_NET_RSS_MAX_TABLE_LEN];
195 u8 key[VIRTIO_NET_RSS_MAX_KEY_SIZE];
198 /* Control VQ buffers: protected by the rtnl lock */
200 struct virtio_net_ctrl_hdr hdr;
201 virtio_net_ctrl_ack status;
202 struct virtio_net_ctrl_mq mq;
207 struct virtio_net_ctrl_rss rss;
210 struct virtnet_info {
211 struct virtio_device *vdev;
212 struct virtqueue *cvq;
213 struct net_device *dev;
214 struct send_queue *sq;
215 struct receive_queue *rq;
218 /* Max # of queue pairs supported by the device */
221 /* # of queue pairs currently used by the driver */
222 u16 curr_queue_pairs;
224 /* # of XDP queue pairs currently used by the driver */
227 /* xdp_queue_pairs may be 0, when xdp is already loaded. So add this. */
230 /* I like... big packets and I cannot lie! */
233 /* number of sg entries allocated for big packets */
234 unsigned int big_packets_num_skbfrags;
236 /* Host will merge rx buffers for big packets (shake it! shake it!) */
237 bool mergeable_rx_bufs;
239 /* Host supports rss and/or hash report */
241 bool has_rss_hash_report;
243 u16 rss_indir_table_size;
244 u32 rss_hash_types_supported;
245 u32 rss_hash_types_saved;
247 /* Has control virtqueue */
250 /* Host can handle any s/g split between our header and packet data */
253 /* Packet virtio header size */
256 /* Work struct for delayed refilling if we run low on memory. */
257 struct delayed_work refill;
259 /* Is delayed refill enabled? */
262 /* The lock to synchronize the access to refill_enabled */
263 spinlock_t refill_lock;
265 /* Work struct for config space updates */
266 struct work_struct config_work;
268 /* Does the affinity hint is set for virtqueues? */
269 bool affinity_hint_set;
271 /* CPU hotplug instances for online & dead */
272 struct hlist_node node;
273 struct hlist_node node_dead;
275 struct control_buf *ctrl;
277 /* Ethtool settings */
281 /* Interrupt coalescing settings */
287 unsigned long guest_offloads;
288 unsigned long guest_offloads_capable;
290 /* failover when STANDBY feature enabled */
291 struct failover *failover;
294 struct padded_vnet_hdr {
295 struct virtio_net_hdr_v1_hash hdr;
297 * hdr is in a separate sg buffer, and data sg buffer shares same page
298 * with this header sg. This padding makes next sg 16 byte aligned
304 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf);
305 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf);
307 static bool is_xdp_frame(void *ptr)
309 return (unsigned long)ptr & VIRTIO_XDP_FLAG;
312 static void *xdp_to_ptr(struct xdp_frame *ptr)
314 return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
317 static struct xdp_frame *ptr_to_xdp(void *ptr)
319 return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
322 /* Converting between virtqueue no. and kernel tx/rx queue no.
323 * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
325 static int vq2txq(struct virtqueue *vq)
327 return (vq->index - 1) / 2;
330 static int txq2vq(int txq)
335 static int vq2rxq(struct virtqueue *vq)
337 return vq->index / 2;
340 static int rxq2vq(int rxq)
345 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
347 return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
351 * private is used to chain pages for big packets, put the whole
352 * most recent used list in the beginning for reuse
354 static void give_pages(struct receive_queue *rq, struct page *page)
358 /* Find end of list, sew whole thing into vi->rq.pages. */
359 for (end = page; end->private; end = (struct page *)end->private);
360 end->private = (unsigned long)rq->pages;
364 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
366 struct page *p = rq->pages;
369 rq->pages = (struct page *)p->private;
370 /* clear private here, it is used to chain pages */
373 p = alloc_page(gfp_mask);
377 static void enable_delayed_refill(struct virtnet_info *vi)
379 spin_lock_bh(&vi->refill_lock);
380 vi->refill_enabled = true;
381 spin_unlock_bh(&vi->refill_lock);
384 static void disable_delayed_refill(struct virtnet_info *vi)
386 spin_lock_bh(&vi->refill_lock);
387 vi->refill_enabled = false;
388 spin_unlock_bh(&vi->refill_lock);
391 static void virtqueue_napi_schedule(struct napi_struct *napi,
392 struct virtqueue *vq)
394 if (napi_schedule_prep(napi)) {
395 virtqueue_disable_cb(vq);
396 __napi_schedule(napi);
400 static void virtqueue_napi_complete(struct napi_struct *napi,
401 struct virtqueue *vq, int processed)
405 opaque = virtqueue_enable_cb_prepare(vq);
406 if (napi_complete_done(napi, processed)) {
407 if (unlikely(virtqueue_poll(vq, opaque)))
408 virtqueue_napi_schedule(napi, vq);
410 virtqueue_disable_cb(vq);
414 static void skb_xmit_done(struct virtqueue *vq)
416 struct virtnet_info *vi = vq->vdev->priv;
417 struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
419 /* Suppress further interrupts. */
420 virtqueue_disable_cb(vq);
423 virtqueue_napi_schedule(napi, vq);
425 /* We were probably waiting for more output buffers. */
426 netif_wake_subqueue(vi->dev, vq2txq(vq));
429 #define MRG_CTX_HEADER_SHIFT 22
430 static void *mergeable_len_to_ctx(unsigned int truesize,
431 unsigned int headroom)
433 return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
436 static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
438 return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
441 static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
443 return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
446 /* Called from bottom half context */
447 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
448 struct receive_queue *rq,
449 struct page *page, unsigned int offset,
450 unsigned int len, unsigned int truesize,
451 unsigned int headroom)
454 struct virtio_net_hdr_mrg_rxbuf *hdr;
455 unsigned int copy, hdr_len, hdr_padded_len;
456 struct page *page_to_free = NULL;
457 int tailroom, shinfo_size;
458 char *p, *hdr_p, *buf;
460 p = page_address(page) + offset;
463 hdr_len = vi->hdr_len;
464 if (vi->mergeable_rx_bufs)
465 hdr_padded_len = hdr_len;
467 hdr_padded_len = sizeof(struct padded_vnet_hdr);
471 offset += hdr_padded_len;
473 tailroom = truesize - headroom - hdr_padded_len - len;
475 shinfo_size = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
477 /* copy small packet so we can reuse these pages */
478 if (!NET_IP_ALIGN && len > GOOD_COPY_LEN && tailroom >= shinfo_size) {
479 skb = build_skb(buf, truesize);
483 skb_reserve(skb, p - buf);
486 page = (struct page *)page->private;
488 give_pages(rq, page);
492 /* copy small packet so we can reuse these pages for small data */
493 skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
497 /* Copy all frame if it fits skb->head, otherwise
498 * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
500 if (len <= skb_tailroom(skb))
504 skb_put_data(skb, p, copy);
509 if (vi->mergeable_rx_bufs) {
511 skb_add_rx_frag(skb, 0, page, offset, len, truesize);
518 * Verify that we can indeed put this data into a skb.
519 * This is here to handle cases when the device erroneously
520 * tries to receive more than is possible. This is usually
521 * the case of a broken device.
523 if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
524 net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
528 BUG_ON(offset >= PAGE_SIZE);
530 unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
531 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
532 frag_size, truesize);
534 page = (struct page *)page->private;
539 give_pages(rq, page);
542 hdr = skb_vnet_hdr(skb);
543 memcpy(hdr, hdr_p, hdr_len);
545 put_page(page_to_free);
550 static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
553 unsigned int packets = 0;
554 unsigned int bytes = 0;
557 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
558 if (likely(!is_xdp_frame(ptr))) {
559 struct sk_buff *skb = ptr;
561 pr_debug("Sent skb %p\n", skb);
564 napi_consume_skb(skb, in_napi);
566 struct xdp_frame *frame = ptr_to_xdp(ptr);
568 bytes += xdp_get_frame_len(frame);
569 xdp_return_frame(frame);
574 /* Avoid overhead when no packets have been processed
575 * happens when called speculatively from start_xmit.
580 u64_stats_update_begin(&sq->stats.syncp);
581 sq->stats.bytes += bytes;
582 sq->stats.packets += packets;
583 u64_stats_update_end(&sq->stats.syncp);
586 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
588 if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
590 else if (q < vi->curr_queue_pairs)
596 static void check_sq_full_and_disable(struct virtnet_info *vi,
597 struct net_device *dev,
598 struct send_queue *sq)
600 bool use_napi = sq->napi.weight;
605 /* If running out of space, stop queue to avoid getting packets that we
606 * are then unable to transmit.
607 * An alternative would be to force queuing layer to requeue the skb by
608 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
609 * returned in a normal path of operation: it means that driver is not
610 * maintaining the TX queue stop/start state properly, and causes
611 * the stack to do a non-trivial amount of useless work.
612 * Since most packets only take 1 or 2 ring slots, stopping the queue
613 * early means 16 slots are typically wasted.
615 if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
616 netif_stop_subqueue(dev, qnum);
618 if (unlikely(!virtqueue_enable_cb_delayed(sq->vq)))
619 virtqueue_napi_schedule(&sq->napi, sq->vq);
620 } else if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
621 /* More just got used, free them then recheck. */
622 free_old_xmit_skbs(sq, false);
623 if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
624 netif_start_subqueue(dev, qnum);
625 virtqueue_disable_cb(sq->vq);
631 static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
632 struct send_queue *sq,
633 struct xdp_frame *xdpf)
635 struct virtio_net_hdr_mrg_rxbuf *hdr;
636 struct skb_shared_info *shinfo;
640 if (unlikely(xdpf->headroom < vi->hdr_len))
643 if (unlikely(xdp_frame_has_frags(xdpf))) {
644 shinfo = xdp_get_shared_info_from_frame(xdpf);
645 nr_frags = shinfo->nr_frags;
648 /* In wrapping function virtnet_xdp_xmit(), we need to free
649 * up the pending old buffers, where we need to calculate the
650 * position of skb_shared_info in xdp_get_frame_len() and
651 * xdp_return_frame(), which will involve to xdpf->data and
652 * xdpf->headroom. Therefore, we need to update the value of
653 * headroom synchronously here.
655 xdpf->headroom -= vi->hdr_len;
656 xdpf->data -= vi->hdr_len;
657 /* Zero header and leave csum up to XDP layers */
659 memset(hdr, 0, vi->hdr_len);
660 xdpf->len += vi->hdr_len;
662 sg_init_table(sq->sg, nr_frags + 1);
663 sg_set_buf(sq->sg, xdpf->data, xdpf->len);
664 for (i = 0; i < nr_frags; i++) {
665 skb_frag_t *frag = &shinfo->frags[i];
667 sg_set_page(&sq->sg[i + 1], skb_frag_page(frag),
668 skb_frag_size(frag), skb_frag_off(frag));
671 err = virtqueue_add_outbuf(sq->vq, sq->sg, nr_frags + 1,
672 xdp_to_ptr(xdpf), GFP_ATOMIC);
674 return -ENOSPC; /* Caller handle free/refcnt */
679 /* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
680 * the current cpu, so it does not need to be locked.
682 * Here we use marco instead of inline functions because we have to deal with
683 * three issues at the same time: 1. the choice of sq. 2. judge and execute the
684 * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
685 * functions to perfectly solve these three problems at the same time.
687 #define virtnet_xdp_get_sq(vi) ({ \
688 int cpu = smp_processor_id(); \
689 struct netdev_queue *txq; \
690 typeof(vi) v = (vi); \
693 if (v->curr_queue_pairs > nr_cpu_ids) { \
694 qp = v->curr_queue_pairs - v->xdp_queue_pairs; \
696 txq = netdev_get_tx_queue(v->dev, qp); \
697 __netif_tx_acquire(txq); \
699 qp = cpu % v->curr_queue_pairs; \
700 txq = netdev_get_tx_queue(v->dev, qp); \
701 __netif_tx_lock(txq, cpu); \
706 #define virtnet_xdp_put_sq(vi, q) { \
707 struct netdev_queue *txq; \
708 typeof(vi) v = (vi); \
710 txq = netdev_get_tx_queue(v->dev, (q) - v->sq); \
711 if (v->curr_queue_pairs > nr_cpu_ids) \
712 __netif_tx_release(txq); \
714 __netif_tx_unlock(txq); \
717 static int virtnet_xdp_xmit(struct net_device *dev,
718 int n, struct xdp_frame **frames, u32 flags)
720 struct virtnet_info *vi = netdev_priv(dev);
721 struct receive_queue *rq = vi->rq;
722 struct bpf_prog *xdp_prog;
723 struct send_queue *sq;
733 /* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
734 * indicate XDP resources have been successfully allocated.
736 xdp_prog = rcu_access_pointer(rq->xdp_prog);
740 sq = virtnet_xdp_get_sq(vi);
742 if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
747 /* Free up any pending old buffers before queueing new ones. */
748 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
749 if (likely(is_xdp_frame(ptr))) {
750 struct xdp_frame *frame = ptr_to_xdp(ptr);
752 bytes += xdp_get_frame_len(frame);
753 xdp_return_frame(frame);
755 struct sk_buff *skb = ptr;
758 napi_consume_skb(skb, false);
763 for (i = 0; i < n; i++) {
764 struct xdp_frame *xdpf = frames[i];
766 if (__virtnet_xdp_xmit_one(vi, sq, xdpf))
772 if (!is_xdp_raw_buffer_queue(vi, sq - vi->sq))
773 check_sq_full_and_disable(vi, dev, sq);
775 if (flags & XDP_XMIT_FLUSH) {
776 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
780 u64_stats_update_begin(&sq->stats.syncp);
781 sq->stats.bytes += bytes;
782 sq->stats.packets += packets;
783 sq->stats.xdp_tx += n;
784 sq->stats.xdp_tx_drops += n - nxmit;
785 sq->stats.kicks += kicks;
786 u64_stats_update_end(&sq->stats.syncp);
788 virtnet_xdp_put_sq(vi, sq);
792 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
794 return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
797 /* We copy the packet for XDP in the following cases:
799 * 1) Packet is scattered across multiple rx buffers.
800 * 2) Headroom space is insufficient.
802 * This is inefficient but it's a temporary condition that
803 * we hit right after XDP is enabled and until queue is refilled
804 * with large buffers with sufficient headroom - so it should affect
805 * at most queue size packets.
806 * Afterwards, the conditions to enable
807 * XDP should preclude the underlying device from sending packets
808 * across multiple buffers (num_buf > 1), and we make sure buffers
809 * have enough headroom.
811 static struct page *xdp_linearize_page(struct receive_queue *rq,
818 int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
821 if (page_off + *len + tailroom > PAGE_SIZE)
824 page = alloc_page(GFP_ATOMIC);
828 memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
836 buf = virtqueue_get_buf(rq->vq, &buflen);
840 p = virt_to_head_page(buf);
841 off = buf - page_address(p);
843 /* guard against a misconfigured or uncooperative backend that
844 * is sending packet larger than the MTU.
846 if ((page_off + buflen + tailroom) > PAGE_SIZE) {
851 memcpy(page_address(page) + page_off,
852 page_address(p) + off, buflen);
857 /* Headroom does not contribute to packet length */
858 *len = page_off - VIRTIO_XDP_HEADROOM;
861 __free_pages(page, 0);
865 static struct sk_buff *receive_small(struct net_device *dev,
866 struct virtnet_info *vi,
867 struct receive_queue *rq,
868 void *buf, void *ctx,
870 unsigned int *xdp_xmit,
871 struct virtnet_rq_stats *stats)
874 struct bpf_prog *xdp_prog;
875 unsigned int xdp_headroom = (unsigned long)ctx;
876 unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
877 unsigned int headroom = vi->hdr_len + header_offset;
878 unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
879 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
880 struct page *page = virt_to_head_page(buf);
881 unsigned int delta = 0;
882 struct page *xdp_page;
884 unsigned int metasize = 0;
889 if (unlikely(len > GOOD_PACKET_LEN)) {
890 pr_debug("%s: rx error: len %u exceeds max size %d\n",
891 dev->name, len, GOOD_PACKET_LEN);
892 dev->stats.rx_length_errors++;
896 if (likely(!vi->xdp_enabled)) {
902 xdp_prog = rcu_dereference(rq->xdp_prog);
904 struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
905 struct xdp_frame *xdpf;
910 if (unlikely(hdr->hdr.gso_type))
913 if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
914 int offset = buf - page_address(page) + header_offset;
915 unsigned int tlen = len + vi->hdr_len;
918 xdp_headroom = virtnet_get_headroom(vi);
919 header_offset = VIRTNET_RX_PAD + xdp_headroom;
920 headroom = vi->hdr_len + header_offset;
921 buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
922 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
923 xdp_page = xdp_linearize_page(rq, &num_buf, page,
924 offset, header_offset,
929 buf = page_address(xdp_page);
934 xdp_init_buff(&xdp, buflen, &rq->xdp_rxq);
935 xdp_prepare_buff(&xdp, buf + VIRTNET_RX_PAD + vi->hdr_len,
936 xdp_headroom, len, true);
937 orig_data = xdp.data;
938 act = bpf_prog_run_xdp(xdp_prog, &xdp);
939 stats->xdp_packets++;
943 /* Recalculate length in case bpf program changed it */
944 delta = orig_data - xdp.data;
945 len = xdp.data_end - xdp.data;
946 metasize = xdp.data - xdp.data_meta;
950 xdpf = xdp_convert_buff_to_frame(&xdp);
953 err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
954 if (unlikely(!err)) {
955 xdp_return_frame_rx_napi(xdpf);
956 } else if (unlikely(err < 0)) {
957 trace_xdp_exception(vi->dev, xdp_prog, act);
960 *xdp_xmit |= VIRTIO_XDP_TX;
964 stats->xdp_redirects++;
965 err = xdp_do_redirect(dev, &xdp, xdp_prog);
968 *xdp_xmit |= VIRTIO_XDP_REDIR;
972 bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
975 trace_xdp_exception(vi->dev, xdp_prog, act);
984 skb = build_skb(buf, buflen);
987 skb_reserve(skb, headroom - delta);
990 buf += header_offset;
991 memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
992 } /* keep zeroed vnet hdr since XDP is loaded */
995 skb_metadata_set(skb, metasize);
1009 static struct sk_buff *receive_big(struct net_device *dev,
1010 struct virtnet_info *vi,
1011 struct receive_queue *rq,
1014 struct virtnet_rq_stats *stats)
1016 struct page *page = buf;
1017 struct sk_buff *skb =
1018 page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, 0);
1020 stats->bytes += len - vi->hdr_len;
1028 give_pages(rq, page);
1032 /* Why not use xdp_build_skb_from_frame() ?
1033 * XDP core assumes that xdp frags are PAGE_SIZE in length, while in
1034 * virtio-net there are 2 points that do not match its requirements:
1035 * 1. The size of the prefilled buffer is not fixed before xdp is set.
1036 * 2. xdp_build_skb_from_frame() does more checks that we don't need,
1037 * like eth_type_trans() (which virtio-net does in receive_buf()).
1039 static struct sk_buff *build_skb_from_xdp_buff(struct net_device *dev,
1040 struct virtnet_info *vi,
1041 struct xdp_buff *xdp,
1042 unsigned int xdp_frags_truesz)
1044 struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
1045 unsigned int headroom, data_len;
1046 struct sk_buff *skb;
1050 if (unlikely(xdp->data_end > xdp_data_hard_end(xdp))) {
1051 pr_debug("Error building skb as missing reserved tailroom for xdp");
1055 if (unlikely(xdp_buff_has_frags(xdp)))
1056 nr_frags = sinfo->nr_frags;
1058 skb = build_skb(xdp->data_hard_start, xdp->frame_sz);
1062 headroom = xdp->data - xdp->data_hard_start;
1063 data_len = xdp->data_end - xdp->data;
1064 skb_reserve(skb, headroom);
1065 __skb_put(skb, data_len);
1067 metasize = xdp->data - xdp->data_meta;
1068 metasize = metasize > 0 ? metasize : 0;
1070 skb_metadata_set(skb, metasize);
1072 if (unlikely(xdp_buff_has_frags(xdp)))
1073 xdp_update_skb_shared_info(skb, nr_frags,
1074 sinfo->xdp_frags_size,
1076 xdp_buff_is_frag_pfmemalloc(xdp));
1081 /* TODO: build xdp in big mode */
1082 static int virtnet_build_xdp_buff_mrg(struct net_device *dev,
1083 struct virtnet_info *vi,
1084 struct receive_queue *rq,
1085 struct xdp_buff *xdp,
1088 unsigned int frame_sz,
1090 unsigned int *xdp_frags_truesize,
1091 struct virtnet_rq_stats *stats)
1093 struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1094 unsigned int headroom, tailroom, room;
1095 unsigned int truesize, cur_frag_size;
1096 struct skb_shared_info *shinfo;
1097 unsigned int xdp_frags_truesz = 0;
1103 xdp_init_buff(xdp, frame_sz, &rq->xdp_rxq);
1104 xdp_prepare_buff(xdp, buf - VIRTIO_XDP_HEADROOM,
1105 VIRTIO_XDP_HEADROOM + vi->hdr_len, len - vi->hdr_len, true);
1111 /* If we want to build multi-buffer xdp, we need
1112 * to specify that the flags of xdp_buff have the
1113 * XDP_FLAGS_HAS_FRAG bit.
1115 if (!xdp_buff_has_frags(xdp))
1116 xdp_buff_set_frags_flag(xdp);
1118 shinfo = xdp_get_shared_info_from_buff(xdp);
1119 shinfo->nr_frags = 0;
1120 shinfo->xdp_frags_size = 0;
1123 if (*num_buf > MAX_SKB_FRAGS + 1)
1126 while (--*num_buf > 0) {
1127 buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1128 if (unlikely(!buf)) {
1129 pr_debug("%s: rx error: %d buffers out of %d missing\n",
1130 dev->name, *num_buf,
1131 virtio16_to_cpu(vi->vdev, hdr->num_buffers));
1132 dev->stats.rx_length_errors++;
1136 stats->bytes += len;
1137 page = virt_to_head_page(buf);
1138 offset = buf - page_address(page);
1140 truesize = mergeable_ctx_to_truesize(ctx);
1141 headroom = mergeable_ctx_to_headroom(ctx);
1142 tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1143 room = SKB_DATA_ALIGN(headroom + tailroom);
1145 cur_frag_size = truesize;
1146 xdp_frags_truesz += cur_frag_size;
1147 if (unlikely(len > truesize - room || cur_frag_size > PAGE_SIZE)) {
1149 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1150 dev->name, len, (unsigned long)(truesize - room));
1151 dev->stats.rx_length_errors++;
1155 frag = &shinfo->frags[shinfo->nr_frags++];
1156 __skb_frag_set_page(frag, page);
1157 skb_frag_off_set(frag, offset);
1158 skb_frag_size_set(frag, len);
1159 if (page_is_pfmemalloc(page))
1160 xdp_buff_set_frag_pfmemalloc(xdp);
1162 shinfo->xdp_frags_size += len;
1165 *xdp_frags_truesize = xdp_frags_truesz;
1169 static struct sk_buff *receive_mergeable(struct net_device *dev,
1170 struct virtnet_info *vi,
1171 struct receive_queue *rq,
1175 unsigned int *xdp_xmit,
1176 struct virtnet_rq_stats *stats)
1178 struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1179 int num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
1180 struct page *page = virt_to_head_page(buf);
1181 int offset = buf - page_address(page);
1182 struct sk_buff *head_skb, *curr_skb;
1183 struct bpf_prog *xdp_prog;
1184 unsigned int truesize = mergeable_ctx_to_truesize(ctx);
1185 unsigned int headroom = mergeable_ctx_to_headroom(ctx);
1186 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1187 unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1188 unsigned int frame_sz, xdp_room;
1192 stats->bytes += len - vi->hdr_len;
1194 if (unlikely(len > truesize - room)) {
1195 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1196 dev->name, len, (unsigned long)(truesize - room));
1197 dev->stats.rx_length_errors++;
1201 if (likely(!vi->xdp_enabled)) {
1207 xdp_prog = rcu_dereference(rq->xdp_prog);
1209 unsigned int xdp_frags_truesz = 0;
1210 struct skb_shared_info *shinfo;
1211 struct xdp_frame *xdpf;
1212 struct page *xdp_page;
1213 struct xdp_buff xdp;
1218 /* Transient failure which in theory could occur if
1219 * in-flight packets from before XDP was enabled reach
1220 * the receive path after XDP is loaded.
1222 if (unlikely(hdr->hdr.gso_type))
1225 /* Now XDP core assumes frag size is PAGE_SIZE, but buffers
1226 * with headroom may add hole in truesize, which
1227 * make their length exceed PAGE_SIZE. So we disabled the
1228 * hole mechanism for xdp. See add_recvbuf_mergeable().
1230 frame_sz = truesize;
1232 /* This happens when headroom is not enough because
1233 * of the buffer was prefilled before XDP is set.
1234 * This should only happen for the first several packets.
1235 * In fact, vq reset can be used here to help us clean up
1236 * the prefilled buffers, but many existing devices do not
1237 * support it, and we don't want to bother users who are
1238 * using xdp normally.
1240 if (!xdp_prog->aux->xdp_has_frags &&
1241 (num_buf > 1 || headroom < virtnet_get_headroom(vi))) {
1242 /* linearize data for XDP */
1243 xdp_page = xdp_linearize_page(rq, &num_buf,
1245 VIRTIO_XDP_HEADROOM,
1247 frame_sz = PAGE_SIZE;
1251 offset = VIRTIO_XDP_HEADROOM;
1252 } else if (unlikely(headroom < virtnet_get_headroom(vi))) {
1253 xdp_room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
1254 sizeof(struct skb_shared_info));
1255 if (len + xdp_room > PAGE_SIZE)
1258 xdp_page = alloc_page(GFP_ATOMIC);
1262 memcpy(page_address(xdp_page) + VIRTIO_XDP_HEADROOM,
1263 page_address(page) + offset, len);
1264 frame_sz = PAGE_SIZE;
1265 offset = VIRTIO_XDP_HEADROOM;
1270 data = page_address(xdp_page) + offset;
1271 err = virtnet_build_xdp_buff_mrg(dev, vi, rq, &xdp, data, len, frame_sz,
1272 &num_buf, &xdp_frags_truesz, stats);
1276 act = bpf_prog_run_xdp(xdp_prog, &xdp);
1277 stats->xdp_packets++;
1281 head_skb = build_skb_from_xdp_buff(dev, vi, &xdp, xdp_frags_truesz);
1282 if (unlikely(!head_skb))
1285 if (unlikely(xdp_page != page))
1291 xdpf = xdp_convert_buff_to_frame(&xdp);
1292 if (unlikely(!xdpf)) {
1293 netdev_dbg(dev, "convert buff to frame failed for xdp\n");
1296 err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
1297 if (unlikely(!err)) {
1298 xdp_return_frame_rx_napi(xdpf);
1299 } else if (unlikely(err < 0)) {
1300 trace_xdp_exception(vi->dev, xdp_prog, act);
1303 *xdp_xmit |= VIRTIO_XDP_TX;
1304 if (unlikely(xdp_page != page))
1309 stats->xdp_redirects++;
1310 err = xdp_do_redirect(dev, &xdp, xdp_prog);
1313 *xdp_xmit |= VIRTIO_XDP_REDIR;
1314 if (unlikely(xdp_page != page))
1319 bpf_warn_invalid_xdp_action(vi->dev, xdp_prog, act);
1322 trace_xdp_exception(vi->dev, xdp_prog, act);
1328 if (unlikely(xdp_page != page))
1329 __free_pages(xdp_page, 0);
1331 if (xdp_buff_has_frags(&xdp)) {
1332 shinfo = xdp_get_shared_info_from_buff(&xdp);
1333 for (i = 0; i < shinfo->nr_frags; i++) {
1334 xdp_page = skb_frag_page(&shinfo->frags[i]);
1344 head_skb = page_to_skb(vi, rq, page, offset, len, truesize, headroom);
1345 curr_skb = head_skb;
1347 if (unlikely(!curr_skb))
1352 buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1353 if (unlikely(!buf)) {
1354 pr_debug("%s: rx error: %d buffers out of %d missing\n",
1356 virtio16_to_cpu(vi->vdev,
1358 dev->stats.rx_length_errors++;
1362 stats->bytes += len;
1363 page = virt_to_head_page(buf);
1365 truesize = mergeable_ctx_to_truesize(ctx);
1366 headroom = mergeable_ctx_to_headroom(ctx);
1367 tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1368 room = SKB_DATA_ALIGN(headroom + tailroom);
1369 if (unlikely(len > truesize - room)) {
1370 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1371 dev->name, len, (unsigned long)(truesize - room));
1372 dev->stats.rx_length_errors++;
1376 num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1377 if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1378 struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1380 if (unlikely(!nskb))
1382 if (curr_skb == head_skb)
1383 skb_shinfo(curr_skb)->frag_list = nskb;
1385 curr_skb->next = nskb;
1387 head_skb->truesize += nskb->truesize;
1390 if (curr_skb != head_skb) {
1391 head_skb->data_len += len;
1392 head_skb->len += len;
1393 head_skb->truesize += truesize;
1395 offset = buf - page_address(page);
1396 if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1398 skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1401 skb_add_rx_frag(curr_skb, num_skb_frags, page,
1402 offset, len, truesize);
1406 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1414 while (num_buf-- > 1) {
1415 buf = virtqueue_get_buf(rq->vq, &len);
1416 if (unlikely(!buf)) {
1417 pr_debug("%s: rx error: %d buffers missing\n",
1418 dev->name, num_buf);
1419 dev->stats.rx_length_errors++;
1422 stats->bytes += len;
1423 page = virt_to_head_page(buf);
1428 dev_kfree_skb(head_skb);
1433 static void virtio_skb_set_hash(const struct virtio_net_hdr_v1_hash *hdr_hash,
1434 struct sk_buff *skb)
1436 enum pkt_hash_types rss_hash_type;
1438 if (!hdr_hash || !skb)
1441 switch (__le16_to_cpu(hdr_hash->hash_report)) {
1442 case VIRTIO_NET_HASH_REPORT_TCPv4:
1443 case VIRTIO_NET_HASH_REPORT_UDPv4:
1444 case VIRTIO_NET_HASH_REPORT_TCPv6:
1445 case VIRTIO_NET_HASH_REPORT_UDPv6:
1446 case VIRTIO_NET_HASH_REPORT_TCPv6_EX:
1447 case VIRTIO_NET_HASH_REPORT_UDPv6_EX:
1448 rss_hash_type = PKT_HASH_TYPE_L4;
1450 case VIRTIO_NET_HASH_REPORT_IPv4:
1451 case VIRTIO_NET_HASH_REPORT_IPv6:
1452 case VIRTIO_NET_HASH_REPORT_IPv6_EX:
1453 rss_hash_type = PKT_HASH_TYPE_L3;
1455 case VIRTIO_NET_HASH_REPORT_NONE:
1457 rss_hash_type = PKT_HASH_TYPE_NONE;
1459 skb_set_hash(skb, __le32_to_cpu(hdr_hash->hash_value), rss_hash_type);
1462 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1463 void *buf, unsigned int len, void **ctx,
1464 unsigned int *xdp_xmit,
1465 struct virtnet_rq_stats *stats)
1467 struct net_device *dev = vi->dev;
1468 struct sk_buff *skb;
1469 struct virtio_net_hdr_mrg_rxbuf *hdr;
1471 if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1472 pr_debug("%s: short packet %i\n", dev->name, len);
1473 dev->stats.rx_length_errors++;
1474 virtnet_rq_free_unused_buf(rq->vq, buf);
1478 if (vi->mergeable_rx_bufs)
1479 skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1481 else if (vi->big_packets)
1482 skb = receive_big(dev, vi, rq, buf, len, stats);
1484 skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1489 hdr = skb_vnet_hdr(skb);
1490 if (dev->features & NETIF_F_RXHASH && vi->has_rss_hash_report)
1491 virtio_skb_set_hash((const struct virtio_net_hdr_v1_hash *)hdr, skb);
1493 if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
1494 skb->ip_summed = CHECKSUM_UNNECESSARY;
1496 if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1497 virtio_is_little_endian(vi->vdev))) {
1498 net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1499 dev->name, hdr->hdr.gso_type,
1504 skb_record_rx_queue(skb, vq2rxq(rq->vq));
1505 skb->protocol = eth_type_trans(skb, dev);
1506 pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1507 ntohs(skb->protocol), skb->len, skb->pkt_type);
1509 napi_gro_receive(&rq->napi, skb);
1513 dev->stats.rx_frame_errors++;
1517 /* Unlike mergeable buffers, all buffers are allocated to the
1518 * same size, except for the headroom. For this reason we do
1519 * not need to use mergeable_len_to_ctx here - it is enough
1520 * to store the headroom as the context ignoring the truesize.
1522 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1525 struct page_frag *alloc_frag = &rq->alloc_frag;
1527 unsigned int xdp_headroom = virtnet_get_headroom(vi);
1528 void *ctx = (void *)(unsigned long)xdp_headroom;
1529 int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1532 len = SKB_DATA_ALIGN(len) +
1533 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1534 if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
1537 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1538 get_page(alloc_frag->page);
1539 alloc_frag->offset += len;
1540 sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1541 vi->hdr_len + GOOD_PACKET_LEN);
1542 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1544 put_page(virt_to_head_page(buf));
1548 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1551 struct page *first, *list = NULL;
1555 sg_init_table(rq->sg, vi->big_packets_num_skbfrags + 2);
1557 /* page in rq->sg[vi->big_packets_num_skbfrags + 1] is list tail */
1558 for (i = vi->big_packets_num_skbfrags + 1; i > 1; --i) {
1559 first = get_a_page(rq, gfp);
1562 give_pages(rq, list);
1565 sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1567 /* chain new page in list head to match sg */
1568 first->private = (unsigned long)list;
1572 first = get_a_page(rq, gfp);
1574 give_pages(rq, list);
1577 p = page_address(first);
1579 /* rq->sg[0], rq->sg[1] share the same page */
1580 /* a separated rq->sg[0] for header - required in case !any_header_sg */
1581 sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1583 /* rq->sg[1] for data packet, from offset */
1584 offset = sizeof(struct padded_vnet_hdr);
1585 sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1587 /* chain first in list head */
1588 first->private = (unsigned long)list;
1589 err = virtqueue_add_inbuf(rq->vq, rq->sg, vi->big_packets_num_skbfrags + 2,
1592 give_pages(rq, first);
1597 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1598 struct ewma_pkt_len *avg_pkt_len,
1601 struct virtnet_info *vi = rq->vq->vdev->priv;
1602 const size_t hdr_len = vi->hdr_len;
1606 return PAGE_SIZE - room;
1608 len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1609 rq->min_buf_len, PAGE_SIZE - hdr_len);
1611 return ALIGN(len, L1_CACHE_BYTES);
1614 static int add_recvbuf_mergeable(struct virtnet_info *vi,
1615 struct receive_queue *rq, gfp_t gfp)
1617 struct page_frag *alloc_frag = &rq->alloc_frag;
1618 unsigned int headroom = virtnet_get_headroom(vi);
1619 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1620 unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1624 unsigned int len, hole;
1626 /* Extra tailroom is needed to satisfy XDP's assumption. This
1627 * means rx frags coalescing won't work, but consider we've
1628 * disabled GSO for XDP, it won't be a big issue.
1630 len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1631 if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
1634 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1635 buf += headroom; /* advance address leaving hole at front of pkt */
1636 get_page(alloc_frag->page);
1637 alloc_frag->offset += len + room;
1638 hole = alloc_frag->size - alloc_frag->offset;
1639 if (hole < len + room) {
1640 /* To avoid internal fragmentation, if there is very likely not
1641 * enough space for another buffer, add the remaining space to
1642 * the current buffer.
1643 * XDP core assumes that frame_size of xdp_buff and the length
1644 * of the frag are PAGE_SIZE, so we disable the hole mechanism.
1648 alloc_frag->offset += hole;
1651 sg_init_one(rq->sg, buf, len);
1652 ctx = mergeable_len_to_ctx(len + room, headroom);
1653 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1655 put_page(virt_to_head_page(buf));
1661 * Returns false if we couldn't fill entirely (OOM).
1663 * Normally run in the receive path, but can also be run from ndo_open
1664 * before we're receiving packets, or from refill_work which is
1665 * careful to disable receiving (using napi_disable).
1667 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1674 if (vi->mergeable_rx_bufs)
1675 err = add_recvbuf_mergeable(vi, rq, gfp);
1676 else if (vi->big_packets)
1677 err = add_recvbuf_big(vi, rq, gfp);
1679 err = add_recvbuf_small(vi, rq, gfp);
1681 oom = err == -ENOMEM;
1684 } while (rq->vq->num_free);
1685 if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
1686 unsigned long flags;
1688 flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1690 u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1696 static void skb_recv_done(struct virtqueue *rvq)
1698 struct virtnet_info *vi = rvq->vdev->priv;
1699 struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1701 virtqueue_napi_schedule(&rq->napi, rvq);
1704 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
1708 /* If all buffers were filled by other side before we napi_enabled, we
1709 * won't get another interrupt, so process any outstanding packets now.
1710 * Call local_bh_enable after to trigger softIRQ processing.
1713 virtqueue_napi_schedule(napi, vq);
1717 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1718 struct virtqueue *vq,
1719 struct napi_struct *napi)
1724 /* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1725 * enable the feature if this is likely affine with the transmit path.
1727 if (!vi->affinity_hint_set) {
1732 return virtnet_napi_enable(vq, napi);
1735 static void virtnet_napi_tx_disable(struct napi_struct *napi)
1741 static void refill_work(struct work_struct *work)
1743 struct virtnet_info *vi =
1744 container_of(work, struct virtnet_info, refill.work);
1748 for (i = 0; i < vi->curr_queue_pairs; i++) {
1749 struct receive_queue *rq = &vi->rq[i];
1751 napi_disable(&rq->napi);
1752 still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1753 virtnet_napi_enable(rq->vq, &rq->napi);
1755 /* In theory, this can happen: if we don't get any buffers in
1756 * we will *never* try to fill again.
1759 schedule_delayed_work(&vi->refill, HZ/2);
1763 static int virtnet_receive(struct receive_queue *rq, int budget,
1764 unsigned int *xdp_xmit)
1766 struct virtnet_info *vi = rq->vq->vdev->priv;
1767 struct virtnet_rq_stats stats = {};
1772 if (!vi->big_packets || vi->mergeable_rx_bufs) {
1775 while (stats.packets < budget &&
1776 (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1777 receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1781 while (stats.packets < budget &&
1782 (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1783 receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1788 if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1789 if (!try_fill_recv(vi, rq, GFP_ATOMIC)) {
1790 spin_lock(&vi->refill_lock);
1791 if (vi->refill_enabled)
1792 schedule_delayed_work(&vi->refill, 0);
1793 spin_unlock(&vi->refill_lock);
1797 u64_stats_update_begin(&rq->stats.syncp);
1798 for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1799 size_t offset = virtnet_rq_stats_desc[i].offset;
1802 item = (u64 *)((u8 *)&rq->stats + offset);
1803 *item += *(u64 *)((u8 *)&stats + offset);
1805 u64_stats_update_end(&rq->stats.syncp);
1807 return stats.packets;
1810 static void virtnet_poll_cleantx(struct receive_queue *rq)
1812 struct virtnet_info *vi = rq->vq->vdev->priv;
1813 unsigned int index = vq2rxq(rq->vq);
1814 struct send_queue *sq = &vi->sq[index];
1815 struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
1817 if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
1820 if (__netif_tx_trylock(txq)) {
1822 __netif_tx_unlock(txq);
1827 virtqueue_disable_cb(sq->vq);
1828 free_old_xmit_skbs(sq, true);
1829 } while (unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1831 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1832 netif_tx_wake_queue(txq);
1834 __netif_tx_unlock(txq);
1838 static int virtnet_poll(struct napi_struct *napi, int budget)
1840 struct receive_queue *rq =
1841 container_of(napi, struct receive_queue, napi);
1842 struct virtnet_info *vi = rq->vq->vdev->priv;
1843 struct send_queue *sq;
1844 unsigned int received;
1845 unsigned int xdp_xmit = 0;
1847 virtnet_poll_cleantx(rq);
1849 received = virtnet_receive(rq, budget, &xdp_xmit);
1851 if (xdp_xmit & VIRTIO_XDP_REDIR)
1854 /* Out of packets? */
1855 if (received < budget)
1856 virtqueue_napi_complete(napi, rq->vq, received);
1858 if (xdp_xmit & VIRTIO_XDP_TX) {
1859 sq = virtnet_xdp_get_sq(vi);
1860 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1861 u64_stats_update_begin(&sq->stats.syncp);
1863 u64_stats_update_end(&sq->stats.syncp);
1865 virtnet_xdp_put_sq(vi, sq);
1871 static void virtnet_disable_queue_pair(struct virtnet_info *vi, int qp_index)
1873 virtnet_napi_tx_disable(&vi->sq[qp_index].napi);
1874 napi_disable(&vi->rq[qp_index].napi);
1875 xdp_rxq_info_unreg(&vi->rq[qp_index].xdp_rxq);
1878 static int virtnet_enable_queue_pair(struct virtnet_info *vi, int qp_index)
1880 struct net_device *dev = vi->dev;
1883 err = xdp_rxq_info_reg(&vi->rq[qp_index].xdp_rxq, dev, qp_index,
1884 vi->rq[qp_index].napi.napi_id);
1888 err = xdp_rxq_info_reg_mem_model(&vi->rq[qp_index].xdp_rxq,
1889 MEM_TYPE_PAGE_SHARED, NULL);
1891 goto err_xdp_reg_mem_model;
1893 virtnet_napi_enable(vi->rq[qp_index].vq, &vi->rq[qp_index].napi);
1894 virtnet_napi_tx_enable(vi, vi->sq[qp_index].vq, &vi->sq[qp_index].napi);
1898 err_xdp_reg_mem_model:
1899 xdp_rxq_info_unreg(&vi->rq[qp_index].xdp_rxq);
1903 static int virtnet_open(struct net_device *dev)
1905 struct virtnet_info *vi = netdev_priv(dev);
1908 enable_delayed_refill(vi);
1910 for (i = 0; i < vi->max_queue_pairs; i++) {
1911 if (i < vi->curr_queue_pairs)
1912 /* Make sure we have some buffers: if oom use wq. */
1913 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1914 schedule_delayed_work(&vi->refill, 0);
1916 err = virtnet_enable_queue_pair(vi, i);
1924 disable_delayed_refill(vi);
1925 cancel_delayed_work_sync(&vi->refill);
1927 for (i--; i >= 0; i--)
1928 virtnet_disable_queue_pair(vi, i);
1932 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1934 struct send_queue *sq = container_of(napi, struct send_queue, napi);
1935 struct virtnet_info *vi = sq->vq->vdev->priv;
1936 unsigned int index = vq2txq(sq->vq);
1937 struct netdev_queue *txq;
1941 if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
1942 /* We don't need to enable cb for XDP */
1943 napi_complete_done(napi, 0);
1947 txq = netdev_get_tx_queue(vi->dev, index);
1948 __netif_tx_lock(txq, raw_smp_processor_id());
1949 virtqueue_disable_cb(sq->vq);
1950 free_old_xmit_skbs(sq, true);
1952 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1953 netif_tx_wake_queue(txq);
1955 opaque = virtqueue_enable_cb_prepare(sq->vq);
1957 done = napi_complete_done(napi, 0);
1960 virtqueue_disable_cb(sq->vq);
1962 __netif_tx_unlock(txq);
1965 if (unlikely(virtqueue_poll(sq->vq, opaque))) {
1966 if (napi_schedule_prep(napi)) {
1967 __netif_tx_lock(txq, raw_smp_processor_id());
1968 virtqueue_disable_cb(sq->vq);
1969 __netif_tx_unlock(txq);
1970 __napi_schedule(napi);
1978 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1980 struct virtio_net_hdr_mrg_rxbuf *hdr;
1981 const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1982 struct virtnet_info *vi = sq->vq->vdev->priv;
1984 unsigned hdr_len = vi->hdr_len;
1987 pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1989 can_push = vi->any_header_sg &&
1990 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1991 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1992 /* Even if we can, don't push here yet as this would skew
1993 * csum_start offset below. */
1995 hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1997 hdr = skb_vnet_hdr(skb);
1999 if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
2000 virtio_is_little_endian(vi->vdev), false,
2004 if (vi->mergeable_rx_bufs)
2005 hdr->num_buffers = 0;
2007 sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
2009 __skb_push(skb, hdr_len);
2010 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
2011 if (unlikely(num_sg < 0))
2013 /* Pull header back to avoid skew in tx bytes calculations. */
2014 __skb_pull(skb, hdr_len);
2016 sg_set_buf(sq->sg, hdr, hdr_len);
2017 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
2018 if (unlikely(num_sg < 0))
2022 return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
2025 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
2027 struct virtnet_info *vi = netdev_priv(dev);
2028 int qnum = skb_get_queue_mapping(skb);
2029 struct send_queue *sq = &vi->sq[qnum];
2031 struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
2032 bool kick = !netdev_xmit_more();
2033 bool use_napi = sq->napi.weight;
2035 /* Free up any pending old buffers before queueing new ones. */
2038 virtqueue_disable_cb(sq->vq);
2040 free_old_xmit_skbs(sq, false);
2042 } while (use_napi && kick &&
2043 unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
2045 /* timestamp packet in software */
2046 skb_tx_timestamp(skb);
2048 /* Try to transmit */
2049 err = xmit_skb(sq, skb);
2051 /* This should not happen! */
2052 if (unlikely(err)) {
2053 dev->stats.tx_fifo_errors++;
2054 if (net_ratelimit())
2056 "Unexpected TXQ (%d) queue failure: %d\n",
2058 dev->stats.tx_dropped++;
2059 dev_kfree_skb_any(skb);
2060 return NETDEV_TX_OK;
2063 /* Don't wait up for transmitted skbs to be freed. */
2069 check_sq_full_and_disable(vi, dev, sq);
2071 if (kick || netif_xmit_stopped(txq)) {
2072 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
2073 u64_stats_update_begin(&sq->stats.syncp);
2075 u64_stats_update_end(&sq->stats.syncp);
2079 return NETDEV_TX_OK;
2082 static int virtnet_rx_resize(struct virtnet_info *vi,
2083 struct receive_queue *rq, u32 ring_num)
2085 bool running = netif_running(vi->dev);
2088 qindex = rq - vi->rq;
2091 napi_disable(&rq->napi);
2093 err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_free_unused_buf);
2095 netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
2097 if (!try_fill_recv(vi, rq, GFP_KERNEL))
2098 schedule_delayed_work(&vi->refill, 0);
2101 virtnet_napi_enable(rq->vq, &rq->napi);
2105 static int virtnet_tx_resize(struct virtnet_info *vi,
2106 struct send_queue *sq, u32 ring_num)
2108 bool running = netif_running(vi->dev);
2109 struct netdev_queue *txq;
2112 qindex = sq - vi->sq;
2115 virtnet_napi_tx_disable(&sq->napi);
2117 txq = netdev_get_tx_queue(vi->dev, qindex);
2119 /* 1. wait all ximt complete
2120 * 2. fix the race of netif_stop_subqueue() vs netif_start_subqueue()
2122 __netif_tx_lock_bh(txq);
2124 /* Prevent rx poll from accessing sq. */
2127 /* Prevent the upper layer from trying to send packets. */
2128 netif_stop_subqueue(vi->dev, qindex);
2130 __netif_tx_unlock_bh(txq);
2132 err = virtqueue_resize(sq->vq, ring_num, virtnet_sq_free_unused_buf);
2134 netdev_err(vi->dev, "resize tx fail: tx queue index: %d err: %d\n", qindex, err);
2136 __netif_tx_lock_bh(txq);
2138 netif_tx_wake_queue(txq);
2139 __netif_tx_unlock_bh(txq);
2142 virtnet_napi_tx_enable(vi, sq->vq, &sq->napi);
2147 * Send command via the control virtqueue and check status. Commands
2148 * supported by the hypervisor, as indicated by feature bits, should
2149 * never fail unless improperly formatted.
2151 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
2152 struct scatterlist *out)
2154 struct scatterlist *sgs[4], hdr, stat;
2155 unsigned out_num = 0, tmp;
2158 /* Caller should know better */
2159 BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
2161 vi->ctrl->status = ~0;
2162 vi->ctrl->hdr.class = class;
2163 vi->ctrl->hdr.cmd = cmd;
2165 sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
2166 sgs[out_num++] = &hdr;
2169 sgs[out_num++] = out;
2171 /* Add return status. */
2172 sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
2173 sgs[out_num] = &stat;
2175 BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
2176 ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
2178 dev_warn(&vi->vdev->dev,
2179 "Failed to add sgs for command vq: %d\n.", ret);
2183 if (unlikely(!virtqueue_kick(vi->cvq)))
2184 return vi->ctrl->status == VIRTIO_NET_OK;
2186 /* Spin for a response, the kick causes an ioport write, trapping
2187 * into the hypervisor, so the request should be handled immediately.
2189 while (!virtqueue_get_buf(vi->cvq, &tmp) &&
2190 !virtqueue_is_broken(vi->cvq))
2193 return vi->ctrl->status == VIRTIO_NET_OK;
2196 static int virtnet_set_mac_address(struct net_device *dev, void *p)
2198 struct virtnet_info *vi = netdev_priv(dev);
2199 struct virtio_device *vdev = vi->vdev;
2201 struct sockaddr *addr;
2202 struct scatterlist sg;
2204 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2207 addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
2211 ret = eth_prepare_mac_addr_change(dev, addr);
2215 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
2216 sg_init_one(&sg, addr->sa_data, dev->addr_len);
2217 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2218 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
2219 dev_warn(&vdev->dev,
2220 "Failed to set mac address by vq command.\n");
2224 } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
2225 !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2228 /* Naturally, this has an atomicity problem. */
2229 for (i = 0; i < dev->addr_len; i++)
2230 virtio_cwrite8(vdev,
2231 offsetof(struct virtio_net_config, mac) +
2232 i, addr->sa_data[i]);
2235 eth_commit_mac_addr_change(dev, p);
2243 static void virtnet_stats(struct net_device *dev,
2244 struct rtnl_link_stats64 *tot)
2246 struct virtnet_info *vi = netdev_priv(dev);
2250 for (i = 0; i < vi->max_queue_pairs; i++) {
2251 u64 tpackets, tbytes, terrors, rpackets, rbytes, rdrops;
2252 struct receive_queue *rq = &vi->rq[i];
2253 struct send_queue *sq = &vi->sq[i];
2256 start = u64_stats_fetch_begin(&sq->stats.syncp);
2257 tpackets = sq->stats.packets;
2258 tbytes = sq->stats.bytes;
2259 terrors = sq->stats.tx_timeouts;
2260 } while (u64_stats_fetch_retry(&sq->stats.syncp, start));
2263 start = u64_stats_fetch_begin(&rq->stats.syncp);
2264 rpackets = rq->stats.packets;
2265 rbytes = rq->stats.bytes;
2266 rdrops = rq->stats.drops;
2267 } while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2269 tot->rx_packets += rpackets;
2270 tot->tx_packets += tpackets;
2271 tot->rx_bytes += rbytes;
2272 tot->tx_bytes += tbytes;
2273 tot->rx_dropped += rdrops;
2274 tot->tx_errors += terrors;
2277 tot->tx_dropped = dev->stats.tx_dropped;
2278 tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
2279 tot->rx_length_errors = dev->stats.rx_length_errors;
2280 tot->rx_frame_errors = dev->stats.rx_frame_errors;
2283 static void virtnet_ack_link_announce(struct virtnet_info *vi)
2286 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
2287 VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
2288 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
2292 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2294 struct scatterlist sg;
2295 struct net_device *dev = vi->dev;
2297 if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
2300 vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
2301 sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
2303 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2304 VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
2305 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
2309 vi->curr_queue_pairs = queue_pairs;
2310 /* virtnet_open() will refill when device is going to up. */
2311 if (dev->flags & IFF_UP)
2312 schedule_delayed_work(&vi->refill, 0);
2318 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2323 err = _virtnet_set_queues(vi, queue_pairs);
2328 static int virtnet_close(struct net_device *dev)
2330 struct virtnet_info *vi = netdev_priv(dev);
2333 /* Make sure NAPI doesn't schedule refill work */
2334 disable_delayed_refill(vi);
2335 /* Make sure refill_work doesn't re-enable napi! */
2336 cancel_delayed_work_sync(&vi->refill);
2338 for (i = 0; i < vi->max_queue_pairs; i++)
2339 virtnet_disable_queue_pair(vi, i);
2344 static void virtnet_set_rx_mode(struct net_device *dev)
2346 struct virtnet_info *vi = netdev_priv(dev);
2347 struct scatterlist sg[2];
2348 struct virtio_net_ctrl_mac *mac_data;
2349 struct netdev_hw_addr *ha;
2355 /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
2356 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
2359 vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
2360 vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
2362 sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
2364 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2365 VIRTIO_NET_CTRL_RX_PROMISC, sg))
2366 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
2367 vi->ctrl->promisc ? "en" : "dis");
2369 sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
2371 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2372 VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
2373 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
2374 vi->ctrl->allmulti ? "en" : "dis");
2376 uc_count = netdev_uc_count(dev);
2377 mc_count = netdev_mc_count(dev);
2378 /* MAC filter - use one buffer for both lists */
2379 buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
2380 (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
2385 sg_init_table(sg, 2);
2387 /* Store the unicast list and count in the front of the buffer */
2388 mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2390 netdev_for_each_uc_addr(ha, dev)
2391 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2393 sg_set_buf(&sg[0], mac_data,
2394 sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2396 /* multicast list and count fill the end */
2397 mac_data = (void *)&mac_data->macs[uc_count][0];
2399 mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2401 netdev_for_each_mc_addr(ha, dev)
2402 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2404 sg_set_buf(&sg[1], mac_data,
2405 sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2407 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2408 VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2409 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2414 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
2415 __be16 proto, u16 vid)
2417 struct virtnet_info *vi = netdev_priv(dev);
2418 struct scatterlist sg;
2420 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2421 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2423 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2424 VIRTIO_NET_CTRL_VLAN_ADD, &sg))
2425 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
2429 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
2430 __be16 proto, u16 vid)
2432 struct virtnet_info *vi = netdev_priv(dev);
2433 struct scatterlist sg;
2435 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2436 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2438 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2439 VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2440 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2444 static void virtnet_clean_affinity(struct virtnet_info *vi)
2448 if (vi->affinity_hint_set) {
2449 for (i = 0; i < vi->max_queue_pairs; i++) {
2450 virtqueue_set_affinity(vi->rq[i].vq, NULL);
2451 virtqueue_set_affinity(vi->sq[i].vq, NULL);
2454 vi->affinity_hint_set = false;
2458 static void virtnet_set_affinity(struct virtnet_info *vi)
2467 if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2468 virtnet_clean_affinity(vi);
2472 num_cpu = num_online_cpus();
2473 stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2474 stragglers = num_cpu >= vi->curr_queue_pairs ?
2475 num_cpu % vi->curr_queue_pairs :
2477 cpu = cpumask_first(cpu_online_mask);
2479 for (i = 0; i < vi->curr_queue_pairs; i++) {
2480 group_size = stride + (i < stragglers ? 1 : 0);
2482 for (j = 0; j < group_size; j++) {
2483 cpumask_set_cpu(cpu, mask);
2484 cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2487 virtqueue_set_affinity(vi->rq[i].vq, mask);
2488 virtqueue_set_affinity(vi->sq[i].vq, mask);
2489 __netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2490 cpumask_clear(mask);
2493 vi->affinity_hint_set = true;
2494 free_cpumask_var(mask);
2497 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2499 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2501 virtnet_set_affinity(vi);
2505 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2507 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2509 virtnet_set_affinity(vi);
2513 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2515 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2518 virtnet_clean_affinity(vi);
2522 static enum cpuhp_state virtionet_online;
2524 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2528 ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2531 ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2535 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2539 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2541 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2542 cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2546 static void virtnet_get_ringparam(struct net_device *dev,
2547 struct ethtool_ringparam *ring,
2548 struct kernel_ethtool_ringparam *kernel_ring,
2549 struct netlink_ext_ack *extack)
2551 struct virtnet_info *vi = netdev_priv(dev);
2553 ring->rx_max_pending = vi->rq[0].vq->num_max;
2554 ring->tx_max_pending = vi->sq[0].vq->num_max;
2555 ring->rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2556 ring->tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2559 static int virtnet_set_ringparam(struct net_device *dev,
2560 struct ethtool_ringparam *ring,
2561 struct kernel_ethtool_ringparam *kernel_ring,
2562 struct netlink_ext_ack *extack)
2564 struct virtnet_info *vi = netdev_priv(dev);
2565 u32 rx_pending, tx_pending;
2566 struct receive_queue *rq;
2567 struct send_queue *sq;
2570 if (ring->rx_mini_pending || ring->rx_jumbo_pending)
2573 rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2574 tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2576 if (ring->rx_pending == rx_pending &&
2577 ring->tx_pending == tx_pending)
2580 if (ring->rx_pending > vi->rq[0].vq->num_max)
2583 if (ring->tx_pending > vi->sq[0].vq->num_max)
2586 for (i = 0; i < vi->max_queue_pairs; i++) {
2590 if (ring->tx_pending != tx_pending) {
2591 err = virtnet_tx_resize(vi, sq, ring->tx_pending);
2596 if (ring->rx_pending != rx_pending) {
2597 err = virtnet_rx_resize(vi, rq, ring->rx_pending);
2606 static bool virtnet_commit_rss_command(struct virtnet_info *vi)
2608 struct net_device *dev = vi->dev;
2609 struct scatterlist sgs[4];
2610 unsigned int sg_buf_size;
2613 sg_init_table(sgs, 4);
2615 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, indirection_table);
2616 sg_set_buf(&sgs[0], &vi->ctrl->rss, sg_buf_size);
2618 sg_buf_size = sizeof(uint16_t) * (vi->ctrl->rss.indirection_table_mask + 1);
2619 sg_set_buf(&sgs[1], vi->ctrl->rss.indirection_table, sg_buf_size);
2621 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, key)
2622 - offsetof(struct virtio_net_ctrl_rss, max_tx_vq);
2623 sg_set_buf(&sgs[2], &vi->ctrl->rss.max_tx_vq, sg_buf_size);
2625 sg_buf_size = vi->rss_key_size;
2626 sg_set_buf(&sgs[3], vi->ctrl->rss.key, sg_buf_size);
2628 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2629 vi->has_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG
2630 : VIRTIO_NET_CTRL_MQ_HASH_CONFIG, sgs)) {
2631 dev_warn(&dev->dev, "VIRTIONET issue with committing RSS sgs\n");
2637 static void virtnet_init_default_rss(struct virtnet_info *vi)
2642 vi->ctrl->rss.hash_types = vi->rss_hash_types_supported;
2643 vi->rss_hash_types_saved = vi->rss_hash_types_supported;
2644 vi->ctrl->rss.indirection_table_mask = vi->rss_indir_table_size
2645 ? vi->rss_indir_table_size - 1 : 0;
2646 vi->ctrl->rss.unclassified_queue = 0;
2648 for (; i < vi->rss_indir_table_size; ++i) {
2649 indir_val = ethtool_rxfh_indir_default(i, vi->curr_queue_pairs);
2650 vi->ctrl->rss.indirection_table[i] = indir_val;
2653 vi->ctrl->rss.max_tx_vq = vi->curr_queue_pairs;
2654 vi->ctrl->rss.hash_key_length = vi->rss_key_size;
2656 netdev_rss_key_fill(vi->ctrl->rss.key, vi->rss_key_size);
2659 static void virtnet_get_hashflow(const struct virtnet_info *vi, struct ethtool_rxnfc *info)
2662 switch (info->flow_type) {
2664 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
2665 info->data = RXH_IP_SRC | RXH_IP_DST |
2666 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2667 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2668 info->data = RXH_IP_SRC | RXH_IP_DST;
2672 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
2673 info->data = RXH_IP_SRC | RXH_IP_DST |
2674 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2675 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2676 info->data = RXH_IP_SRC | RXH_IP_DST;
2680 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
2681 info->data = RXH_IP_SRC | RXH_IP_DST |
2682 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2683 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2684 info->data = RXH_IP_SRC | RXH_IP_DST;
2688 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
2689 info->data = RXH_IP_SRC | RXH_IP_DST |
2690 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2691 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2692 info->data = RXH_IP_SRC | RXH_IP_DST;
2696 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4)
2697 info->data = RXH_IP_SRC | RXH_IP_DST;
2701 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6)
2702 info->data = RXH_IP_SRC | RXH_IP_DST;
2711 static bool virtnet_set_hashflow(struct virtnet_info *vi, struct ethtool_rxnfc *info)
2713 u32 new_hashtypes = vi->rss_hash_types_saved;
2714 bool is_disable = info->data & RXH_DISCARD;
2715 bool is_l4 = info->data == (RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3);
2717 /* supports only 'sd', 'sdfn' and 'r' */
2718 if (!((info->data == (RXH_IP_SRC | RXH_IP_DST)) | is_l4 | is_disable))
2721 switch (info->flow_type) {
2723 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_TCPv4);
2725 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2726 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0);
2729 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_UDPv4);
2731 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2732 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0);
2735 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2737 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2740 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_TCPv6);
2742 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2743 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0);
2746 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_UDPv6);
2748 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2749 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0);
2752 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2754 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2757 /* unsupported flow */
2761 /* if unsupported hashtype was set */
2762 if (new_hashtypes != (new_hashtypes & vi->rss_hash_types_supported))
2765 if (new_hashtypes != vi->rss_hash_types_saved) {
2766 vi->rss_hash_types_saved = new_hashtypes;
2767 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
2768 if (vi->dev->features & NETIF_F_RXHASH)
2769 return virtnet_commit_rss_command(vi);
2775 static void virtnet_get_drvinfo(struct net_device *dev,
2776 struct ethtool_drvinfo *info)
2778 struct virtnet_info *vi = netdev_priv(dev);
2779 struct virtio_device *vdev = vi->vdev;
2781 strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2782 strscpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2783 strscpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2787 /* TODO: Eliminate OOO packets during switching */
2788 static int virtnet_set_channels(struct net_device *dev,
2789 struct ethtool_channels *channels)
2791 struct virtnet_info *vi = netdev_priv(dev);
2792 u16 queue_pairs = channels->combined_count;
2795 /* We don't support separate rx/tx channels.
2796 * We don't allow setting 'other' channels.
2798 if (channels->rx_count || channels->tx_count || channels->other_count)
2801 if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2804 /* For now we don't support modifying channels while XDP is loaded
2805 * also when XDP is loaded all RX queues have XDP programs so we only
2806 * need to check a single RX queue.
2808 if (vi->rq[0].xdp_prog)
2812 err = _virtnet_set_queues(vi, queue_pairs);
2817 virtnet_set_affinity(vi);
2820 netif_set_real_num_tx_queues(dev, queue_pairs);
2821 netif_set_real_num_rx_queues(dev, queue_pairs);
2826 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2828 struct virtnet_info *vi = netdev_priv(dev);
2832 switch (stringset) {
2834 for (i = 0; i < vi->curr_queue_pairs; i++) {
2835 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
2836 ethtool_sprintf(&p, "rx_queue_%u_%s", i,
2837 virtnet_rq_stats_desc[j].desc);
2840 for (i = 0; i < vi->curr_queue_pairs; i++) {
2841 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
2842 ethtool_sprintf(&p, "tx_queue_%u_%s", i,
2843 virtnet_sq_stats_desc[j].desc);
2849 static int virtnet_get_sset_count(struct net_device *dev, int sset)
2851 struct virtnet_info *vi = netdev_priv(dev);
2855 return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2856 VIRTNET_SQ_STATS_LEN);
2862 static void virtnet_get_ethtool_stats(struct net_device *dev,
2863 struct ethtool_stats *stats, u64 *data)
2865 struct virtnet_info *vi = netdev_priv(dev);
2866 unsigned int idx = 0, start, i, j;
2867 const u8 *stats_base;
2870 for (i = 0; i < vi->curr_queue_pairs; i++) {
2871 struct receive_queue *rq = &vi->rq[i];
2873 stats_base = (u8 *)&rq->stats;
2875 start = u64_stats_fetch_begin(&rq->stats.syncp);
2876 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2877 offset = virtnet_rq_stats_desc[j].offset;
2878 data[idx + j] = *(u64 *)(stats_base + offset);
2880 } while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2881 idx += VIRTNET_RQ_STATS_LEN;
2884 for (i = 0; i < vi->curr_queue_pairs; i++) {
2885 struct send_queue *sq = &vi->sq[i];
2887 stats_base = (u8 *)&sq->stats;
2889 start = u64_stats_fetch_begin(&sq->stats.syncp);
2890 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2891 offset = virtnet_sq_stats_desc[j].offset;
2892 data[idx + j] = *(u64 *)(stats_base + offset);
2894 } while (u64_stats_fetch_retry(&sq->stats.syncp, start));
2895 idx += VIRTNET_SQ_STATS_LEN;
2899 static void virtnet_get_channels(struct net_device *dev,
2900 struct ethtool_channels *channels)
2902 struct virtnet_info *vi = netdev_priv(dev);
2904 channels->combined_count = vi->curr_queue_pairs;
2905 channels->max_combined = vi->max_queue_pairs;
2906 channels->max_other = 0;
2907 channels->rx_count = 0;
2908 channels->tx_count = 0;
2909 channels->other_count = 0;
2912 static int virtnet_set_link_ksettings(struct net_device *dev,
2913 const struct ethtool_link_ksettings *cmd)
2915 struct virtnet_info *vi = netdev_priv(dev);
2917 return ethtool_virtdev_set_link_ksettings(dev, cmd,
2918 &vi->speed, &vi->duplex);
2921 static int virtnet_get_link_ksettings(struct net_device *dev,
2922 struct ethtool_link_ksettings *cmd)
2924 struct virtnet_info *vi = netdev_priv(dev);
2926 cmd->base.speed = vi->speed;
2927 cmd->base.duplex = vi->duplex;
2928 cmd->base.port = PORT_OTHER;
2933 static int virtnet_send_notf_coal_cmds(struct virtnet_info *vi,
2934 struct ethtool_coalesce *ec)
2936 struct scatterlist sgs_tx, sgs_rx;
2937 struct virtio_net_ctrl_coal_tx coal_tx;
2938 struct virtio_net_ctrl_coal_rx coal_rx;
2940 coal_tx.tx_usecs = cpu_to_le32(ec->tx_coalesce_usecs);
2941 coal_tx.tx_max_packets = cpu_to_le32(ec->tx_max_coalesced_frames);
2942 sg_init_one(&sgs_tx, &coal_tx, sizeof(coal_tx));
2944 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2945 VIRTIO_NET_CTRL_NOTF_COAL_TX_SET,
2949 /* Save parameters */
2950 vi->tx_usecs = ec->tx_coalesce_usecs;
2951 vi->tx_max_packets = ec->tx_max_coalesced_frames;
2953 coal_rx.rx_usecs = cpu_to_le32(ec->rx_coalesce_usecs);
2954 coal_rx.rx_max_packets = cpu_to_le32(ec->rx_max_coalesced_frames);
2955 sg_init_one(&sgs_rx, &coal_rx, sizeof(coal_rx));
2957 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
2958 VIRTIO_NET_CTRL_NOTF_COAL_RX_SET,
2962 /* Save parameters */
2963 vi->rx_usecs = ec->rx_coalesce_usecs;
2964 vi->rx_max_packets = ec->rx_max_coalesced_frames;
2969 static int virtnet_coal_params_supported(struct ethtool_coalesce *ec)
2971 /* usecs coalescing is supported only if VIRTIO_NET_F_NOTF_COAL
2972 * feature is negotiated.
2974 if (ec->rx_coalesce_usecs || ec->tx_coalesce_usecs)
2977 if (ec->tx_max_coalesced_frames > 1 ||
2978 ec->rx_max_coalesced_frames != 1)
2984 static int virtnet_set_coalesce(struct net_device *dev,
2985 struct ethtool_coalesce *ec,
2986 struct kernel_ethtool_coalesce *kernel_coal,
2987 struct netlink_ext_ack *extack)
2989 struct virtnet_info *vi = netdev_priv(dev);
2990 int ret, i, napi_weight;
2991 bool update_napi = false;
2993 /* Can't change NAPI weight if the link is up */
2994 napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
2995 if (napi_weight ^ vi->sq[0].napi.weight) {
2996 if (dev->flags & IFF_UP)
3002 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL))
3003 ret = virtnet_send_notf_coal_cmds(vi, ec);
3005 ret = virtnet_coal_params_supported(ec);
3011 for (i = 0; i < vi->max_queue_pairs; i++)
3012 vi->sq[i].napi.weight = napi_weight;
3018 static int virtnet_get_coalesce(struct net_device *dev,
3019 struct ethtool_coalesce *ec,
3020 struct kernel_ethtool_coalesce *kernel_coal,
3021 struct netlink_ext_ack *extack)
3023 struct virtnet_info *vi = netdev_priv(dev);
3025 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
3026 ec->rx_coalesce_usecs = vi->rx_usecs;
3027 ec->tx_coalesce_usecs = vi->tx_usecs;
3028 ec->tx_max_coalesced_frames = vi->tx_max_packets;
3029 ec->rx_max_coalesced_frames = vi->rx_max_packets;
3031 ec->rx_max_coalesced_frames = 1;
3033 if (vi->sq[0].napi.weight)
3034 ec->tx_max_coalesced_frames = 1;
3040 static void virtnet_init_settings(struct net_device *dev)
3042 struct virtnet_info *vi = netdev_priv(dev);
3044 vi->speed = SPEED_UNKNOWN;
3045 vi->duplex = DUPLEX_UNKNOWN;
3048 static void virtnet_update_settings(struct virtnet_info *vi)
3053 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
3056 virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
3058 if (ethtool_validate_speed(speed))
3061 virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
3063 if (ethtool_validate_duplex(duplex))
3064 vi->duplex = duplex;
3067 static u32 virtnet_get_rxfh_key_size(struct net_device *dev)
3069 return ((struct virtnet_info *)netdev_priv(dev))->rss_key_size;
3072 static u32 virtnet_get_rxfh_indir_size(struct net_device *dev)
3074 return ((struct virtnet_info *)netdev_priv(dev))->rss_indir_table_size;
3077 static int virtnet_get_rxfh(struct net_device *dev, u32 *indir, u8 *key, u8 *hfunc)
3079 struct virtnet_info *vi = netdev_priv(dev);
3083 for (i = 0; i < vi->rss_indir_table_size; ++i)
3084 indir[i] = vi->ctrl->rss.indirection_table[i];
3088 memcpy(key, vi->ctrl->rss.key, vi->rss_key_size);
3091 *hfunc = ETH_RSS_HASH_TOP;
3096 static int virtnet_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key, const u8 hfunc)
3098 struct virtnet_info *vi = netdev_priv(dev);
3101 if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
3105 for (i = 0; i < vi->rss_indir_table_size; ++i)
3106 vi->ctrl->rss.indirection_table[i] = indir[i];
3109 memcpy(vi->ctrl->rss.key, key, vi->rss_key_size);
3111 virtnet_commit_rss_command(vi);
3116 static int virtnet_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rule_locs)
3118 struct virtnet_info *vi = netdev_priv(dev);
3121 switch (info->cmd) {
3122 case ETHTOOL_GRXRINGS:
3123 info->data = vi->curr_queue_pairs;
3126 virtnet_get_hashflow(vi, info);
3135 static int virtnet_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info)
3137 struct virtnet_info *vi = netdev_priv(dev);
3140 switch (info->cmd) {
3142 if (!virtnet_set_hashflow(vi, info))
3153 static const struct ethtool_ops virtnet_ethtool_ops = {
3154 .supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES |
3155 ETHTOOL_COALESCE_USECS,
3156 .get_drvinfo = virtnet_get_drvinfo,
3157 .get_link = ethtool_op_get_link,
3158 .get_ringparam = virtnet_get_ringparam,
3159 .set_ringparam = virtnet_set_ringparam,
3160 .get_strings = virtnet_get_strings,
3161 .get_sset_count = virtnet_get_sset_count,
3162 .get_ethtool_stats = virtnet_get_ethtool_stats,
3163 .set_channels = virtnet_set_channels,
3164 .get_channels = virtnet_get_channels,
3165 .get_ts_info = ethtool_op_get_ts_info,
3166 .get_link_ksettings = virtnet_get_link_ksettings,
3167 .set_link_ksettings = virtnet_set_link_ksettings,
3168 .set_coalesce = virtnet_set_coalesce,
3169 .get_coalesce = virtnet_get_coalesce,
3170 .get_rxfh_key_size = virtnet_get_rxfh_key_size,
3171 .get_rxfh_indir_size = virtnet_get_rxfh_indir_size,
3172 .get_rxfh = virtnet_get_rxfh,
3173 .set_rxfh = virtnet_set_rxfh,
3174 .get_rxnfc = virtnet_get_rxnfc,
3175 .set_rxnfc = virtnet_set_rxnfc,
3178 static void virtnet_freeze_down(struct virtio_device *vdev)
3180 struct virtnet_info *vi = vdev->priv;
3182 /* Make sure no work handler is accessing the device */
3183 flush_work(&vi->config_work);
3185 netif_tx_lock_bh(vi->dev);
3186 netif_device_detach(vi->dev);
3187 netif_tx_unlock_bh(vi->dev);
3188 if (netif_running(vi->dev))
3189 virtnet_close(vi->dev);
3192 static int init_vqs(struct virtnet_info *vi);
3194 static int virtnet_restore_up(struct virtio_device *vdev)
3196 struct virtnet_info *vi = vdev->priv;
3203 virtio_device_ready(vdev);
3205 enable_delayed_refill(vi);
3207 if (netif_running(vi->dev)) {
3208 err = virtnet_open(vi->dev);
3213 netif_tx_lock_bh(vi->dev);
3214 netif_device_attach(vi->dev);
3215 netif_tx_unlock_bh(vi->dev);
3219 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
3221 struct scatterlist sg;
3222 vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
3224 sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
3226 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
3227 VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
3228 dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
3235 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
3239 if (!vi->guest_offloads)
3242 return virtnet_set_guest_offloads(vi, offloads);
3245 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
3247 u64 offloads = vi->guest_offloads;
3249 if (!vi->guest_offloads)
3252 return virtnet_set_guest_offloads(vi, offloads);
3255 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
3256 struct netlink_ext_ack *extack)
3258 unsigned int room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
3259 sizeof(struct skb_shared_info));
3260 unsigned int max_sz = PAGE_SIZE - room - ETH_HLEN;
3261 struct virtnet_info *vi = netdev_priv(dev);
3262 struct bpf_prog *old_prog;
3263 u16 xdp_qp = 0, curr_qp;
3266 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
3267 && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3268 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3269 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3270 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3271 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM) ||
3272 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) ||
3273 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6))) {
3274 NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
3278 if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
3279 NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
3283 if (prog && !prog->aux->xdp_has_frags && dev->mtu > max_sz) {
3284 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP without frags");
3285 netdev_warn(dev, "single-buffer XDP requires MTU less than %u\n", max_sz);
3289 curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
3291 xdp_qp = nr_cpu_ids;
3293 /* XDP requires extra queues for XDP_TX */
3294 if (curr_qp + xdp_qp > vi->max_queue_pairs) {
3295 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",
3296 curr_qp + xdp_qp, vi->max_queue_pairs);
3300 old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
3301 if (!prog && !old_prog)
3305 bpf_prog_add(prog, vi->max_queue_pairs - 1);
3307 /* Make sure NAPI is not using any XDP TX queues for RX. */
3308 if (netif_running(dev)) {
3309 for (i = 0; i < vi->max_queue_pairs; i++) {
3310 napi_disable(&vi->rq[i].napi);
3311 virtnet_napi_tx_disable(&vi->sq[i].napi);
3316 for (i = 0; i < vi->max_queue_pairs; i++) {
3317 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3319 virtnet_restore_guest_offloads(vi);
3324 err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
3327 netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
3328 vi->xdp_queue_pairs = xdp_qp;
3331 vi->xdp_enabled = true;
3332 for (i = 0; i < vi->max_queue_pairs; i++) {
3333 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3334 if (i == 0 && !old_prog)
3335 virtnet_clear_guest_offloads(vi);
3338 xdp_features_set_redirect_target(dev, true);
3340 xdp_features_clear_redirect_target(dev);
3341 vi->xdp_enabled = false;
3344 for (i = 0; i < vi->max_queue_pairs; i++) {
3346 bpf_prog_put(old_prog);
3347 if (netif_running(dev)) {
3348 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3349 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3358 virtnet_clear_guest_offloads(vi);
3359 for (i = 0; i < vi->max_queue_pairs; i++)
3360 rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
3363 if (netif_running(dev)) {
3364 for (i = 0; i < vi->max_queue_pairs; i++) {
3365 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3366 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3371 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
3375 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
3377 switch (xdp->command) {
3378 case XDP_SETUP_PROG:
3379 return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
3385 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
3388 struct virtnet_info *vi = netdev_priv(dev);
3391 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
3394 ret = snprintf(buf, len, "sby");
3401 static int virtnet_set_features(struct net_device *dev,
3402 netdev_features_t features)
3404 struct virtnet_info *vi = netdev_priv(dev);
3408 if ((dev->features ^ features) & NETIF_F_GRO_HW) {
3409 if (vi->xdp_enabled)
3412 if (features & NETIF_F_GRO_HW)
3413 offloads = vi->guest_offloads_capable;
3415 offloads = vi->guest_offloads_capable &
3416 ~GUEST_OFFLOAD_GRO_HW_MASK;
3418 err = virtnet_set_guest_offloads(vi, offloads);
3421 vi->guest_offloads = offloads;
3424 if ((dev->features ^ features) & NETIF_F_RXHASH) {
3425 if (features & NETIF_F_RXHASH)
3426 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
3428 vi->ctrl->rss.hash_types = VIRTIO_NET_HASH_REPORT_NONE;
3430 if (!virtnet_commit_rss_command(vi))
3437 static void virtnet_tx_timeout(struct net_device *dev, unsigned int txqueue)
3439 struct virtnet_info *priv = netdev_priv(dev);
3440 struct send_queue *sq = &priv->sq[txqueue];
3441 struct netdev_queue *txq = netdev_get_tx_queue(dev, txqueue);
3443 u64_stats_update_begin(&sq->stats.syncp);
3444 sq->stats.tx_timeouts++;
3445 u64_stats_update_end(&sq->stats.syncp);
3447 netdev_err(dev, "TX timeout on queue: %u, sq: %s, vq: 0x%x, name: %s, %u usecs ago\n",
3448 txqueue, sq->name, sq->vq->index, sq->vq->name,
3449 jiffies_to_usecs(jiffies - READ_ONCE(txq->trans_start)));
3452 static const struct net_device_ops virtnet_netdev = {
3453 .ndo_open = virtnet_open,
3454 .ndo_stop = virtnet_close,
3455 .ndo_start_xmit = start_xmit,
3456 .ndo_validate_addr = eth_validate_addr,
3457 .ndo_set_mac_address = virtnet_set_mac_address,
3458 .ndo_set_rx_mode = virtnet_set_rx_mode,
3459 .ndo_get_stats64 = virtnet_stats,
3460 .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
3461 .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
3462 .ndo_bpf = virtnet_xdp,
3463 .ndo_xdp_xmit = virtnet_xdp_xmit,
3464 .ndo_features_check = passthru_features_check,
3465 .ndo_get_phys_port_name = virtnet_get_phys_port_name,
3466 .ndo_set_features = virtnet_set_features,
3467 .ndo_tx_timeout = virtnet_tx_timeout,
3470 static void virtnet_config_changed_work(struct work_struct *work)
3472 struct virtnet_info *vi =
3473 container_of(work, struct virtnet_info, config_work);
3476 if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
3477 struct virtio_net_config, status, &v) < 0)
3480 if (v & VIRTIO_NET_S_ANNOUNCE) {
3481 netdev_notify_peers(vi->dev);
3482 virtnet_ack_link_announce(vi);
3485 /* Ignore unknown (future) status bits */
3486 v &= VIRTIO_NET_S_LINK_UP;
3488 if (vi->status == v)
3493 if (vi->status & VIRTIO_NET_S_LINK_UP) {
3494 virtnet_update_settings(vi);
3495 netif_carrier_on(vi->dev);
3496 netif_tx_wake_all_queues(vi->dev);
3498 netif_carrier_off(vi->dev);
3499 netif_tx_stop_all_queues(vi->dev);
3503 static void virtnet_config_changed(struct virtio_device *vdev)
3505 struct virtnet_info *vi = vdev->priv;
3507 schedule_work(&vi->config_work);
3510 static void virtnet_free_queues(struct virtnet_info *vi)
3514 for (i = 0; i < vi->max_queue_pairs; i++) {
3515 __netif_napi_del(&vi->rq[i].napi);
3516 __netif_napi_del(&vi->sq[i].napi);
3519 /* We called __netif_napi_del(),
3520 * we need to respect an RCU grace period before freeing vi->rq
3529 static void _free_receive_bufs(struct virtnet_info *vi)
3531 struct bpf_prog *old_prog;
3534 for (i = 0; i < vi->max_queue_pairs; i++) {
3535 while (vi->rq[i].pages)
3536 __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
3538 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
3539 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
3541 bpf_prog_put(old_prog);
3545 static void free_receive_bufs(struct virtnet_info *vi)
3548 _free_receive_bufs(vi);
3552 static void free_receive_page_frags(struct virtnet_info *vi)
3555 for (i = 0; i < vi->max_queue_pairs; i++)
3556 if (vi->rq[i].alloc_frag.page)
3557 put_page(vi->rq[i].alloc_frag.page);
3560 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf)
3562 if (!is_xdp_frame(buf))
3565 xdp_return_frame(ptr_to_xdp(buf));
3568 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf)
3570 struct virtnet_info *vi = vq->vdev->priv;
3573 if (vi->mergeable_rx_bufs)
3574 put_page(virt_to_head_page(buf));
3575 else if (vi->big_packets)
3576 give_pages(&vi->rq[i], buf);
3578 put_page(virt_to_head_page(buf));
3581 static void free_unused_bufs(struct virtnet_info *vi)
3586 for (i = 0; i < vi->max_queue_pairs; i++) {
3587 struct virtqueue *vq = vi->sq[i].vq;
3588 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3589 virtnet_sq_free_unused_buf(vq, buf);
3593 for (i = 0; i < vi->max_queue_pairs; i++) {
3594 struct virtqueue *vq = vi->rq[i].vq;
3595 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3596 virtnet_rq_free_unused_buf(vq, buf);
3601 static void virtnet_del_vqs(struct virtnet_info *vi)
3603 struct virtio_device *vdev = vi->vdev;
3605 virtnet_clean_affinity(vi);
3607 vdev->config->del_vqs(vdev);
3609 virtnet_free_queues(vi);
3612 /* How large should a single buffer be so a queue full of these can fit at
3613 * least one full packet?
3614 * Logic below assumes the mergeable buffer header is used.
3616 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
3618 const unsigned int hdr_len = vi->hdr_len;
3619 unsigned int rq_size = virtqueue_get_vring_size(vq);
3620 unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
3621 unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
3622 unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
3624 return max(max(min_buf_len, hdr_len) - hdr_len,
3625 (unsigned int)GOOD_PACKET_LEN);
3628 static int virtnet_find_vqs(struct virtnet_info *vi)
3630 vq_callback_t **callbacks;
3631 struct virtqueue **vqs;
3637 /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
3638 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
3639 * possible control vq.
3641 total_vqs = vi->max_queue_pairs * 2 +
3642 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
3644 /* Allocate space for find_vqs parameters */
3645 vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
3648 callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
3651 names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
3654 if (!vi->big_packets || vi->mergeable_rx_bufs) {
3655 ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
3662 /* Parameters for control virtqueue, if any */
3664 callbacks[total_vqs - 1] = NULL;
3665 names[total_vqs - 1] = "control";
3668 /* Allocate/initialize parameters for send/receive virtqueues */
3669 for (i = 0; i < vi->max_queue_pairs; i++) {
3670 callbacks[rxq2vq(i)] = skb_recv_done;
3671 callbacks[txq2vq(i)] = skb_xmit_done;
3672 sprintf(vi->rq[i].name, "input.%d", i);
3673 sprintf(vi->sq[i].name, "output.%d", i);
3674 names[rxq2vq(i)] = vi->rq[i].name;
3675 names[txq2vq(i)] = vi->sq[i].name;
3677 ctx[rxq2vq(i)] = true;
3680 ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
3686 vi->cvq = vqs[total_vqs - 1];
3687 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
3688 vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
3691 for (i = 0; i < vi->max_queue_pairs; i++) {
3692 vi->rq[i].vq = vqs[rxq2vq(i)];
3693 vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
3694 vi->sq[i].vq = vqs[txq2vq(i)];
3697 /* run here: ret == 0. */
3712 static int virtnet_alloc_queues(struct virtnet_info *vi)
3717 vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
3723 vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
3726 vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
3730 INIT_DELAYED_WORK(&vi->refill, refill_work);
3731 for (i = 0; i < vi->max_queue_pairs; i++) {
3732 vi->rq[i].pages = NULL;
3733 netif_napi_add_weight(vi->dev, &vi->rq[i].napi, virtnet_poll,
3735 netif_napi_add_tx_weight(vi->dev, &vi->sq[i].napi,
3737 napi_tx ? napi_weight : 0);
3739 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
3740 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
3741 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
3743 u64_stats_init(&vi->rq[i].stats.syncp);
3744 u64_stats_init(&vi->sq[i].stats.syncp);
3757 static int init_vqs(struct virtnet_info *vi)
3761 /* Allocate send & receive queues */
3762 ret = virtnet_alloc_queues(vi);
3766 ret = virtnet_find_vqs(vi);
3771 virtnet_set_affinity(vi);
3777 virtnet_free_queues(vi);
3783 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
3786 struct virtnet_info *vi = netdev_priv(queue->dev);
3787 unsigned int queue_index = get_netdev_rx_queue_index(queue);
3788 unsigned int headroom = virtnet_get_headroom(vi);
3789 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
3790 struct ewma_pkt_len *avg;
3792 BUG_ON(queue_index >= vi->max_queue_pairs);
3793 avg = &vi->rq[queue_index].mrg_avg_pkt_len;
3794 return sprintf(buf, "%u\n",
3795 get_mergeable_buf_len(&vi->rq[queue_index], avg,
3796 SKB_DATA_ALIGN(headroom + tailroom)));
3799 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
3800 __ATTR_RO(mergeable_rx_buffer_size);
3802 static struct attribute *virtio_net_mrg_rx_attrs[] = {
3803 &mergeable_rx_buffer_size_attribute.attr,
3807 static const struct attribute_group virtio_net_mrg_rx_group = {
3808 .name = "virtio_net",
3809 .attrs = virtio_net_mrg_rx_attrs
3813 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
3815 const char *fname, const char *dname)
3817 if (!virtio_has_feature(vdev, fbit))
3820 dev_err(&vdev->dev, "device advertises feature %s but not %s",
3826 #define VIRTNET_FAIL_ON(vdev, fbit, dbit) \
3827 virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
3829 static bool virtnet_validate_features(struct virtio_device *vdev)
3831 if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
3832 (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
3833 "VIRTIO_NET_F_CTRL_VQ") ||
3834 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
3835 "VIRTIO_NET_F_CTRL_VQ") ||
3836 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
3837 "VIRTIO_NET_F_CTRL_VQ") ||
3838 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
3839 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
3840 "VIRTIO_NET_F_CTRL_VQ") ||
3841 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_RSS,
3842 "VIRTIO_NET_F_CTRL_VQ") ||
3843 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_HASH_REPORT,
3844 "VIRTIO_NET_F_CTRL_VQ") ||
3845 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_NOTF_COAL,
3846 "VIRTIO_NET_F_CTRL_VQ"))) {
3853 #define MIN_MTU ETH_MIN_MTU
3854 #define MAX_MTU ETH_MAX_MTU
3856 static int virtnet_validate(struct virtio_device *vdev)
3858 if (!vdev->config->get) {
3859 dev_err(&vdev->dev, "%s failure: config access disabled\n",
3864 if (!virtnet_validate_features(vdev))
3867 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3868 int mtu = virtio_cread16(vdev,
3869 offsetof(struct virtio_net_config,
3872 __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3875 if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY) &&
3876 !virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3877 dev_warn(&vdev->dev, "device advertises feature VIRTIO_NET_F_STANDBY but not VIRTIO_NET_F_MAC, disabling standby");
3878 __virtio_clear_bit(vdev, VIRTIO_NET_F_STANDBY);
3884 static bool virtnet_check_guest_gso(const struct virtnet_info *vi)
3886 return virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3887 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3888 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3889 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3890 (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) &&
3891 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6));
3894 static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu)
3896 bool guest_gso = virtnet_check_guest_gso(vi);
3898 /* If device can receive ANY guest GSO packets, regardless of mtu,
3899 * allocate packets of maximum size, otherwise limit it to only
3900 * mtu size worth only.
3902 if (mtu > ETH_DATA_LEN || guest_gso) {
3903 vi->big_packets = true;
3904 vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE);
3908 static int virtnet_probe(struct virtio_device *vdev)
3910 int i, err = -ENOMEM;
3911 struct net_device *dev;
3912 struct virtnet_info *vi;
3913 u16 max_queue_pairs;
3916 /* Find if host supports multiqueue/rss virtio_net device */
3917 max_queue_pairs = 1;
3918 if (virtio_has_feature(vdev, VIRTIO_NET_F_MQ) || virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
3920 virtio_cread16(vdev, offsetof(struct virtio_net_config, max_virtqueue_pairs));
3922 /* We need at least 2 queue's */
3923 if (max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
3924 max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
3925 !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3926 max_queue_pairs = 1;
3928 /* Allocate ourselves a network device with room for our info */
3929 dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
3933 /* Set up network device as normal. */
3934 dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
3935 IFF_TX_SKB_NO_LINEAR;
3936 dev->netdev_ops = &virtnet_netdev;
3937 dev->features = NETIF_F_HIGHDMA;
3939 dev->ethtool_ops = &virtnet_ethtool_ops;
3940 SET_NETDEV_DEV(dev, &vdev->dev);
3942 /* Do we support "hardware" checksums? */
3943 if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
3944 /* This opens up the world of extra features. */
3945 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3947 dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
3949 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
3950 dev->hw_features |= NETIF_F_TSO
3951 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
3953 /* Individual feature bits: what can host handle? */
3954 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
3955 dev->hw_features |= NETIF_F_TSO;
3956 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
3957 dev->hw_features |= NETIF_F_TSO6;
3958 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
3959 dev->hw_features |= NETIF_F_TSO_ECN;
3960 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_USO))
3961 dev->hw_features |= NETIF_F_GSO_UDP_L4;
3963 dev->features |= NETIF_F_GSO_ROBUST;
3966 dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
3967 /* (!csum && gso) case will be fixed by register_netdev() */
3969 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
3970 dev->features |= NETIF_F_RXCSUM;
3971 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3972 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3973 dev->features |= NETIF_F_GRO_HW;
3974 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3975 dev->hw_features |= NETIF_F_GRO_HW;
3977 dev->vlan_features = dev->features;
3978 dev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT;
3980 /* MTU range: 68 - 65535 */
3981 dev->min_mtu = MIN_MTU;
3982 dev->max_mtu = MAX_MTU;
3984 /* Configuration may specify what MAC to use. Otherwise random. */
3985 if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3988 virtio_cread_bytes(vdev,
3989 offsetof(struct virtio_net_config, mac),
3991 eth_hw_addr_set(dev, addr);
3993 eth_hw_addr_random(dev);
3994 dev_info(&vdev->dev, "Assigned random MAC address %pM\n",
3998 /* Set up our device-specific information */
3999 vi = netdev_priv(dev);
4004 INIT_WORK(&vi->config_work, virtnet_config_changed_work);
4005 spin_lock_init(&vi->refill_lock);
4007 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) {
4008 vi->mergeable_rx_bufs = true;
4009 dev->xdp_features |= NETDEV_XDP_ACT_RX_SG;
4012 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
4015 vi->tx_max_packets = 0;
4016 vi->rx_max_packets = 0;
4019 if (virtio_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT))
4020 vi->has_rss_hash_report = true;
4022 if (virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
4025 if (vi->has_rss || vi->has_rss_hash_report) {
4026 vi->rss_indir_table_size =
4027 virtio_cread16(vdev, offsetof(struct virtio_net_config,
4028 rss_max_indirection_table_length));
4030 virtio_cread8(vdev, offsetof(struct virtio_net_config, rss_max_key_size));
4032 vi->rss_hash_types_supported =
4033 virtio_cread32(vdev, offsetof(struct virtio_net_config, supported_hash_types));
4034 vi->rss_hash_types_supported &=
4035 ~(VIRTIO_NET_RSS_HASH_TYPE_IP_EX |
4036 VIRTIO_NET_RSS_HASH_TYPE_TCP_EX |
4037 VIRTIO_NET_RSS_HASH_TYPE_UDP_EX);
4039 dev->hw_features |= NETIF_F_RXHASH;
4042 if (vi->has_rss_hash_report)
4043 vi->hdr_len = sizeof(struct virtio_net_hdr_v1_hash);
4044 else if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
4045 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4046 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
4048 vi->hdr_len = sizeof(struct virtio_net_hdr);
4050 if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
4051 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4052 vi->any_header_sg = true;
4054 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
4057 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
4058 mtu = virtio_cread16(vdev,
4059 offsetof(struct virtio_net_config,
4061 if (mtu < dev->min_mtu) {
4062 /* Should never trigger: MTU was previously validated
4063 * in virtnet_validate.
4066 "device MTU appears to have changed it is now %d < %d",
4076 virtnet_set_big_packets(vi, mtu);
4078 if (vi->any_header_sg)
4079 dev->needed_headroom = vi->hdr_len;
4081 /* Enable multiqueue by default */
4082 if (num_online_cpus() >= max_queue_pairs)
4083 vi->curr_queue_pairs = max_queue_pairs;
4085 vi->curr_queue_pairs = num_online_cpus();
4086 vi->max_queue_pairs = max_queue_pairs;
4088 /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
4094 if (vi->mergeable_rx_bufs)
4095 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
4097 netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
4098 netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
4100 virtnet_init_settings(dev);
4102 if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
4103 vi->failover = net_failover_create(vi->dev);
4104 if (IS_ERR(vi->failover)) {
4105 err = PTR_ERR(vi->failover);
4110 if (vi->has_rss || vi->has_rss_hash_report)
4111 virtnet_init_default_rss(vi);
4113 /* serialize netdev register + virtio_device_ready() with ndo_open() */
4116 err = register_netdevice(dev);
4118 pr_debug("virtio_net: registering device failed\n");
4123 virtio_device_ready(vdev);
4125 /* a random MAC address has been assigned, notify the device.
4126 * We don't fail probe if VIRTIO_NET_F_CTRL_MAC_ADDR is not there
4127 * because many devices work fine without getting MAC explicitly
4129 if (!virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
4130 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
4131 struct scatterlist sg;
4133 sg_init_one(&sg, dev->dev_addr, dev->addr_len);
4134 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
4135 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
4136 pr_debug("virtio_net: setting MAC address failed\n");
4139 goto free_unregister_netdev;
4145 err = virtnet_cpu_notif_add(vi);
4147 pr_debug("virtio_net: registering cpu notifier failed\n");
4148 goto free_unregister_netdev;
4151 virtnet_set_queues(vi, vi->curr_queue_pairs);
4153 /* Assume link up if device can't report link status,
4154 otherwise get link status from config. */
4155 netif_carrier_off(dev);
4156 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
4157 schedule_work(&vi->config_work);
4159 vi->status = VIRTIO_NET_S_LINK_UP;
4160 virtnet_update_settings(vi);
4161 netif_carrier_on(dev);
4164 for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
4165 if (virtio_has_feature(vi->vdev, guest_offloads[i]))
4166 set_bit(guest_offloads[i], &vi->guest_offloads);
4167 vi->guest_offloads_capable = vi->guest_offloads;
4169 pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
4170 dev->name, max_queue_pairs);
4174 free_unregister_netdev:
4175 unregister_netdev(dev);
4177 net_failover_destroy(vi->failover);
4179 virtio_reset_device(vdev);
4180 cancel_delayed_work_sync(&vi->refill);
4181 free_receive_page_frags(vi);
4182 virtnet_del_vqs(vi);
4188 static void remove_vq_common(struct virtnet_info *vi)
4190 virtio_reset_device(vi->vdev);
4192 /* Free unused buffers in both send and recv, if any. */
4193 free_unused_bufs(vi);
4195 free_receive_bufs(vi);
4197 free_receive_page_frags(vi);
4199 virtnet_del_vqs(vi);
4202 static void virtnet_remove(struct virtio_device *vdev)
4204 struct virtnet_info *vi = vdev->priv;
4206 virtnet_cpu_notif_remove(vi);
4208 /* Make sure no work handler is accessing the device. */
4209 flush_work(&vi->config_work);
4211 unregister_netdev(vi->dev);
4213 net_failover_destroy(vi->failover);
4215 remove_vq_common(vi);
4217 free_netdev(vi->dev);
4220 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
4222 struct virtnet_info *vi = vdev->priv;
4224 virtnet_cpu_notif_remove(vi);
4225 virtnet_freeze_down(vdev);
4226 remove_vq_common(vi);
4231 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
4233 struct virtnet_info *vi = vdev->priv;
4236 err = virtnet_restore_up(vdev);
4239 virtnet_set_queues(vi, vi->curr_queue_pairs);
4241 err = virtnet_cpu_notif_add(vi);
4243 virtnet_freeze_down(vdev);
4244 remove_vq_common(vi);
4251 static struct virtio_device_id id_table[] = {
4252 { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
4256 #define VIRTNET_FEATURES \
4257 VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
4259 VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
4260 VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
4261 VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
4262 VIRTIO_NET_F_HOST_USO, VIRTIO_NET_F_GUEST_USO4, VIRTIO_NET_F_GUEST_USO6, \
4263 VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
4264 VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
4265 VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
4266 VIRTIO_NET_F_CTRL_MAC_ADDR, \
4267 VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
4268 VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY, \
4269 VIRTIO_NET_F_RSS, VIRTIO_NET_F_HASH_REPORT, VIRTIO_NET_F_NOTF_COAL, \
4270 VIRTIO_NET_F_GUEST_HDRLEN
4272 static unsigned int features[] = {
4276 static unsigned int features_legacy[] = {
4279 VIRTIO_F_ANY_LAYOUT,
4282 static struct virtio_driver virtio_net_driver = {
4283 .feature_table = features,
4284 .feature_table_size = ARRAY_SIZE(features),
4285 .feature_table_legacy = features_legacy,
4286 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
4287 .driver.name = KBUILD_MODNAME,
4288 .driver.owner = THIS_MODULE,
4289 .id_table = id_table,
4290 .validate = virtnet_validate,
4291 .probe = virtnet_probe,
4292 .remove = virtnet_remove,
4293 .config_changed = virtnet_config_changed,
4294 #ifdef CONFIG_PM_SLEEP
4295 .freeze = virtnet_freeze,
4296 .restore = virtnet_restore,
4300 static __init int virtio_net_driver_init(void)
4304 ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
4306 virtnet_cpu_down_prep);
4309 virtionet_online = ret;
4310 ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
4311 NULL, virtnet_cpu_dead);
4314 ret = register_virtio_driver(&virtio_net_driver);
4319 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4321 cpuhp_remove_multi_state(virtionet_online);
4325 module_init(virtio_net_driver_init);
4327 static __exit void virtio_net_driver_exit(void)
4329 unregister_virtio_driver(&virtio_net_driver);
4330 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4331 cpuhp_remove_multi_state(virtionet_online);
4333 module_exit(virtio_net_driver_exit);
4335 MODULE_DEVICE_TABLE(virtio, id_table);
4336 MODULE_DESCRIPTION("Virtio network driver");
4337 MODULE_LICENSE("GPL");