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;
208 struct virtio_net_ctrl_coal_tx coal_tx;
209 struct virtio_net_ctrl_coal_rx coal_rx;
212 struct virtnet_info {
213 struct virtio_device *vdev;
214 struct virtqueue *cvq;
215 struct net_device *dev;
216 struct send_queue *sq;
217 struct receive_queue *rq;
220 /* Max # of queue pairs supported by the device */
223 /* # of queue pairs currently used by the driver */
224 u16 curr_queue_pairs;
226 /* # of XDP queue pairs currently used by the driver */
229 /* xdp_queue_pairs may be 0, when xdp is already loaded. So add this. */
232 /* I like... big packets and I cannot lie! */
235 /* number of sg entries allocated for big packets */
236 unsigned int big_packets_num_skbfrags;
238 /* Host will merge rx buffers for big packets (shake it! shake it!) */
239 bool mergeable_rx_bufs;
241 /* Host supports rss and/or hash report */
243 bool has_rss_hash_report;
245 u16 rss_indir_table_size;
246 u32 rss_hash_types_supported;
247 u32 rss_hash_types_saved;
249 /* Has control virtqueue */
252 /* Host can handle any s/g split between our header and packet data */
255 /* Packet virtio header size */
258 /* Work struct for delayed refilling if we run low on memory. */
259 struct delayed_work refill;
261 /* Is delayed refill enabled? */
264 /* The lock to synchronize the access to refill_enabled */
265 spinlock_t refill_lock;
267 /* Work struct for config space updates */
268 struct work_struct config_work;
270 /* Does the affinity hint is set for virtqueues? */
271 bool affinity_hint_set;
273 /* CPU hotplug instances for online & dead */
274 struct hlist_node node;
275 struct hlist_node node_dead;
277 struct control_buf *ctrl;
279 /* Ethtool settings */
283 /* Interrupt coalescing settings */
289 unsigned long guest_offloads;
290 unsigned long guest_offloads_capable;
292 /* failover when STANDBY feature enabled */
293 struct failover *failover;
296 struct padded_vnet_hdr {
297 struct virtio_net_hdr_v1_hash hdr;
299 * hdr is in a separate sg buffer, and data sg buffer shares same page
300 * with this header sg. This padding makes next sg 16 byte aligned
306 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf);
307 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf);
309 static bool is_xdp_frame(void *ptr)
311 return (unsigned long)ptr & VIRTIO_XDP_FLAG;
314 static void *xdp_to_ptr(struct xdp_frame *ptr)
316 return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
319 static struct xdp_frame *ptr_to_xdp(void *ptr)
321 return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
324 /* Converting between virtqueue no. and kernel tx/rx queue no.
325 * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
327 static int vq2txq(struct virtqueue *vq)
329 return (vq->index - 1) / 2;
332 static int txq2vq(int txq)
337 static int vq2rxq(struct virtqueue *vq)
339 return vq->index / 2;
342 static int rxq2vq(int rxq)
347 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
349 return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
353 * private is used to chain pages for big packets, put the whole
354 * most recent used list in the beginning for reuse
356 static void give_pages(struct receive_queue *rq, struct page *page)
360 /* Find end of list, sew whole thing into vi->rq.pages. */
361 for (end = page; end->private; end = (struct page *)end->private);
362 end->private = (unsigned long)rq->pages;
366 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
368 struct page *p = rq->pages;
371 rq->pages = (struct page *)p->private;
372 /* clear private here, it is used to chain pages */
375 p = alloc_page(gfp_mask);
379 static void enable_delayed_refill(struct virtnet_info *vi)
381 spin_lock_bh(&vi->refill_lock);
382 vi->refill_enabled = true;
383 spin_unlock_bh(&vi->refill_lock);
386 static void disable_delayed_refill(struct virtnet_info *vi)
388 spin_lock_bh(&vi->refill_lock);
389 vi->refill_enabled = false;
390 spin_unlock_bh(&vi->refill_lock);
393 static void virtqueue_napi_schedule(struct napi_struct *napi,
394 struct virtqueue *vq)
396 if (napi_schedule_prep(napi)) {
397 virtqueue_disable_cb(vq);
398 __napi_schedule(napi);
402 static void virtqueue_napi_complete(struct napi_struct *napi,
403 struct virtqueue *vq, int processed)
407 opaque = virtqueue_enable_cb_prepare(vq);
408 if (napi_complete_done(napi, processed)) {
409 if (unlikely(virtqueue_poll(vq, opaque)))
410 virtqueue_napi_schedule(napi, vq);
412 virtqueue_disable_cb(vq);
416 static void skb_xmit_done(struct virtqueue *vq)
418 struct virtnet_info *vi = vq->vdev->priv;
419 struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
421 /* Suppress further interrupts. */
422 virtqueue_disable_cb(vq);
425 virtqueue_napi_schedule(napi, vq);
427 /* We were probably waiting for more output buffers. */
428 netif_wake_subqueue(vi->dev, vq2txq(vq));
431 #define MRG_CTX_HEADER_SHIFT 22
432 static void *mergeable_len_to_ctx(unsigned int truesize,
433 unsigned int headroom)
435 return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
438 static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
440 return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
443 static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
445 return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
448 static struct sk_buff *virtnet_build_skb(void *buf, unsigned int buflen,
449 unsigned int headroom,
454 skb = build_skb(buf, buflen);
458 skb_reserve(skb, headroom);
464 /* Called from bottom half context */
465 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
466 struct receive_queue *rq,
467 struct page *page, unsigned int offset,
468 unsigned int len, unsigned int truesize,
469 unsigned int headroom)
472 struct virtio_net_hdr_mrg_rxbuf *hdr;
473 unsigned int copy, hdr_len, hdr_padded_len;
474 struct page *page_to_free = NULL;
475 int tailroom, shinfo_size;
476 char *p, *hdr_p, *buf;
478 p = page_address(page) + offset;
481 hdr_len = vi->hdr_len;
482 if (vi->mergeable_rx_bufs)
483 hdr_padded_len = hdr_len;
485 hdr_padded_len = sizeof(struct padded_vnet_hdr);
489 offset += hdr_padded_len;
491 tailroom = truesize - headroom - hdr_padded_len - len;
493 shinfo_size = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
495 /* copy small packet so we can reuse these pages */
496 if (!NET_IP_ALIGN && len > GOOD_COPY_LEN && tailroom >= shinfo_size) {
497 skb = virtnet_build_skb(buf, truesize, p - buf, len);
501 page = (struct page *)page->private;
503 give_pages(rq, page);
507 /* copy small packet so we can reuse these pages for small data */
508 skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
512 /* Copy all frame if it fits skb->head, otherwise
513 * we let virtio_net_hdr_to_skb() and GRO pull headers as needed.
515 if (len <= skb_tailroom(skb))
519 skb_put_data(skb, p, copy);
524 if (vi->mergeable_rx_bufs) {
526 skb_add_rx_frag(skb, 0, page, offset, len, truesize);
533 * Verify that we can indeed put this data into a skb.
534 * This is here to handle cases when the device erroneously
535 * tries to receive more than is possible. This is usually
536 * the case of a broken device.
538 if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
539 net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
543 BUG_ON(offset >= PAGE_SIZE);
545 unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
546 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
547 frag_size, truesize);
549 page = (struct page *)page->private;
554 give_pages(rq, page);
557 hdr = skb_vnet_hdr(skb);
558 memcpy(hdr, hdr_p, hdr_len);
560 put_page(page_to_free);
565 static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
568 unsigned int packets = 0;
569 unsigned int bytes = 0;
572 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
573 if (likely(!is_xdp_frame(ptr))) {
574 struct sk_buff *skb = ptr;
576 pr_debug("Sent skb %p\n", skb);
579 napi_consume_skb(skb, in_napi);
581 struct xdp_frame *frame = ptr_to_xdp(ptr);
583 bytes += xdp_get_frame_len(frame);
584 xdp_return_frame(frame);
589 /* Avoid overhead when no packets have been processed
590 * happens when called speculatively from start_xmit.
595 u64_stats_update_begin(&sq->stats.syncp);
596 sq->stats.bytes += bytes;
597 sq->stats.packets += packets;
598 u64_stats_update_end(&sq->stats.syncp);
601 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
603 if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
605 else if (q < vi->curr_queue_pairs)
611 static void check_sq_full_and_disable(struct virtnet_info *vi,
612 struct net_device *dev,
613 struct send_queue *sq)
615 bool use_napi = sq->napi.weight;
620 /* If running out of space, stop queue to avoid getting packets that we
621 * are then unable to transmit.
622 * An alternative would be to force queuing layer to requeue the skb by
623 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
624 * returned in a normal path of operation: it means that driver is not
625 * maintaining the TX queue stop/start state properly, and causes
626 * the stack to do a non-trivial amount of useless work.
627 * Since most packets only take 1 or 2 ring slots, stopping the queue
628 * early means 16 slots are typically wasted.
630 if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
631 netif_stop_subqueue(dev, qnum);
633 if (unlikely(!virtqueue_enable_cb_delayed(sq->vq)))
634 virtqueue_napi_schedule(&sq->napi, sq->vq);
635 } else if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
636 /* More just got used, free them then recheck. */
637 free_old_xmit_skbs(sq, false);
638 if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
639 netif_start_subqueue(dev, qnum);
640 virtqueue_disable_cb(sq->vq);
646 static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
647 struct send_queue *sq,
648 struct xdp_frame *xdpf)
650 struct virtio_net_hdr_mrg_rxbuf *hdr;
651 struct skb_shared_info *shinfo;
655 if (unlikely(xdpf->headroom < vi->hdr_len))
658 if (unlikely(xdp_frame_has_frags(xdpf))) {
659 shinfo = xdp_get_shared_info_from_frame(xdpf);
660 nr_frags = shinfo->nr_frags;
663 /* In wrapping function virtnet_xdp_xmit(), we need to free
664 * up the pending old buffers, where we need to calculate the
665 * position of skb_shared_info in xdp_get_frame_len() and
666 * xdp_return_frame(), which will involve to xdpf->data and
667 * xdpf->headroom. Therefore, we need to update the value of
668 * headroom synchronously here.
670 xdpf->headroom -= vi->hdr_len;
671 xdpf->data -= vi->hdr_len;
672 /* Zero header and leave csum up to XDP layers */
674 memset(hdr, 0, vi->hdr_len);
675 xdpf->len += vi->hdr_len;
677 sg_init_table(sq->sg, nr_frags + 1);
678 sg_set_buf(sq->sg, xdpf->data, xdpf->len);
679 for (i = 0; i < nr_frags; i++) {
680 skb_frag_t *frag = &shinfo->frags[i];
682 sg_set_page(&sq->sg[i + 1], skb_frag_page(frag),
683 skb_frag_size(frag), skb_frag_off(frag));
686 err = virtqueue_add_outbuf(sq->vq, sq->sg, nr_frags + 1,
687 xdp_to_ptr(xdpf), GFP_ATOMIC);
689 return -ENOSPC; /* Caller handle free/refcnt */
694 /* when vi->curr_queue_pairs > nr_cpu_ids, the txq/sq is only used for xdp tx on
695 * the current cpu, so it does not need to be locked.
697 * Here we use marco instead of inline functions because we have to deal with
698 * three issues at the same time: 1. the choice of sq. 2. judge and execute the
699 * lock/unlock of txq 3. make sparse happy. It is difficult for two inline
700 * functions to perfectly solve these three problems at the same time.
702 #define virtnet_xdp_get_sq(vi) ({ \
703 int cpu = smp_processor_id(); \
704 struct netdev_queue *txq; \
705 typeof(vi) v = (vi); \
708 if (v->curr_queue_pairs > nr_cpu_ids) { \
709 qp = v->curr_queue_pairs - v->xdp_queue_pairs; \
711 txq = netdev_get_tx_queue(v->dev, qp); \
712 __netif_tx_acquire(txq); \
714 qp = cpu % v->curr_queue_pairs; \
715 txq = netdev_get_tx_queue(v->dev, qp); \
716 __netif_tx_lock(txq, cpu); \
721 #define virtnet_xdp_put_sq(vi, q) { \
722 struct netdev_queue *txq; \
723 typeof(vi) v = (vi); \
725 txq = netdev_get_tx_queue(v->dev, (q) - v->sq); \
726 if (v->curr_queue_pairs > nr_cpu_ids) \
727 __netif_tx_release(txq); \
729 __netif_tx_unlock(txq); \
732 static int virtnet_xdp_xmit(struct net_device *dev,
733 int n, struct xdp_frame **frames, u32 flags)
735 struct virtnet_info *vi = netdev_priv(dev);
736 struct receive_queue *rq = vi->rq;
737 struct bpf_prog *xdp_prog;
738 struct send_queue *sq;
748 /* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
749 * indicate XDP resources have been successfully allocated.
751 xdp_prog = rcu_access_pointer(rq->xdp_prog);
755 sq = virtnet_xdp_get_sq(vi);
757 if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
762 /* Free up any pending old buffers before queueing new ones. */
763 while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
764 if (likely(is_xdp_frame(ptr))) {
765 struct xdp_frame *frame = ptr_to_xdp(ptr);
767 bytes += xdp_get_frame_len(frame);
768 xdp_return_frame(frame);
770 struct sk_buff *skb = ptr;
773 napi_consume_skb(skb, false);
778 for (i = 0; i < n; i++) {
779 struct xdp_frame *xdpf = frames[i];
781 if (__virtnet_xdp_xmit_one(vi, sq, xdpf))
787 if (!is_xdp_raw_buffer_queue(vi, sq - vi->sq))
788 check_sq_full_and_disable(vi, dev, sq);
790 if (flags & XDP_XMIT_FLUSH) {
791 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
795 u64_stats_update_begin(&sq->stats.syncp);
796 sq->stats.bytes += bytes;
797 sq->stats.packets += packets;
798 sq->stats.xdp_tx += n;
799 sq->stats.xdp_tx_drops += n - nxmit;
800 sq->stats.kicks += kicks;
801 u64_stats_update_end(&sq->stats.syncp);
803 virtnet_xdp_put_sq(vi, sq);
807 static void put_xdp_frags(struct xdp_buff *xdp)
809 struct skb_shared_info *shinfo;
810 struct page *xdp_page;
813 if (xdp_buff_has_frags(xdp)) {
814 shinfo = xdp_get_shared_info_from_buff(xdp);
815 for (i = 0; i < shinfo->nr_frags; i++) {
816 xdp_page = skb_frag_page(&shinfo->frags[i]);
822 static int virtnet_xdp_handler(struct bpf_prog *xdp_prog, struct xdp_buff *xdp,
823 struct net_device *dev,
824 unsigned int *xdp_xmit,
825 struct virtnet_rq_stats *stats)
827 struct xdp_frame *xdpf;
831 act = bpf_prog_run_xdp(xdp_prog, xdp);
832 stats->xdp_packets++;
840 xdpf = xdp_convert_buff_to_frame(xdp);
841 if (unlikely(!xdpf)) {
842 netdev_dbg(dev, "convert buff to frame failed for xdp\n");
846 err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
847 if (unlikely(!err)) {
848 xdp_return_frame_rx_napi(xdpf);
849 } else if (unlikely(err < 0)) {
850 trace_xdp_exception(dev, xdp_prog, act);
853 *xdp_xmit |= VIRTIO_XDP_TX;
857 stats->xdp_redirects++;
858 err = xdp_do_redirect(dev, xdp, xdp_prog);
862 *xdp_xmit |= VIRTIO_XDP_REDIR;
866 bpf_warn_invalid_xdp_action(dev, xdp_prog, act);
869 trace_xdp_exception(dev, xdp_prog, act);
876 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
878 return vi->xdp_enabled ? VIRTIO_XDP_HEADROOM : 0;
881 /* We copy the packet for XDP in the following cases:
883 * 1) Packet is scattered across multiple rx buffers.
884 * 2) Headroom space is insufficient.
886 * This is inefficient but it's a temporary condition that
887 * we hit right after XDP is enabled and until queue is refilled
888 * with large buffers with sufficient headroom - so it should affect
889 * at most queue size packets.
890 * Afterwards, the conditions to enable
891 * XDP should preclude the underlying device from sending packets
892 * across multiple buffers (num_buf > 1), and we make sure buffers
893 * have enough headroom.
895 static struct page *xdp_linearize_page(struct receive_queue *rq,
902 int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
905 if (page_off + *len + tailroom > PAGE_SIZE)
908 page = alloc_page(GFP_ATOMIC);
912 memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
920 buf = virtqueue_get_buf(rq->vq, &buflen);
924 p = virt_to_head_page(buf);
925 off = buf - page_address(p);
927 /* guard against a misconfigured or uncooperative backend that
928 * is sending packet larger than the MTU.
930 if ((page_off + buflen + tailroom) > PAGE_SIZE) {
935 memcpy(page_address(page) + page_off,
936 page_address(p) + off, buflen);
941 /* Headroom does not contribute to packet length */
942 *len = page_off - VIRTIO_XDP_HEADROOM;
945 __free_pages(page, 0);
949 static struct sk_buff *receive_small_build_skb(struct virtnet_info *vi,
950 unsigned int xdp_headroom,
954 unsigned int header_offset;
955 unsigned int headroom;
959 header_offset = VIRTNET_RX_PAD + xdp_headroom;
960 headroom = vi->hdr_len + header_offset;
961 buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
962 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
964 skb = virtnet_build_skb(buf, buflen, headroom, len);
968 buf += header_offset;
969 memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
974 static struct sk_buff *receive_small_xdp(struct net_device *dev,
975 struct virtnet_info *vi,
976 struct receive_queue *rq,
977 struct bpf_prog *xdp_prog,
979 unsigned int xdp_headroom,
981 unsigned int *xdp_xmit,
982 struct virtnet_rq_stats *stats)
984 unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
985 unsigned int headroom = vi->hdr_len + header_offset;
986 struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
987 struct page *page = virt_to_head_page(buf);
988 struct page *xdp_page;
992 unsigned int metasize = 0;
995 if (unlikely(hdr->hdr.gso_type))
998 buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
999 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1001 if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
1002 int offset = buf - page_address(page) + header_offset;
1003 unsigned int tlen = len + vi->hdr_len;
1006 xdp_headroom = virtnet_get_headroom(vi);
1007 header_offset = VIRTNET_RX_PAD + xdp_headroom;
1008 headroom = vi->hdr_len + header_offset;
1009 buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
1010 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1011 xdp_page = xdp_linearize_page(rq, &num_buf, page,
1012 offset, header_offset,
1017 buf = page_address(xdp_page);
1022 xdp_init_buff(&xdp, buflen, &rq->xdp_rxq);
1023 xdp_prepare_buff(&xdp, buf + VIRTNET_RX_PAD + vi->hdr_len,
1024 xdp_headroom, len, true);
1026 act = virtnet_xdp_handler(xdp_prog, &xdp, dev, xdp_xmit, stats);
1030 /* Recalculate length in case bpf program changed it */
1031 len = xdp.data_end - xdp.data;
1032 metasize = xdp.data - xdp.data_meta;
1043 skb = virtnet_build_skb(buf, buflen, xdp.data - buf, len);
1048 skb_metadata_set(skb, metasize);
1061 static struct sk_buff *receive_small(struct net_device *dev,
1062 struct virtnet_info *vi,
1063 struct receive_queue *rq,
1064 void *buf, void *ctx,
1066 unsigned int *xdp_xmit,
1067 struct virtnet_rq_stats *stats)
1069 unsigned int xdp_headroom = (unsigned long)ctx;
1070 struct page *page = virt_to_head_page(buf);
1071 struct sk_buff *skb;
1074 stats->bytes += len;
1076 if (unlikely(len > GOOD_PACKET_LEN)) {
1077 pr_debug("%s: rx error: len %u exceeds max size %d\n",
1078 dev->name, len, GOOD_PACKET_LEN);
1079 dev->stats.rx_length_errors++;
1083 if (unlikely(vi->xdp_enabled)) {
1084 struct bpf_prog *xdp_prog;
1087 xdp_prog = rcu_dereference(rq->xdp_prog);
1089 skb = receive_small_xdp(dev, vi, rq, xdp_prog, buf,
1090 xdp_headroom, len, xdp_xmit,
1098 skb = receive_small_build_skb(vi, xdp_headroom, buf, len);
1108 static struct sk_buff *receive_big(struct net_device *dev,
1109 struct virtnet_info *vi,
1110 struct receive_queue *rq,
1113 struct virtnet_rq_stats *stats)
1115 struct page *page = buf;
1116 struct sk_buff *skb =
1117 page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, 0);
1119 stats->bytes += len - vi->hdr_len;
1127 give_pages(rq, page);
1131 static void mergeable_buf_free(struct receive_queue *rq, int num_buf,
1132 struct net_device *dev,
1133 struct virtnet_rq_stats *stats)
1139 while (num_buf-- > 1) {
1140 buf = virtqueue_get_buf(rq->vq, &len);
1141 if (unlikely(!buf)) {
1142 pr_debug("%s: rx error: %d buffers missing\n",
1143 dev->name, num_buf);
1144 dev->stats.rx_length_errors++;
1147 stats->bytes += len;
1148 page = virt_to_head_page(buf);
1153 /* Why not use xdp_build_skb_from_frame() ?
1154 * XDP core assumes that xdp frags are PAGE_SIZE in length, while in
1155 * virtio-net there are 2 points that do not match its requirements:
1156 * 1. The size of the prefilled buffer is not fixed before xdp is set.
1157 * 2. xdp_build_skb_from_frame() does more checks that we don't need,
1158 * like eth_type_trans() (which virtio-net does in receive_buf()).
1160 static struct sk_buff *build_skb_from_xdp_buff(struct net_device *dev,
1161 struct virtnet_info *vi,
1162 struct xdp_buff *xdp,
1163 unsigned int xdp_frags_truesz)
1165 struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
1166 unsigned int headroom, data_len;
1167 struct sk_buff *skb;
1171 if (unlikely(xdp->data_end > xdp_data_hard_end(xdp))) {
1172 pr_debug("Error building skb as missing reserved tailroom for xdp");
1176 if (unlikely(xdp_buff_has_frags(xdp)))
1177 nr_frags = sinfo->nr_frags;
1179 skb = build_skb(xdp->data_hard_start, xdp->frame_sz);
1183 headroom = xdp->data - xdp->data_hard_start;
1184 data_len = xdp->data_end - xdp->data;
1185 skb_reserve(skb, headroom);
1186 __skb_put(skb, data_len);
1188 metasize = xdp->data - xdp->data_meta;
1189 metasize = metasize > 0 ? metasize : 0;
1191 skb_metadata_set(skb, metasize);
1193 if (unlikely(xdp_buff_has_frags(xdp)))
1194 xdp_update_skb_shared_info(skb, nr_frags,
1195 sinfo->xdp_frags_size,
1197 xdp_buff_is_frag_pfmemalloc(xdp));
1202 /* TODO: build xdp in big mode */
1203 static int virtnet_build_xdp_buff_mrg(struct net_device *dev,
1204 struct virtnet_info *vi,
1205 struct receive_queue *rq,
1206 struct xdp_buff *xdp,
1209 unsigned int frame_sz,
1211 unsigned int *xdp_frags_truesize,
1212 struct virtnet_rq_stats *stats)
1214 struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1215 unsigned int headroom, tailroom, room;
1216 unsigned int truesize, cur_frag_size;
1217 struct skb_shared_info *shinfo;
1218 unsigned int xdp_frags_truesz = 0;
1224 xdp_init_buff(xdp, frame_sz, &rq->xdp_rxq);
1225 xdp_prepare_buff(xdp, buf - VIRTIO_XDP_HEADROOM,
1226 VIRTIO_XDP_HEADROOM + vi->hdr_len, len - vi->hdr_len, true);
1232 /* If we want to build multi-buffer xdp, we need
1233 * to specify that the flags of xdp_buff have the
1234 * XDP_FLAGS_HAS_FRAG bit.
1236 if (!xdp_buff_has_frags(xdp))
1237 xdp_buff_set_frags_flag(xdp);
1239 shinfo = xdp_get_shared_info_from_buff(xdp);
1240 shinfo->nr_frags = 0;
1241 shinfo->xdp_frags_size = 0;
1244 if (*num_buf > MAX_SKB_FRAGS + 1)
1247 while (--*num_buf > 0) {
1248 buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1249 if (unlikely(!buf)) {
1250 pr_debug("%s: rx error: %d buffers out of %d missing\n",
1251 dev->name, *num_buf,
1252 virtio16_to_cpu(vi->vdev, hdr->num_buffers));
1253 dev->stats.rx_length_errors++;
1257 stats->bytes += len;
1258 page = virt_to_head_page(buf);
1259 offset = buf - page_address(page);
1261 truesize = mergeable_ctx_to_truesize(ctx);
1262 headroom = mergeable_ctx_to_headroom(ctx);
1263 tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1264 room = SKB_DATA_ALIGN(headroom + tailroom);
1266 cur_frag_size = truesize;
1267 xdp_frags_truesz += cur_frag_size;
1268 if (unlikely(len > truesize - room || cur_frag_size > PAGE_SIZE)) {
1270 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1271 dev->name, len, (unsigned long)(truesize - room));
1272 dev->stats.rx_length_errors++;
1276 frag = &shinfo->frags[shinfo->nr_frags++];
1277 skb_frag_fill_page_desc(frag, page, offset, len);
1278 if (page_is_pfmemalloc(page))
1279 xdp_buff_set_frag_pfmemalloc(xdp);
1281 shinfo->xdp_frags_size += len;
1284 *xdp_frags_truesize = xdp_frags_truesz;
1292 static void *mergeable_xdp_get_buf(struct virtnet_info *vi,
1293 struct receive_queue *rq,
1294 struct bpf_prog *xdp_prog,
1296 unsigned int *frame_sz,
1301 struct virtio_net_hdr_mrg_rxbuf *hdr)
1303 unsigned int truesize = mergeable_ctx_to_truesize(ctx);
1304 unsigned int headroom = mergeable_ctx_to_headroom(ctx);
1305 struct page *xdp_page;
1306 unsigned int xdp_room;
1308 /* Transient failure which in theory could occur if
1309 * in-flight packets from before XDP was enabled reach
1310 * the receive path after XDP is loaded.
1312 if (unlikely(hdr->hdr.gso_type))
1315 /* Now XDP core assumes frag size is PAGE_SIZE, but buffers
1316 * with headroom may add hole in truesize, which
1317 * make their length exceed PAGE_SIZE. So we disabled the
1318 * hole mechanism for xdp. See add_recvbuf_mergeable().
1320 *frame_sz = truesize;
1322 if (likely(headroom >= virtnet_get_headroom(vi) &&
1323 (*num_buf == 1 || xdp_prog->aux->xdp_has_frags))) {
1324 return page_address(*page) + offset;
1327 /* This happens when headroom is not enough because
1328 * of the buffer was prefilled before XDP is set.
1329 * This should only happen for the first several packets.
1330 * In fact, vq reset can be used here to help us clean up
1331 * the prefilled buffers, but many existing devices do not
1332 * support it, and we don't want to bother users who are
1333 * using xdp normally.
1335 if (!xdp_prog->aux->xdp_has_frags) {
1336 /* linearize data for XDP */
1337 xdp_page = xdp_linearize_page(rq, num_buf,
1339 VIRTIO_XDP_HEADROOM,
1344 xdp_room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
1345 sizeof(struct skb_shared_info));
1346 if (*len + xdp_room > PAGE_SIZE)
1349 xdp_page = alloc_page(GFP_ATOMIC);
1353 memcpy(page_address(xdp_page) + VIRTIO_XDP_HEADROOM,
1354 page_address(*page) + offset, *len);
1357 *frame_sz = PAGE_SIZE;
1363 return page_address(*page) + VIRTIO_XDP_HEADROOM;
1366 static struct sk_buff *receive_mergeable_xdp(struct net_device *dev,
1367 struct virtnet_info *vi,
1368 struct receive_queue *rq,
1369 struct bpf_prog *xdp_prog,
1373 unsigned int *xdp_xmit,
1374 struct virtnet_rq_stats *stats)
1376 struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1377 int num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
1378 struct page *page = virt_to_head_page(buf);
1379 int offset = buf - page_address(page);
1380 unsigned int xdp_frags_truesz = 0;
1381 struct sk_buff *head_skb;
1382 unsigned int frame_sz;
1383 struct xdp_buff xdp;
1388 data = mergeable_xdp_get_buf(vi, rq, xdp_prog, ctx, &frame_sz, &num_buf, &page,
1390 if (unlikely(!data))
1393 err = virtnet_build_xdp_buff_mrg(dev, vi, rq, &xdp, data, len, frame_sz,
1394 &num_buf, &xdp_frags_truesz, stats);
1398 act = virtnet_xdp_handler(xdp_prog, &xdp, dev, xdp_xmit, stats);
1402 head_skb = build_skb_from_xdp_buff(dev, vi, &xdp, xdp_frags_truesz);
1403 if (unlikely(!head_skb))
1415 put_xdp_frags(&xdp);
1419 mergeable_buf_free(rq, num_buf, dev, stats);
1426 static struct sk_buff *receive_mergeable(struct net_device *dev,
1427 struct virtnet_info *vi,
1428 struct receive_queue *rq,
1432 unsigned int *xdp_xmit,
1433 struct virtnet_rq_stats *stats)
1435 struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
1436 int num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
1437 struct page *page = virt_to_head_page(buf);
1438 int offset = buf - page_address(page);
1439 struct sk_buff *head_skb, *curr_skb;
1440 unsigned int truesize = mergeable_ctx_to_truesize(ctx);
1441 unsigned int headroom = mergeable_ctx_to_headroom(ctx);
1442 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1443 unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1446 stats->bytes += len - vi->hdr_len;
1448 if (unlikely(len > truesize - room)) {
1449 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1450 dev->name, len, (unsigned long)(truesize - room));
1451 dev->stats.rx_length_errors++;
1455 if (unlikely(vi->xdp_enabled)) {
1456 struct bpf_prog *xdp_prog;
1459 xdp_prog = rcu_dereference(rq->xdp_prog);
1461 head_skb = receive_mergeable_xdp(dev, vi, rq, xdp_prog, buf, ctx,
1462 len, xdp_xmit, stats);
1469 head_skb = page_to_skb(vi, rq, page, offset, len, truesize, headroom);
1470 curr_skb = head_skb;
1472 if (unlikely(!curr_skb))
1477 buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
1478 if (unlikely(!buf)) {
1479 pr_debug("%s: rx error: %d buffers out of %d missing\n",
1481 virtio16_to_cpu(vi->vdev,
1483 dev->stats.rx_length_errors++;
1487 stats->bytes += len;
1488 page = virt_to_head_page(buf);
1490 truesize = mergeable_ctx_to_truesize(ctx);
1491 headroom = mergeable_ctx_to_headroom(ctx);
1492 tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1493 room = SKB_DATA_ALIGN(headroom + tailroom);
1494 if (unlikely(len > truesize - room)) {
1495 pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
1496 dev->name, len, (unsigned long)(truesize - room));
1497 dev->stats.rx_length_errors++;
1501 num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
1502 if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
1503 struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
1505 if (unlikely(!nskb))
1507 if (curr_skb == head_skb)
1508 skb_shinfo(curr_skb)->frag_list = nskb;
1510 curr_skb->next = nskb;
1512 head_skb->truesize += nskb->truesize;
1515 if (curr_skb != head_skb) {
1516 head_skb->data_len += len;
1517 head_skb->len += len;
1518 head_skb->truesize += truesize;
1520 offset = buf - page_address(page);
1521 if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
1523 skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
1526 skb_add_rx_frag(curr_skb, num_skb_frags, page,
1527 offset, len, truesize);
1531 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
1536 mergeable_buf_free(rq, num_buf, dev, stats);
1540 dev_kfree_skb(head_skb);
1544 static void virtio_skb_set_hash(const struct virtio_net_hdr_v1_hash *hdr_hash,
1545 struct sk_buff *skb)
1547 enum pkt_hash_types rss_hash_type;
1549 if (!hdr_hash || !skb)
1552 switch (__le16_to_cpu(hdr_hash->hash_report)) {
1553 case VIRTIO_NET_HASH_REPORT_TCPv4:
1554 case VIRTIO_NET_HASH_REPORT_UDPv4:
1555 case VIRTIO_NET_HASH_REPORT_TCPv6:
1556 case VIRTIO_NET_HASH_REPORT_UDPv6:
1557 case VIRTIO_NET_HASH_REPORT_TCPv6_EX:
1558 case VIRTIO_NET_HASH_REPORT_UDPv6_EX:
1559 rss_hash_type = PKT_HASH_TYPE_L4;
1561 case VIRTIO_NET_HASH_REPORT_IPv4:
1562 case VIRTIO_NET_HASH_REPORT_IPv6:
1563 case VIRTIO_NET_HASH_REPORT_IPv6_EX:
1564 rss_hash_type = PKT_HASH_TYPE_L3;
1566 case VIRTIO_NET_HASH_REPORT_NONE:
1568 rss_hash_type = PKT_HASH_TYPE_NONE;
1570 skb_set_hash(skb, __le32_to_cpu(hdr_hash->hash_value), rss_hash_type);
1573 static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
1574 void *buf, unsigned int len, void **ctx,
1575 unsigned int *xdp_xmit,
1576 struct virtnet_rq_stats *stats)
1578 struct net_device *dev = vi->dev;
1579 struct sk_buff *skb;
1580 struct virtio_net_hdr_mrg_rxbuf *hdr;
1582 if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
1583 pr_debug("%s: short packet %i\n", dev->name, len);
1584 dev->stats.rx_length_errors++;
1585 virtnet_rq_free_unused_buf(rq->vq, buf);
1589 if (vi->mergeable_rx_bufs)
1590 skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1592 else if (vi->big_packets)
1593 skb = receive_big(dev, vi, rq, buf, len, stats);
1595 skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1600 hdr = skb_vnet_hdr(skb);
1601 if (dev->features & NETIF_F_RXHASH && vi->has_rss_hash_report)
1602 virtio_skb_set_hash((const struct virtio_net_hdr_v1_hash *)hdr, skb);
1604 if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
1605 skb->ip_summed = CHECKSUM_UNNECESSARY;
1607 if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1608 virtio_is_little_endian(vi->vdev))) {
1609 net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1610 dev->name, hdr->hdr.gso_type,
1615 skb_record_rx_queue(skb, vq2rxq(rq->vq));
1616 skb->protocol = eth_type_trans(skb, dev);
1617 pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1618 ntohs(skb->protocol), skb->len, skb->pkt_type);
1620 napi_gro_receive(&rq->napi, skb);
1624 dev->stats.rx_frame_errors++;
1628 /* Unlike mergeable buffers, all buffers are allocated to the
1629 * same size, except for the headroom. For this reason we do
1630 * not need to use mergeable_len_to_ctx here - it is enough
1631 * to store the headroom as the context ignoring the truesize.
1633 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1636 struct page_frag *alloc_frag = &rq->alloc_frag;
1638 unsigned int xdp_headroom = virtnet_get_headroom(vi);
1639 void *ctx = (void *)(unsigned long)xdp_headroom;
1640 int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
1643 len = SKB_DATA_ALIGN(len) +
1644 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1645 if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
1648 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1649 get_page(alloc_frag->page);
1650 alloc_frag->offset += len;
1651 sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1652 vi->hdr_len + GOOD_PACKET_LEN);
1653 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1655 put_page(virt_to_head_page(buf));
1659 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1662 struct page *first, *list = NULL;
1666 sg_init_table(rq->sg, vi->big_packets_num_skbfrags + 2);
1668 /* page in rq->sg[vi->big_packets_num_skbfrags + 1] is list tail */
1669 for (i = vi->big_packets_num_skbfrags + 1; i > 1; --i) {
1670 first = get_a_page(rq, gfp);
1673 give_pages(rq, list);
1676 sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
1678 /* chain new page in list head to match sg */
1679 first->private = (unsigned long)list;
1683 first = get_a_page(rq, gfp);
1685 give_pages(rq, list);
1688 p = page_address(first);
1690 /* rq->sg[0], rq->sg[1] share the same page */
1691 /* a separated rq->sg[0] for header - required in case !any_header_sg */
1692 sg_set_buf(&rq->sg[0], p, vi->hdr_len);
1694 /* rq->sg[1] for data packet, from offset */
1695 offset = sizeof(struct padded_vnet_hdr);
1696 sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
1698 /* chain first in list head */
1699 first->private = (unsigned long)list;
1700 err = virtqueue_add_inbuf(rq->vq, rq->sg, vi->big_packets_num_skbfrags + 2,
1703 give_pages(rq, first);
1708 static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
1709 struct ewma_pkt_len *avg_pkt_len,
1712 struct virtnet_info *vi = rq->vq->vdev->priv;
1713 const size_t hdr_len = vi->hdr_len;
1717 return PAGE_SIZE - room;
1719 len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1720 rq->min_buf_len, PAGE_SIZE - hdr_len);
1722 return ALIGN(len, L1_CACHE_BYTES);
1725 static int add_recvbuf_mergeable(struct virtnet_info *vi,
1726 struct receive_queue *rq, gfp_t gfp)
1728 struct page_frag *alloc_frag = &rq->alloc_frag;
1729 unsigned int headroom = virtnet_get_headroom(vi);
1730 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
1731 unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1735 unsigned int len, hole;
1737 /* Extra tailroom is needed to satisfy XDP's assumption. This
1738 * means rx frags coalescing won't work, but consider we've
1739 * disabled GSO for XDP, it won't be a big issue.
1741 len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
1742 if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
1745 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1746 buf += headroom; /* advance address leaving hole at front of pkt */
1747 get_page(alloc_frag->page);
1748 alloc_frag->offset += len + room;
1749 hole = alloc_frag->size - alloc_frag->offset;
1750 if (hole < len + room) {
1751 /* To avoid internal fragmentation, if there is very likely not
1752 * enough space for another buffer, add the remaining space to
1753 * the current buffer.
1754 * XDP core assumes that frame_size of xdp_buff and the length
1755 * of the frag are PAGE_SIZE, so we disable the hole mechanism.
1759 alloc_frag->offset += hole;
1762 sg_init_one(rq->sg, buf, len);
1763 ctx = mergeable_len_to_ctx(len + room, headroom);
1764 err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
1766 put_page(virt_to_head_page(buf));
1772 * Returns false if we couldn't fill entirely (OOM).
1774 * Normally run in the receive path, but can also be run from ndo_open
1775 * before we're receiving packets, or from refill_work which is
1776 * careful to disable receiving (using napi_disable).
1778 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1785 if (vi->mergeable_rx_bufs)
1786 err = add_recvbuf_mergeable(vi, rq, gfp);
1787 else if (vi->big_packets)
1788 err = add_recvbuf_big(vi, rq, gfp);
1790 err = add_recvbuf_small(vi, rq, gfp);
1792 oom = err == -ENOMEM;
1795 } while (rq->vq->num_free);
1796 if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
1797 unsigned long flags;
1799 flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1801 u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1807 static void skb_recv_done(struct virtqueue *rvq)
1809 struct virtnet_info *vi = rvq->vdev->priv;
1810 struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1812 virtqueue_napi_schedule(&rq->napi, rvq);
1815 static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
1819 /* If all buffers were filled by other side before we napi_enabled, we
1820 * won't get another interrupt, so process any outstanding packets now.
1821 * Call local_bh_enable after to trigger softIRQ processing.
1824 virtqueue_napi_schedule(napi, vq);
1828 static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1829 struct virtqueue *vq,
1830 struct napi_struct *napi)
1835 /* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1836 * enable the feature if this is likely affine with the transmit path.
1838 if (!vi->affinity_hint_set) {
1843 return virtnet_napi_enable(vq, napi);
1846 static void virtnet_napi_tx_disable(struct napi_struct *napi)
1852 static void refill_work(struct work_struct *work)
1854 struct virtnet_info *vi =
1855 container_of(work, struct virtnet_info, refill.work);
1859 for (i = 0; i < vi->curr_queue_pairs; i++) {
1860 struct receive_queue *rq = &vi->rq[i];
1862 napi_disable(&rq->napi);
1863 still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1864 virtnet_napi_enable(rq->vq, &rq->napi);
1866 /* In theory, this can happen: if we don't get any buffers in
1867 * we will *never* try to fill again.
1870 schedule_delayed_work(&vi->refill, HZ/2);
1874 static int virtnet_receive(struct receive_queue *rq, int budget,
1875 unsigned int *xdp_xmit)
1877 struct virtnet_info *vi = rq->vq->vdev->priv;
1878 struct virtnet_rq_stats stats = {};
1883 if (!vi->big_packets || vi->mergeable_rx_bufs) {
1886 while (stats.packets < budget &&
1887 (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1888 receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1892 while (stats.packets < budget &&
1893 (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1894 receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1899 if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1900 if (!try_fill_recv(vi, rq, GFP_ATOMIC)) {
1901 spin_lock(&vi->refill_lock);
1902 if (vi->refill_enabled)
1903 schedule_delayed_work(&vi->refill, 0);
1904 spin_unlock(&vi->refill_lock);
1908 u64_stats_update_begin(&rq->stats.syncp);
1909 for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1910 size_t offset = virtnet_rq_stats_desc[i].offset;
1913 item = (u64 *)((u8 *)&rq->stats + offset);
1914 *item += *(u64 *)((u8 *)&stats + offset);
1916 u64_stats_update_end(&rq->stats.syncp);
1918 return stats.packets;
1921 static void virtnet_poll_cleantx(struct receive_queue *rq)
1923 struct virtnet_info *vi = rq->vq->vdev->priv;
1924 unsigned int index = vq2rxq(rq->vq);
1925 struct send_queue *sq = &vi->sq[index];
1926 struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
1928 if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
1931 if (__netif_tx_trylock(txq)) {
1933 __netif_tx_unlock(txq);
1938 virtqueue_disable_cb(sq->vq);
1939 free_old_xmit_skbs(sq, true);
1940 } while (unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
1942 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1943 netif_tx_wake_queue(txq);
1945 __netif_tx_unlock(txq);
1949 static int virtnet_poll(struct napi_struct *napi, int budget)
1951 struct receive_queue *rq =
1952 container_of(napi, struct receive_queue, napi);
1953 struct virtnet_info *vi = rq->vq->vdev->priv;
1954 struct send_queue *sq;
1955 unsigned int received;
1956 unsigned int xdp_xmit = 0;
1958 virtnet_poll_cleantx(rq);
1960 received = virtnet_receive(rq, budget, &xdp_xmit);
1962 if (xdp_xmit & VIRTIO_XDP_REDIR)
1965 /* Out of packets? */
1966 if (received < budget)
1967 virtqueue_napi_complete(napi, rq->vq, received);
1969 if (xdp_xmit & VIRTIO_XDP_TX) {
1970 sq = virtnet_xdp_get_sq(vi);
1971 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1972 u64_stats_update_begin(&sq->stats.syncp);
1974 u64_stats_update_end(&sq->stats.syncp);
1976 virtnet_xdp_put_sq(vi, sq);
1982 static void virtnet_disable_queue_pair(struct virtnet_info *vi, int qp_index)
1984 virtnet_napi_tx_disable(&vi->sq[qp_index].napi);
1985 napi_disable(&vi->rq[qp_index].napi);
1986 xdp_rxq_info_unreg(&vi->rq[qp_index].xdp_rxq);
1989 static int virtnet_enable_queue_pair(struct virtnet_info *vi, int qp_index)
1991 struct net_device *dev = vi->dev;
1994 err = xdp_rxq_info_reg(&vi->rq[qp_index].xdp_rxq, dev, qp_index,
1995 vi->rq[qp_index].napi.napi_id);
1999 err = xdp_rxq_info_reg_mem_model(&vi->rq[qp_index].xdp_rxq,
2000 MEM_TYPE_PAGE_SHARED, NULL);
2002 goto err_xdp_reg_mem_model;
2004 virtnet_napi_enable(vi->rq[qp_index].vq, &vi->rq[qp_index].napi);
2005 virtnet_napi_tx_enable(vi, vi->sq[qp_index].vq, &vi->sq[qp_index].napi);
2009 err_xdp_reg_mem_model:
2010 xdp_rxq_info_unreg(&vi->rq[qp_index].xdp_rxq);
2014 static int virtnet_open(struct net_device *dev)
2016 struct virtnet_info *vi = netdev_priv(dev);
2019 enable_delayed_refill(vi);
2021 for (i = 0; i < vi->max_queue_pairs; i++) {
2022 if (i < vi->curr_queue_pairs)
2023 /* Make sure we have some buffers: if oom use wq. */
2024 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
2025 schedule_delayed_work(&vi->refill, 0);
2027 err = virtnet_enable_queue_pair(vi, i);
2035 disable_delayed_refill(vi);
2036 cancel_delayed_work_sync(&vi->refill);
2038 for (i--; i >= 0; i--)
2039 virtnet_disable_queue_pair(vi, i);
2043 static int virtnet_poll_tx(struct napi_struct *napi, int budget)
2045 struct send_queue *sq = container_of(napi, struct send_queue, napi);
2046 struct virtnet_info *vi = sq->vq->vdev->priv;
2047 unsigned int index = vq2txq(sq->vq);
2048 struct netdev_queue *txq;
2052 if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
2053 /* We don't need to enable cb for XDP */
2054 napi_complete_done(napi, 0);
2058 txq = netdev_get_tx_queue(vi->dev, index);
2059 __netif_tx_lock(txq, raw_smp_processor_id());
2060 virtqueue_disable_cb(sq->vq);
2061 free_old_xmit_skbs(sq, true);
2063 if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
2064 netif_tx_wake_queue(txq);
2066 opaque = virtqueue_enable_cb_prepare(sq->vq);
2068 done = napi_complete_done(napi, 0);
2071 virtqueue_disable_cb(sq->vq);
2073 __netif_tx_unlock(txq);
2076 if (unlikely(virtqueue_poll(sq->vq, opaque))) {
2077 if (napi_schedule_prep(napi)) {
2078 __netif_tx_lock(txq, raw_smp_processor_id());
2079 virtqueue_disable_cb(sq->vq);
2080 __netif_tx_unlock(txq);
2081 __napi_schedule(napi);
2089 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
2091 struct virtio_net_hdr_mrg_rxbuf *hdr;
2092 const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
2093 struct virtnet_info *vi = sq->vq->vdev->priv;
2095 unsigned hdr_len = vi->hdr_len;
2098 pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
2100 can_push = vi->any_header_sg &&
2101 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
2102 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
2103 /* Even if we can, don't push here yet as this would skew
2104 * csum_start offset below. */
2106 hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
2108 hdr = skb_vnet_hdr(skb);
2110 if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
2111 virtio_is_little_endian(vi->vdev), false,
2115 if (vi->mergeable_rx_bufs)
2116 hdr->num_buffers = 0;
2118 sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
2120 __skb_push(skb, hdr_len);
2121 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
2122 if (unlikely(num_sg < 0))
2124 /* Pull header back to avoid skew in tx bytes calculations. */
2125 __skb_pull(skb, hdr_len);
2127 sg_set_buf(sq->sg, hdr, hdr_len);
2128 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
2129 if (unlikely(num_sg < 0))
2133 return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
2136 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
2138 struct virtnet_info *vi = netdev_priv(dev);
2139 int qnum = skb_get_queue_mapping(skb);
2140 struct send_queue *sq = &vi->sq[qnum];
2142 struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
2143 bool kick = !netdev_xmit_more();
2144 bool use_napi = sq->napi.weight;
2146 /* Free up any pending old buffers before queueing new ones. */
2149 virtqueue_disable_cb(sq->vq);
2151 free_old_xmit_skbs(sq, false);
2153 } while (use_napi && kick &&
2154 unlikely(!virtqueue_enable_cb_delayed(sq->vq)));
2156 /* timestamp packet in software */
2157 skb_tx_timestamp(skb);
2159 /* Try to transmit */
2160 err = xmit_skb(sq, skb);
2162 /* This should not happen! */
2163 if (unlikely(err)) {
2164 dev->stats.tx_fifo_errors++;
2165 if (net_ratelimit())
2167 "Unexpected TXQ (%d) queue failure: %d\n",
2169 dev->stats.tx_dropped++;
2170 dev_kfree_skb_any(skb);
2171 return NETDEV_TX_OK;
2174 /* Don't wait up for transmitted skbs to be freed. */
2180 check_sq_full_and_disable(vi, dev, sq);
2182 if (kick || netif_xmit_stopped(txq)) {
2183 if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
2184 u64_stats_update_begin(&sq->stats.syncp);
2186 u64_stats_update_end(&sq->stats.syncp);
2190 return NETDEV_TX_OK;
2193 static int virtnet_rx_resize(struct virtnet_info *vi,
2194 struct receive_queue *rq, u32 ring_num)
2196 bool running = netif_running(vi->dev);
2199 qindex = rq - vi->rq;
2202 napi_disable(&rq->napi);
2204 err = virtqueue_resize(rq->vq, ring_num, virtnet_rq_free_unused_buf);
2206 netdev_err(vi->dev, "resize rx fail: rx queue index: %d err: %d\n", qindex, err);
2208 if (!try_fill_recv(vi, rq, GFP_KERNEL))
2209 schedule_delayed_work(&vi->refill, 0);
2212 virtnet_napi_enable(rq->vq, &rq->napi);
2216 static int virtnet_tx_resize(struct virtnet_info *vi,
2217 struct send_queue *sq, u32 ring_num)
2219 bool running = netif_running(vi->dev);
2220 struct netdev_queue *txq;
2223 qindex = sq - vi->sq;
2226 virtnet_napi_tx_disable(&sq->napi);
2228 txq = netdev_get_tx_queue(vi->dev, qindex);
2230 /* 1. wait all ximt complete
2231 * 2. fix the race of netif_stop_subqueue() vs netif_start_subqueue()
2233 __netif_tx_lock_bh(txq);
2235 /* Prevent rx poll from accessing sq. */
2238 /* Prevent the upper layer from trying to send packets. */
2239 netif_stop_subqueue(vi->dev, qindex);
2241 __netif_tx_unlock_bh(txq);
2243 err = virtqueue_resize(sq->vq, ring_num, virtnet_sq_free_unused_buf);
2245 netdev_err(vi->dev, "resize tx fail: tx queue index: %d err: %d\n", qindex, err);
2247 __netif_tx_lock_bh(txq);
2249 netif_tx_wake_queue(txq);
2250 __netif_tx_unlock_bh(txq);
2253 virtnet_napi_tx_enable(vi, sq->vq, &sq->napi);
2258 * Send command via the control virtqueue and check status. Commands
2259 * supported by the hypervisor, as indicated by feature bits, should
2260 * never fail unless improperly formatted.
2262 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
2263 struct scatterlist *out)
2265 struct scatterlist *sgs[4], hdr, stat;
2266 unsigned out_num = 0, tmp;
2269 /* Caller should know better */
2270 BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
2272 vi->ctrl->status = ~0;
2273 vi->ctrl->hdr.class = class;
2274 vi->ctrl->hdr.cmd = cmd;
2276 sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
2277 sgs[out_num++] = &hdr;
2280 sgs[out_num++] = out;
2282 /* Add return status. */
2283 sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
2284 sgs[out_num] = &stat;
2286 BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
2287 ret = virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
2289 dev_warn(&vi->vdev->dev,
2290 "Failed to add sgs for command vq: %d\n.", ret);
2294 if (unlikely(!virtqueue_kick(vi->cvq)))
2295 return vi->ctrl->status == VIRTIO_NET_OK;
2297 /* Spin for a response, the kick causes an ioport write, trapping
2298 * into the hypervisor, so the request should be handled immediately.
2300 while (!virtqueue_get_buf(vi->cvq, &tmp) &&
2301 !virtqueue_is_broken(vi->cvq))
2304 return vi->ctrl->status == VIRTIO_NET_OK;
2307 static int virtnet_set_mac_address(struct net_device *dev, void *p)
2309 struct virtnet_info *vi = netdev_priv(dev);
2310 struct virtio_device *vdev = vi->vdev;
2312 struct sockaddr *addr;
2313 struct scatterlist sg;
2315 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2318 addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
2322 ret = eth_prepare_mac_addr_change(dev, addr);
2326 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
2327 sg_init_one(&sg, addr->sa_data, dev->addr_len);
2328 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2329 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
2330 dev_warn(&vdev->dev,
2331 "Failed to set mac address by vq command.\n");
2335 } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
2336 !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
2339 /* Naturally, this has an atomicity problem. */
2340 for (i = 0; i < dev->addr_len; i++)
2341 virtio_cwrite8(vdev,
2342 offsetof(struct virtio_net_config, mac) +
2343 i, addr->sa_data[i]);
2346 eth_commit_mac_addr_change(dev, p);
2354 static void virtnet_stats(struct net_device *dev,
2355 struct rtnl_link_stats64 *tot)
2357 struct virtnet_info *vi = netdev_priv(dev);
2361 for (i = 0; i < vi->max_queue_pairs; i++) {
2362 u64 tpackets, tbytes, terrors, rpackets, rbytes, rdrops;
2363 struct receive_queue *rq = &vi->rq[i];
2364 struct send_queue *sq = &vi->sq[i];
2367 start = u64_stats_fetch_begin(&sq->stats.syncp);
2368 tpackets = sq->stats.packets;
2369 tbytes = sq->stats.bytes;
2370 terrors = sq->stats.tx_timeouts;
2371 } while (u64_stats_fetch_retry(&sq->stats.syncp, start));
2374 start = u64_stats_fetch_begin(&rq->stats.syncp);
2375 rpackets = rq->stats.packets;
2376 rbytes = rq->stats.bytes;
2377 rdrops = rq->stats.drops;
2378 } while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2380 tot->rx_packets += rpackets;
2381 tot->tx_packets += tpackets;
2382 tot->rx_bytes += rbytes;
2383 tot->tx_bytes += tbytes;
2384 tot->rx_dropped += rdrops;
2385 tot->tx_errors += terrors;
2388 tot->tx_dropped = dev->stats.tx_dropped;
2389 tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
2390 tot->rx_length_errors = dev->stats.rx_length_errors;
2391 tot->rx_frame_errors = dev->stats.rx_frame_errors;
2394 static void virtnet_ack_link_announce(struct virtnet_info *vi)
2397 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
2398 VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
2399 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
2403 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2405 struct scatterlist sg;
2406 struct net_device *dev = vi->dev;
2408 if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
2411 vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
2412 sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
2414 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2415 VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
2416 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
2420 vi->curr_queue_pairs = queue_pairs;
2421 /* virtnet_open() will refill when device is going to up. */
2422 if (dev->flags & IFF_UP)
2423 schedule_delayed_work(&vi->refill, 0);
2429 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
2434 err = _virtnet_set_queues(vi, queue_pairs);
2439 static int virtnet_close(struct net_device *dev)
2441 struct virtnet_info *vi = netdev_priv(dev);
2444 /* Make sure NAPI doesn't schedule refill work */
2445 disable_delayed_refill(vi);
2446 /* Make sure refill_work doesn't re-enable napi! */
2447 cancel_delayed_work_sync(&vi->refill);
2449 for (i = 0; i < vi->max_queue_pairs; i++)
2450 virtnet_disable_queue_pair(vi, i);
2455 static void virtnet_set_rx_mode(struct net_device *dev)
2457 struct virtnet_info *vi = netdev_priv(dev);
2458 struct scatterlist sg[2];
2459 struct virtio_net_ctrl_mac *mac_data;
2460 struct netdev_hw_addr *ha;
2466 /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
2467 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
2470 vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
2471 vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
2473 sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
2475 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2476 VIRTIO_NET_CTRL_RX_PROMISC, sg))
2477 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
2478 vi->ctrl->promisc ? "en" : "dis");
2480 sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
2482 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
2483 VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
2484 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
2485 vi->ctrl->allmulti ? "en" : "dis");
2487 uc_count = netdev_uc_count(dev);
2488 mc_count = netdev_mc_count(dev);
2489 /* MAC filter - use one buffer for both lists */
2490 buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
2491 (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
2496 sg_init_table(sg, 2);
2498 /* Store the unicast list and count in the front of the buffer */
2499 mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
2501 netdev_for_each_uc_addr(ha, dev)
2502 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2504 sg_set_buf(&sg[0], mac_data,
2505 sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
2507 /* multicast list and count fill the end */
2508 mac_data = (void *)&mac_data->macs[uc_count][0];
2510 mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
2512 netdev_for_each_mc_addr(ha, dev)
2513 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
2515 sg_set_buf(&sg[1], mac_data,
2516 sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
2518 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
2519 VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
2520 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
2525 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
2526 __be16 proto, u16 vid)
2528 struct virtnet_info *vi = netdev_priv(dev);
2529 struct scatterlist sg;
2531 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2532 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2534 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2535 VIRTIO_NET_CTRL_VLAN_ADD, &sg))
2536 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
2540 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
2541 __be16 proto, u16 vid)
2543 struct virtnet_info *vi = netdev_priv(dev);
2544 struct scatterlist sg;
2546 vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
2547 sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
2549 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
2550 VIRTIO_NET_CTRL_VLAN_DEL, &sg))
2551 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
2555 static void virtnet_clean_affinity(struct virtnet_info *vi)
2559 if (vi->affinity_hint_set) {
2560 for (i = 0; i < vi->max_queue_pairs; i++) {
2561 virtqueue_set_affinity(vi->rq[i].vq, NULL);
2562 virtqueue_set_affinity(vi->sq[i].vq, NULL);
2565 vi->affinity_hint_set = false;
2569 static void virtnet_set_affinity(struct virtnet_info *vi)
2578 if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
2579 virtnet_clean_affinity(vi);
2583 num_cpu = num_online_cpus();
2584 stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
2585 stragglers = num_cpu >= vi->curr_queue_pairs ?
2586 num_cpu % vi->curr_queue_pairs :
2588 cpu = cpumask_first(cpu_online_mask);
2590 for (i = 0; i < vi->curr_queue_pairs; i++) {
2591 group_size = stride + (i < stragglers ? 1 : 0);
2593 for (j = 0; j < group_size; j++) {
2594 cpumask_set_cpu(cpu, mask);
2595 cpu = cpumask_next_wrap(cpu, cpu_online_mask,
2598 virtqueue_set_affinity(vi->rq[i].vq, mask);
2599 virtqueue_set_affinity(vi->sq[i].vq, mask);
2600 __netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, XPS_CPUS);
2601 cpumask_clear(mask);
2604 vi->affinity_hint_set = true;
2605 free_cpumask_var(mask);
2608 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
2610 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2612 virtnet_set_affinity(vi);
2616 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
2618 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2620 virtnet_set_affinity(vi);
2624 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
2626 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
2629 virtnet_clean_affinity(vi);
2633 static enum cpuhp_state virtionet_online;
2635 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
2639 ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
2642 ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2646 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2650 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
2652 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
2653 cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
2657 static void virtnet_get_ringparam(struct net_device *dev,
2658 struct ethtool_ringparam *ring,
2659 struct kernel_ethtool_ringparam *kernel_ring,
2660 struct netlink_ext_ack *extack)
2662 struct virtnet_info *vi = netdev_priv(dev);
2664 ring->rx_max_pending = vi->rq[0].vq->num_max;
2665 ring->tx_max_pending = vi->sq[0].vq->num_max;
2666 ring->rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2667 ring->tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2670 static int virtnet_set_ringparam(struct net_device *dev,
2671 struct ethtool_ringparam *ring,
2672 struct kernel_ethtool_ringparam *kernel_ring,
2673 struct netlink_ext_ack *extack)
2675 struct virtnet_info *vi = netdev_priv(dev);
2676 u32 rx_pending, tx_pending;
2677 struct receive_queue *rq;
2678 struct send_queue *sq;
2681 if (ring->rx_mini_pending || ring->rx_jumbo_pending)
2684 rx_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2685 tx_pending = virtqueue_get_vring_size(vi->sq[0].vq);
2687 if (ring->rx_pending == rx_pending &&
2688 ring->tx_pending == tx_pending)
2691 if (ring->rx_pending > vi->rq[0].vq->num_max)
2694 if (ring->tx_pending > vi->sq[0].vq->num_max)
2697 for (i = 0; i < vi->max_queue_pairs; i++) {
2701 if (ring->tx_pending != tx_pending) {
2702 err = virtnet_tx_resize(vi, sq, ring->tx_pending);
2707 if (ring->rx_pending != rx_pending) {
2708 err = virtnet_rx_resize(vi, rq, ring->rx_pending);
2717 static bool virtnet_commit_rss_command(struct virtnet_info *vi)
2719 struct net_device *dev = vi->dev;
2720 struct scatterlist sgs[4];
2721 unsigned int sg_buf_size;
2724 sg_init_table(sgs, 4);
2726 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, indirection_table);
2727 sg_set_buf(&sgs[0], &vi->ctrl->rss, sg_buf_size);
2729 sg_buf_size = sizeof(uint16_t) * (vi->ctrl->rss.indirection_table_mask + 1);
2730 sg_set_buf(&sgs[1], vi->ctrl->rss.indirection_table, sg_buf_size);
2732 sg_buf_size = offsetof(struct virtio_net_ctrl_rss, key)
2733 - offsetof(struct virtio_net_ctrl_rss, max_tx_vq);
2734 sg_set_buf(&sgs[2], &vi->ctrl->rss.max_tx_vq, sg_buf_size);
2736 sg_buf_size = vi->rss_key_size;
2737 sg_set_buf(&sgs[3], vi->ctrl->rss.key, sg_buf_size);
2739 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
2740 vi->has_rss ? VIRTIO_NET_CTRL_MQ_RSS_CONFIG
2741 : VIRTIO_NET_CTRL_MQ_HASH_CONFIG, sgs)) {
2742 dev_warn(&dev->dev, "VIRTIONET issue with committing RSS sgs\n");
2748 static void virtnet_init_default_rss(struct virtnet_info *vi)
2753 vi->ctrl->rss.hash_types = vi->rss_hash_types_supported;
2754 vi->rss_hash_types_saved = vi->rss_hash_types_supported;
2755 vi->ctrl->rss.indirection_table_mask = vi->rss_indir_table_size
2756 ? vi->rss_indir_table_size - 1 : 0;
2757 vi->ctrl->rss.unclassified_queue = 0;
2759 for (; i < vi->rss_indir_table_size; ++i) {
2760 indir_val = ethtool_rxfh_indir_default(i, vi->curr_queue_pairs);
2761 vi->ctrl->rss.indirection_table[i] = indir_val;
2764 vi->ctrl->rss.max_tx_vq = vi->has_rss ? vi->curr_queue_pairs : 0;
2765 vi->ctrl->rss.hash_key_length = vi->rss_key_size;
2767 netdev_rss_key_fill(vi->ctrl->rss.key, vi->rss_key_size);
2770 static void virtnet_get_hashflow(const struct virtnet_info *vi, struct ethtool_rxnfc *info)
2773 switch (info->flow_type) {
2775 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
2776 info->data = RXH_IP_SRC | RXH_IP_DST |
2777 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2778 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2779 info->data = RXH_IP_SRC | RXH_IP_DST;
2783 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
2784 info->data = RXH_IP_SRC | RXH_IP_DST |
2785 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2786 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2787 info->data = RXH_IP_SRC | RXH_IP_DST;
2791 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
2792 info->data = RXH_IP_SRC | RXH_IP_DST |
2793 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2794 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
2795 info->data = RXH_IP_SRC | RXH_IP_DST;
2799 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
2800 info->data = RXH_IP_SRC | RXH_IP_DST |
2801 RXH_L4_B_0_1 | RXH_L4_B_2_3;
2802 } else if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
2803 info->data = RXH_IP_SRC | RXH_IP_DST;
2807 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv4)
2808 info->data = RXH_IP_SRC | RXH_IP_DST;
2812 if (vi->rss_hash_types_saved & VIRTIO_NET_RSS_HASH_TYPE_IPv6)
2813 info->data = RXH_IP_SRC | RXH_IP_DST;
2822 static bool virtnet_set_hashflow(struct virtnet_info *vi, struct ethtool_rxnfc *info)
2824 u32 new_hashtypes = vi->rss_hash_types_saved;
2825 bool is_disable = info->data & RXH_DISCARD;
2826 bool is_l4 = info->data == (RXH_IP_SRC | RXH_IP_DST | RXH_L4_B_0_1 | RXH_L4_B_2_3);
2828 /* supports only 'sd', 'sdfn' and 'r' */
2829 if (!((info->data == (RXH_IP_SRC | RXH_IP_DST)) | is_l4 | is_disable))
2832 switch (info->flow_type) {
2834 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_TCPv4);
2836 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2837 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv4 : 0);
2840 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv4 | VIRTIO_NET_RSS_HASH_TYPE_UDPv4);
2842 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv4
2843 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv4 : 0);
2846 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2848 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv4;
2851 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_TCPv6);
2853 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2854 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_TCPv6 : 0);
2857 new_hashtypes &= ~(VIRTIO_NET_RSS_HASH_TYPE_IPv6 | VIRTIO_NET_RSS_HASH_TYPE_UDPv6);
2859 new_hashtypes |= VIRTIO_NET_RSS_HASH_TYPE_IPv6
2860 | (is_l4 ? VIRTIO_NET_RSS_HASH_TYPE_UDPv6 : 0);
2863 new_hashtypes &= ~VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2865 new_hashtypes = VIRTIO_NET_RSS_HASH_TYPE_IPv6;
2868 /* unsupported flow */
2872 /* if unsupported hashtype was set */
2873 if (new_hashtypes != (new_hashtypes & vi->rss_hash_types_supported))
2876 if (new_hashtypes != vi->rss_hash_types_saved) {
2877 vi->rss_hash_types_saved = new_hashtypes;
2878 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
2879 if (vi->dev->features & NETIF_F_RXHASH)
2880 return virtnet_commit_rss_command(vi);
2886 static void virtnet_get_drvinfo(struct net_device *dev,
2887 struct ethtool_drvinfo *info)
2889 struct virtnet_info *vi = netdev_priv(dev);
2890 struct virtio_device *vdev = vi->vdev;
2892 strscpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
2893 strscpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
2894 strscpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
2898 /* TODO: Eliminate OOO packets during switching */
2899 static int virtnet_set_channels(struct net_device *dev,
2900 struct ethtool_channels *channels)
2902 struct virtnet_info *vi = netdev_priv(dev);
2903 u16 queue_pairs = channels->combined_count;
2906 /* We don't support separate rx/tx channels.
2907 * We don't allow setting 'other' channels.
2909 if (channels->rx_count || channels->tx_count || channels->other_count)
2912 if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2915 /* For now we don't support modifying channels while XDP is loaded
2916 * also when XDP is loaded all RX queues have XDP programs so we only
2917 * need to check a single RX queue.
2919 if (vi->rq[0].xdp_prog)
2923 err = _virtnet_set_queues(vi, queue_pairs);
2928 virtnet_set_affinity(vi);
2931 netif_set_real_num_tx_queues(dev, queue_pairs);
2932 netif_set_real_num_rx_queues(dev, queue_pairs);
2937 static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2939 struct virtnet_info *vi = netdev_priv(dev);
2943 switch (stringset) {
2945 for (i = 0; i < vi->curr_queue_pairs; i++) {
2946 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++)
2947 ethtool_sprintf(&p, "rx_queue_%u_%s", i,
2948 virtnet_rq_stats_desc[j].desc);
2951 for (i = 0; i < vi->curr_queue_pairs; i++) {
2952 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++)
2953 ethtool_sprintf(&p, "tx_queue_%u_%s", i,
2954 virtnet_sq_stats_desc[j].desc);
2960 static int virtnet_get_sset_count(struct net_device *dev, int sset)
2962 struct virtnet_info *vi = netdev_priv(dev);
2966 return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2967 VIRTNET_SQ_STATS_LEN);
2973 static void virtnet_get_ethtool_stats(struct net_device *dev,
2974 struct ethtool_stats *stats, u64 *data)
2976 struct virtnet_info *vi = netdev_priv(dev);
2977 unsigned int idx = 0, start, i, j;
2978 const u8 *stats_base;
2981 for (i = 0; i < vi->curr_queue_pairs; i++) {
2982 struct receive_queue *rq = &vi->rq[i];
2984 stats_base = (u8 *)&rq->stats;
2986 start = u64_stats_fetch_begin(&rq->stats.syncp);
2987 for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2988 offset = virtnet_rq_stats_desc[j].offset;
2989 data[idx + j] = *(u64 *)(stats_base + offset);
2991 } while (u64_stats_fetch_retry(&rq->stats.syncp, start));
2992 idx += VIRTNET_RQ_STATS_LEN;
2995 for (i = 0; i < vi->curr_queue_pairs; i++) {
2996 struct send_queue *sq = &vi->sq[i];
2998 stats_base = (u8 *)&sq->stats;
3000 start = u64_stats_fetch_begin(&sq->stats.syncp);
3001 for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
3002 offset = virtnet_sq_stats_desc[j].offset;
3003 data[idx + j] = *(u64 *)(stats_base + offset);
3005 } while (u64_stats_fetch_retry(&sq->stats.syncp, start));
3006 idx += VIRTNET_SQ_STATS_LEN;
3010 static void virtnet_get_channels(struct net_device *dev,
3011 struct ethtool_channels *channels)
3013 struct virtnet_info *vi = netdev_priv(dev);
3015 channels->combined_count = vi->curr_queue_pairs;
3016 channels->max_combined = vi->max_queue_pairs;
3017 channels->max_other = 0;
3018 channels->rx_count = 0;
3019 channels->tx_count = 0;
3020 channels->other_count = 0;
3023 static int virtnet_set_link_ksettings(struct net_device *dev,
3024 const struct ethtool_link_ksettings *cmd)
3026 struct virtnet_info *vi = netdev_priv(dev);
3028 return ethtool_virtdev_set_link_ksettings(dev, cmd,
3029 &vi->speed, &vi->duplex);
3032 static int virtnet_get_link_ksettings(struct net_device *dev,
3033 struct ethtool_link_ksettings *cmd)
3035 struct virtnet_info *vi = netdev_priv(dev);
3037 cmd->base.speed = vi->speed;
3038 cmd->base.duplex = vi->duplex;
3039 cmd->base.port = PORT_OTHER;
3044 static int virtnet_send_notf_coal_cmds(struct virtnet_info *vi,
3045 struct ethtool_coalesce *ec)
3047 struct scatterlist sgs_tx, sgs_rx;
3049 vi->ctrl->coal_tx.tx_usecs = cpu_to_le32(ec->tx_coalesce_usecs);
3050 vi->ctrl->coal_tx.tx_max_packets = cpu_to_le32(ec->tx_max_coalesced_frames);
3051 sg_init_one(&sgs_tx, &vi->ctrl->coal_tx, sizeof(vi->ctrl->coal_tx));
3053 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
3054 VIRTIO_NET_CTRL_NOTF_COAL_TX_SET,
3058 /* Save parameters */
3059 vi->tx_usecs = ec->tx_coalesce_usecs;
3060 vi->tx_max_packets = ec->tx_max_coalesced_frames;
3062 vi->ctrl->coal_rx.rx_usecs = cpu_to_le32(ec->rx_coalesce_usecs);
3063 vi->ctrl->coal_rx.rx_max_packets = cpu_to_le32(ec->rx_max_coalesced_frames);
3064 sg_init_one(&sgs_rx, &vi->ctrl->coal_rx, sizeof(vi->ctrl->coal_rx));
3066 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_NOTF_COAL,
3067 VIRTIO_NET_CTRL_NOTF_COAL_RX_SET,
3071 /* Save parameters */
3072 vi->rx_usecs = ec->rx_coalesce_usecs;
3073 vi->rx_max_packets = ec->rx_max_coalesced_frames;
3078 static int virtnet_coal_params_supported(struct ethtool_coalesce *ec)
3080 /* usecs coalescing is supported only if VIRTIO_NET_F_NOTF_COAL
3081 * feature is negotiated.
3083 if (ec->rx_coalesce_usecs || ec->tx_coalesce_usecs)
3086 if (ec->tx_max_coalesced_frames > 1 ||
3087 ec->rx_max_coalesced_frames != 1)
3093 static int virtnet_set_coalesce(struct net_device *dev,
3094 struct ethtool_coalesce *ec,
3095 struct kernel_ethtool_coalesce *kernel_coal,
3096 struct netlink_ext_ack *extack)
3098 struct virtnet_info *vi = netdev_priv(dev);
3099 int ret, i, napi_weight;
3100 bool update_napi = false;
3102 /* Can't change NAPI weight if the link is up */
3103 napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
3104 if (napi_weight ^ vi->sq[0].napi.weight) {
3105 if (dev->flags & IFF_UP)
3111 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL))
3112 ret = virtnet_send_notf_coal_cmds(vi, ec);
3114 ret = virtnet_coal_params_supported(ec);
3120 for (i = 0; i < vi->max_queue_pairs; i++)
3121 vi->sq[i].napi.weight = napi_weight;
3127 static int virtnet_get_coalesce(struct net_device *dev,
3128 struct ethtool_coalesce *ec,
3129 struct kernel_ethtool_coalesce *kernel_coal,
3130 struct netlink_ext_ack *extack)
3132 struct virtnet_info *vi = netdev_priv(dev);
3134 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
3135 ec->rx_coalesce_usecs = vi->rx_usecs;
3136 ec->tx_coalesce_usecs = vi->tx_usecs;
3137 ec->tx_max_coalesced_frames = vi->tx_max_packets;
3138 ec->rx_max_coalesced_frames = vi->rx_max_packets;
3140 ec->rx_max_coalesced_frames = 1;
3142 if (vi->sq[0].napi.weight)
3143 ec->tx_max_coalesced_frames = 1;
3149 static void virtnet_init_settings(struct net_device *dev)
3151 struct virtnet_info *vi = netdev_priv(dev);
3153 vi->speed = SPEED_UNKNOWN;
3154 vi->duplex = DUPLEX_UNKNOWN;
3157 static void virtnet_update_settings(struct virtnet_info *vi)
3162 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
3165 virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
3167 if (ethtool_validate_speed(speed))
3170 virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
3172 if (ethtool_validate_duplex(duplex))
3173 vi->duplex = duplex;
3176 static u32 virtnet_get_rxfh_key_size(struct net_device *dev)
3178 return ((struct virtnet_info *)netdev_priv(dev))->rss_key_size;
3181 static u32 virtnet_get_rxfh_indir_size(struct net_device *dev)
3183 return ((struct virtnet_info *)netdev_priv(dev))->rss_indir_table_size;
3186 static int virtnet_get_rxfh(struct net_device *dev, u32 *indir, u8 *key, u8 *hfunc)
3188 struct virtnet_info *vi = netdev_priv(dev);
3192 for (i = 0; i < vi->rss_indir_table_size; ++i)
3193 indir[i] = vi->ctrl->rss.indirection_table[i];
3197 memcpy(key, vi->ctrl->rss.key, vi->rss_key_size);
3200 *hfunc = ETH_RSS_HASH_TOP;
3205 static int virtnet_set_rxfh(struct net_device *dev, const u32 *indir, const u8 *key, const u8 hfunc)
3207 struct virtnet_info *vi = netdev_priv(dev);
3210 if (hfunc != ETH_RSS_HASH_NO_CHANGE && hfunc != ETH_RSS_HASH_TOP)
3214 for (i = 0; i < vi->rss_indir_table_size; ++i)
3215 vi->ctrl->rss.indirection_table[i] = indir[i];
3218 memcpy(vi->ctrl->rss.key, key, vi->rss_key_size);
3220 virtnet_commit_rss_command(vi);
3225 static int virtnet_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info, u32 *rule_locs)
3227 struct virtnet_info *vi = netdev_priv(dev);
3230 switch (info->cmd) {
3231 case ETHTOOL_GRXRINGS:
3232 info->data = vi->curr_queue_pairs;
3235 virtnet_get_hashflow(vi, info);
3244 static int virtnet_set_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info)
3246 struct virtnet_info *vi = netdev_priv(dev);
3249 switch (info->cmd) {
3251 if (!virtnet_set_hashflow(vi, info))
3262 static const struct ethtool_ops virtnet_ethtool_ops = {
3263 .supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES |
3264 ETHTOOL_COALESCE_USECS,
3265 .get_drvinfo = virtnet_get_drvinfo,
3266 .get_link = ethtool_op_get_link,
3267 .get_ringparam = virtnet_get_ringparam,
3268 .set_ringparam = virtnet_set_ringparam,
3269 .get_strings = virtnet_get_strings,
3270 .get_sset_count = virtnet_get_sset_count,
3271 .get_ethtool_stats = virtnet_get_ethtool_stats,
3272 .set_channels = virtnet_set_channels,
3273 .get_channels = virtnet_get_channels,
3274 .get_ts_info = ethtool_op_get_ts_info,
3275 .get_link_ksettings = virtnet_get_link_ksettings,
3276 .set_link_ksettings = virtnet_set_link_ksettings,
3277 .set_coalesce = virtnet_set_coalesce,
3278 .get_coalesce = virtnet_get_coalesce,
3279 .get_rxfh_key_size = virtnet_get_rxfh_key_size,
3280 .get_rxfh_indir_size = virtnet_get_rxfh_indir_size,
3281 .get_rxfh = virtnet_get_rxfh,
3282 .set_rxfh = virtnet_set_rxfh,
3283 .get_rxnfc = virtnet_get_rxnfc,
3284 .set_rxnfc = virtnet_set_rxnfc,
3287 static void virtnet_freeze_down(struct virtio_device *vdev)
3289 struct virtnet_info *vi = vdev->priv;
3291 /* Make sure no work handler is accessing the device */
3292 flush_work(&vi->config_work);
3294 netif_tx_lock_bh(vi->dev);
3295 netif_device_detach(vi->dev);
3296 netif_tx_unlock_bh(vi->dev);
3297 if (netif_running(vi->dev))
3298 virtnet_close(vi->dev);
3301 static int init_vqs(struct virtnet_info *vi);
3303 static int virtnet_restore_up(struct virtio_device *vdev)
3305 struct virtnet_info *vi = vdev->priv;
3312 virtio_device_ready(vdev);
3314 enable_delayed_refill(vi);
3316 if (netif_running(vi->dev)) {
3317 err = virtnet_open(vi->dev);
3322 netif_tx_lock_bh(vi->dev);
3323 netif_device_attach(vi->dev);
3324 netif_tx_unlock_bh(vi->dev);
3328 static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
3330 struct scatterlist sg;
3331 vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
3333 sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
3335 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
3336 VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
3337 dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
3344 static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
3348 if (!vi->guest_offloads)
3351 return virtnet_set_guest_offloads(vi, offloads);
3354 static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
3356 u64 offloads = vi->guest_offloads;
3358 if (!vi->guest_offloads)
3361 return virtnet_set_guest_offloads(vi, offloads);
3364 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
3365 struct netlink_ext_ack *extack)
3367 unsigned int room = SKB_DATA_ALIGN(VIRTIO_XDP_HEADROOM +
3368 sizeof(struct skb_shared_info));
3369 unsigned int max_sz = PAGE_SIZE - room - ETH_HLEN;
3370 struct virtnet_info *vi = netdev_priv(dev);
3371 struct bpf_prog *old_prog;
3372 u16 xdp_qp = 0, curr_qp;
3375 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
3376 && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3377 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3378 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3379 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3380 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM) ||
3381 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) ||
3382 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6))) {
3383 NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing GRO_HW/CSUM, disable GRO_HW/CSUM first");
3387 if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
3388 NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
3392 if (prog && !prog->aux->xdp_has_frags && dev->mtu > max_sz) {
3393 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP without frags");
3394 netdev_warn(dev, "single-buffer XDP requires MTU less than %u\n", max_sz);
3398 curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
3400 xdp_qp = nr_cpu_ids;
3402 /* XDP requires extra queues for XDP_TX */
3403 if (curr_qp + xdp_qp > vi->max_queue_pairs) {
3404 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",
3405 curr_qp + xdp_qp, vi->max_queue_pairs);
3409 old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
3410 if (!prog && !old_prog)
3414 bpf_prog_add(prog, vi->max_queue_pairs - 1);
3416 /* Make sure NAPI is not using any XDP TX queues for RX. */
3417 if (netif_running(dev)) {
3418 for (i = 0; i < vi->max_queue_pairs; i++) {
3419 napi_disable(&vi->rq[i].napi);
3420 virtnet_napi_tx_disable(&vi->sq[i].napi);
3425 for (i = 0; i < vi->max_queue_pairs; i++) {
3426 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3428 virtnet_restore_guest_offloads(vi);
3433 err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
3436 netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
3437 vi->xdp_queue_pairs = xdp_qp;
3440 vi->xdp_enabled = true;
3441 for (i = 0; i < vi->max_queue_pairs; i++) {
3442 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
3443 if (i == 0 && !old_prog)
3444 virtnet_clear_guest_offloads(vi);
3447 xdp_features_set_redirect_target(dev, true);
3449 xdp_features_clear_redirect_target(dev);
3450 vi->xdp_enabled = false;
3453 for (i = 0; i < vi->max_queue_pairs; i++) {
3455 bpf_prog_put(old_prog);
3456 if (netif_running(dev)) {
3457 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3458 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3467 virtnet_clear_guest_offloads(vi);
3468 for (i = 0; i < vi->max_queue_pairs; i++)
3469 rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
3472 if (netif_running(dev)) {
3473 for (i = 0; i < vi->max_queue_pairs; i++) {
3474 virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
3475 virtnet_napi_tx_enable(vi, vi->sq[i].vq,
3480 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
3484 static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
3486 switch (xdp->command) {
3487 case XDP_SETUP_PROG:
3488 return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
3494 static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
3497 struct virtnet_info *vi = netdev_priv(dev);
3500 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
3503 ret = snprintf(buf, len, "sby");
3510 static int virtnet_set_features(struct net_device *dev,
3511 netdev_features_t features)
3513 struct virtnet_info *vi = netdev_priv(dev);
3517 if ((dev->features ^ features) & NETIF_F_GRO_HW) {
3518 if (vi->xdp_enabled)
3521 if (features & NETIF_F_GRO_HW)
3522 offloads = vi->guest_offloads_capable;
3524 offloads = vi->guest_offloads_capable &
3525 ~GUEST_OFFLOAD_GRO_HW_MASK;
3527 err = virtnet_set_guest_offloads(vi, offloads);
3530 vi->guest_offloads = offloads;
3533 if ((dev->features ^ features) & NETIF_F_RXHASH) {
3534 if (features & NETIF_F_RXHASH)
3535 vi->ctrl->rss.hash_types = vi->rss_hash_types_saved;
3537 vi->ctrl->rss.hash_types = VIRTIO_NET_HASH_REPORT_NONE;
3539 if (!virtnet_commit_rss_command(vi))
3546 static void virtnet_tx_timeout(struct net_device *dev, unsigned int txqueue)
3548 struct virtnet_info *priv = netdev_priv(dev);
3549 struct send_queue *sq = &priv->sq[txqueue];
3550 struct netdev_queue *txq = netdev_get_tx_queue(dev, txqueue);
3552 u64_stats_update_begin(&sq->stats.syncp);
3553 sq->stats.tx_timeouts++;
3554 u64_stats_update_end(&sq->stats.syncp);
3556 netdev_err(dev, "TX timeout on queue: %u, sq: %s, vq: 0x%x, name: %s, %u usecs ago\n",
3557 txqueue, sq->name, sq->vq->index, sq->vq->name,
3558 jiffies_to_usecs(jiffies - READ_ONCE(txq->trans_start)));
3561 static const struct net_device_ops virtnet_netdev = {
3562 .ndo_open = virtnet_open,
3563 .ndo_stop = virtnet_close,
3564 .ndo_start_xmit = start_xmit,
3565 .ndo_validate_addr = eth_validate_addr,
3566 .ndo_set_mac_address = virtnet_set_mac_address,
3567 .ndo_set_rx_mode = virtnet_set_rx_mode,
3568 .ndo_get_stats64 = virtnet_stats,
3569 .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
3570 .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
3571 .ndo_bpf = virtnet_xdp,
3572 .ndo_xdp_xmit = virtnet_xdp_xmit,
3573 .ndo_features_check = passthru_features_check,
3574 .ndo_get_phys_port_name = virtnet_get_phys_port_name,
3575 .ndo_set_features = virtnet_set_features,
3576 .ndo_tx_timeout = virtnet_tx_timeout,
3579 static void virtnet_config_changed_work(struct work_struct *work)
3581 struct virtnet_info *vi =
3582 container_of(work, struct virtnet_info, config_work);
3585 if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
3586 struct virtio_net_config, status, &v) < 0)
3589 if (v & VIRTIO_NET_S_ANNOUNCE) {
3590 netdev_notify_peers(vi->dev);
3591 virtnet_ack_link_announce(vi);
3594 /* Ignore unknown (future) status bits */
3595 v &= VIRTIO_NET_S_LINK_UP;
3597 if (vi->status == v)
3602 if (vi->status & VIRTIO_NET_S_LINK_UP) {
3603 virtnet_update_settings(vi);
3604 netif_carrier_on(vi->dev);
3605 netif_tx_wake_all_queues(vi->dev);
3607 netif_carrier_off(vi->dev);
3608 netif_tx_stop_all_queues(vi->dev);
3612 static void virtnet_config_changed(struct virtio_device *vdev)
3614 struct virtnet_info *vi = vdev->priv;
3616 schedule_work(&vi->config_work);
3619 static void virtnet_free_queues(struct virtnet_info *vi)
3623 for (i = 0; i < vi->max_queue_pairs; i++) {
3624 __netif_napi_del(&vi->rq[i].napi);
3625 __netif_napi_del(&vi->sq[i].napi);
3628 /* We called __netif_napi_del(),
3629 * we need to respect an RCU grace period before freeing vi->rq
3638 static void _free_receive_bufs(struct virtnet_info *vi)
3640 struct bpf_prog *old_prog;
3643 for (i = 0; i < vi->max_queue_pairs; i++) {
3644 while (vi->rq[i].pages)
3645 __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
3647 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
3648 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
3650 bpf_prog_put(old_prog);
3654 static void free_receive_bufs(struct virtnet_info *vi)
3657 _free_receive_bufs(vi);
3661 static void free_receive_page_frags(struct virtnet_info *vi)
3664 for (i = 0; i < vi->max_queue_pairs; i++)
3665 if (vi->rq[i].alloc_frag.page)
3666 put_page(vi->rq[i].alloc_frag.page);
3669 static void virtnet_sq_free_unused_buf(struct virtqueue *vq, void *buf)
3671 if (!is_xdp_frame(buf))
3674 xdp_return_frame(ptr_to_xdp(buf));
3677 static void virtnet_rq_free_unused_buf(struct virtqueue *vq, void *buf)
3679 struct virtnet_info *vi = vq->vdev->priv;
3682 if (vi->mergeable_rx_bufs)
3683 put_page(virt_to_head_page(buf));
3684 else if (vi->big_packets)
3685 give_pages(&vi->rq[i], buf);
3687 put_page(virt_to_head_page(buf));
3690 static void free_unused_bufs(struct virtnet_info *vi)
3695 for (i = 0; i < vi->max_queue_pairs; i++) {
3696 struct virtqueue *vq = vi->sq[i].vq;
3697 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3698 virtnet_sq_free_unused_buf(vq, buf);
3702 for (i = 0; i < vi->max_queue_pairs; i++) {
3703 struct virtqueue *vq = vi->rq[i].vq;
3704 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
3705 virtnet_rq_free_unused_buf(vq, buf);
3710 static void virtnet_del_vqs(struct virtnet_info *vi)
3712 struct virtio_device *vdev = vi->vdev;
3714 virtnet_clean_affinity(vi);
3716 vdev->config->del_vqs(vdev);
3718 virtnet_free_queues(vi);
3721 /* How large should a single buffer be so a queue full of these can fit at
3722 * least one full packet?
3723 * Logic below assumes the mergeable buffer header is used.
3725 static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
3727 const unsigned int hdr_len = vi->hdr_len;
3728 unsigned int rq_size = virtqueue_get_vring_size(vq);
3729 unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
3730 unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
3731 unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
3733 return max(max(min_buf_len, hdr_len) - hdr_len,
3734 (unsigned int)GOOD_PACKET_LEN);
3737 static int virtnet_find_vqs(struct virtnet_info *vi)
3739 vq_callback_t **callbacks;
3740 struct virtqueue **vqs;
3746 /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
3747 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
3748 * possible control vq.
3750 total_vqs = vi->max_queue_pairs * 2 +
3751 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
3753 /* Allocate space for find_vqs parameters */
3754 vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
3757 callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
3760 names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
3763 if (!vi->big_packets || vi->mergeable_rx_bufs) {
3764 ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
3771 /* Parameters for control virtqueue, if any */
3773 callbacks[total_vqs - 1] = NULL;
3774 names[total_vqs - 1] = "control";
3777 /* Allocate/initialize parameters for send/receive virtqueues */
3778 for (i = 0; i < vi->max_queue_pairs; i++) {
3779 callbacks[rxq2vq(i)] = skb_recv_done;
3780 callbacks[txq2vq(i)] = skb_xmit_done;
3781 sprintf(vi->rq[i].name, "input.%d", i);
3782 sprintf(vi->sq[i].name, "output.%d", i);
3783 names[rxq2vq(i)] = vi->rq[i].name;
3784 names[txq2vq(i)] = vi->sq[i].name;
3786 ctx[rxq2vq(i)] = true;
3789 ret = virtio_find_vqs_ctx(vi->vdev, total_vqs, vqs, callbacks,
3795 vi->cvq = vqs[total_vqs - 1];
3796 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
3797 vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
3800 for (i = 0; i < vi->max_queue_pairs; i++) {
3801 vi->rq[i].vq = vqs[rxq2vq(i)];
3802 vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
3803 vi->sq[i].vq = vqs[txq2vq(i)];
3806 /* run here: ret == 0. */
3821 static int virtnet_alloc_queues(struct virtnet_info *vi)
3826 vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
3832 vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
3835 vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
3839 INIT_DELAYED_WORK(&vi->refill, refill_work);
3840 for (i = 0; i < vi->max_queue_pairs; i++) {
3841 vi->rq[i].pages = NULL;
3842 netif_napi_add_weight(vi->dev, &vi->rq[i].napi, virtnet_poll,
3844 netif_napi_add_tx_weight(vi->dev, &vi->sq[i].napi,
3846 napi_tx ? napi_weight : 0);
3848 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
3849 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
3850 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
3852 u64_stats_init(&vi->rq[i].stats.syncp);
3853 u64_stats_init(&vi->sq[i].stats.syncp);
3866 static int init_vqs(struct virtnet_info *vi)
3870 /* Allocate send & receive queues */
3871 ret = virtnet_alloc_queues(vi);
3875 ret = virtnet_find_vqs(vi);
3880 virtnet_set_affinity(vi);
3886 virtnet_free_queues(vi);
3892 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
3895 struct virtnet_info *vi = netdev_priv(queue->dev);
3896 unsigned int queue_index = get_netdev_rx_queue_index(queue);
3897 unsigned int headroom = virtnet_get_headroom(vi);
3898 unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
3899 struct ewma_pkt_len *avg;
3901 BUG_ON(queue_index >= vi->max_queue_pairs);
3902 avg = &vi->rq[queue_index].mrg_avg_pkt_len;
3903 return sprintf(buf, "%u\n",
3904 get_mergeable_buf_len(&vi->rq[queue_index], avg,
3905 SKB_DATA_ALIGN(headroom + tailroom)));
3908 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
3909 __ATTR_RO(mergeable_rx_buffer_size);
3911 static struct attribute *virtio_net_mrg_rx_attrs[] = {
3912 &mergeable_rx_buffer_size_attribute.attr,
3916 static const struct attribute_group virtio_net_mrg_rx_group = {
3917 .name = "virtio_net",
3918 .attrs = virtio_net_mrg_rx_attrs
3922 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
3924 const char *fname, const char *dname)
3926 if (!virtio_has_feature(vdev, fbit))
3929 dev_err(&vdev->dev, "device advertises feature %s but not %s",
3935 #define VIRTNET_FAIL_ON(vdev, fbit, dbit) \
3936 virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
3938 static bool virtnet_validate_features(struct virtio_device *vdev)
3940 if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
3941 (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
3942 "VIRTIO_NET_F_CTRL_VQ") ||
3943 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
3944 "VIRTIO_NET_F_CTRL_VQ") ||
3945 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
3946 "VIRTIO_NET_F_CTRL_VQ") ||
3947 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
3948 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
3949 "VIRTIO_NET_F_CTRL_VQ") ||
3950 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_RSS,
3951 "VIRTIO_NET_F_CTRL_VQ") ||
3952 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_HASH_REPORT,
3953 "VIRTIO_NET_F_CTRL_VQ") ||
3954 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_NOTF_COAL,
3955 "VIRTIO_NET_F_CTRL_VQ"))) {
3962 #define MIN_MTU ETH_MIN_MTU
3963 #define MAX_MTU ETH_MAX_MTU
3965 static int virtnet_validate(struct virtio_device *vdev)
3967 if (!vdev->config->get) {
3968 dev_err(&vdev->dev, "%s failure: config access disabled\n",
3973 if (!virtnet_validate_features(vdev))
3976 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
3977 int mtu = virtio_cread16(vdev,
3978 offsetof(struct virtio_net_config,
3981 __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
3984 if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY) &&
3985 !virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
3986 dev_warn(&vdev->dev, "device advertises feature VIRTIO_NET_F_STANDBY but not VIRTIO_NET_F_MAC, disabling standby");
3987 __virtio_clear_bit(vdev, VIRTIO_NET_F_STANDBY);
3993 static bool virtnet_check_guest_gso(const struct virtnet_info *vi)
3995 return virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3996 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3997 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
3998 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
3999 (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO4) &&
4000 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_USO6));
4003 static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu)
4005 bool guest_gso = virtnet_check_guest_gso(vi);
4007 /* If device can receive ANY guest GSO packets, regardless of mtu,
4008 * allocate packets of maximum size, otherwise limit it to only
4009 * mtu size worth only.
4011 if (mtu > ETH_DATA_LEN || guest_gso) {
4012 vi->big_packets = true;
4013 vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE);
4017 static int virtnet_probe(struct virtio_device *vdev)
4019 int i, err = -ENOMEM;
4020 struct net_device *dev;
4021 struct virtnet_info *vi;
4022 u16 max_queue_pairs;
4025 /* Find if host supports multiqueue/rss virtio_net device */
4026 max_queue_pairs = 1;
4027 if (virtio_has_feature(vdev, VIRTIO_NET_F_MQ) || virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
4029 virtio_cread16(vdev, offsetof(struct virtio_net_config, max_virtqueue_pairs));
4031 /* We need at least 2 queue's */
4032 if (max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
4033 max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
4034 !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
4035 max_queue_pairs = 1;
4037 /* Allocate ourselves a network device with room for our info */
4038 dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
4042 /* Set up network device as normal. */
4043 dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE |
4044 IFF_TX_SKB_NO_LINEAR;
4045 dev->netdev_ops = &virtnet_netdev;
4046 dev->features = NETIF_F_HIGHDMA;
4048 dev->ethtool_ops = &virtnet_ethtool_ops;
4049 SET_NETDEV_DEV(dev, &vdev->dev);
4051 /* Do we support "hardware" checksums? */
4052 if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
4053 /* This opens up the world of extra features. */
4054 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
4056 dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
4058 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
4059 dev->hw_features |= NETIF_F_TSO
4060 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
4062 /* Individual feature bits: what can host handle? */
4063 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
4064 dev->hw_features |= NETIF_F_TSO;
4065 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
4066 dev->hw_features |= NETIF_F_TSO6;
4067 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
4068 dev->hw_features |= NETIF_F_TSO_ECN;
4069 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_USO))
4070 dev->hw_features |= NETIF_F_GSO_UDP_L4;
4072 dev->features |= NETIF_F_GSO_ROBUST;
4075 dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
4076 /* (!csum && gso) case will be fixed by register_netdev() */
4078 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
4079 dev->features |= NETIF_F_RXCSUM;
4080 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
4081 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
4082 dev->features |= NETIF_F_GRO_HW;
4083 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
4084 dev->hw_features |= NETIF_F_GRO_HW;
4086 dev->vlan_features = dev->features;
4087 dev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT;
4089 /* MTU range: 68 - 65535 */
4090 dev->min_mtu = MIN_MTU;
4091 dev->max_mtu = MAX_MTU;
4093 /* Configuration may specify what MAC to use. Otherwise random. */
4094 if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
4097 virtio_cread_bytes(vdev,
4098 offsetof(struct virtio_net_config, mac),
4100 eth_hw_addr_set(dev, addr);
4102 eth_hw_addr_random(dev);
4103 dev_info(&vdev->dev, "Assigned random MAC address %pM\n",
4107 /* Set up our device-specific information */
4108 vi = netdev_priv(dev);
4113 INIT_WORK(&vi->config_work, virtnet_config_changed_work);
4114 spin_lock_init(&vi->refill_lock);
4116 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) {
4117 vi->mergeable_rx_bufs = true;
4118 dev->xdp_features |= NETDEV_XDP_ACT_RX_SG;
4121 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_NOTF_COAL)) {
4124 vi->tx_max_packets = 0;
4125 vi->rx_max_packets = 0;
4128 if (virtio_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT))
4129 vi->has_rss_hash_report = true;
4131 if (virtio_has_feature(vdev, VIRTIO_NET_F_RSS))
4134 if (vi->has_rss || vi->has_rss_hash_report) {
4135 vi->rss_indir_table_size =
4136 virtio_cread16(vdev, offsetof(struct virtio_net_config,
4137 rss_max_indirection_table_length));
4139 virtio_cread8(vdev, offsetof(struct virtio_net_config, rss_max_key_size));
4141 vi->rss_hash_types_supported =
4142 virtio_cread32(vdev, offsetof(struct virtio_net_config, supported_hash_types));
4143 vi->rss_hash_types_supported &=
4144 ~(VIRTIO_NET_RSS_HASH_TYPE_IP_EX |
4145 VIRTIO_NET_RSS_HASH_TYPE_TCP_EX |
4146 VIRTIO_NET_RSS_HASH_TYPE_UDP_EX);
4148 dev->hw_features |= NETIF_F_RXHASH;
4151 if (vi->has_rss_hash_report)
4152 vi->hdr_len = sizeof(struct virtio_net_hdr_v1_hash);
4153 else if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
4154 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4155 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
4157 vi->hdr_len = sizeof(struct virtio_net_hdr);
4159 if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
4160 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
4161 vi->any_header_sg = true;
4163 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
4166 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
4167 mtu = virtio_cread16(vdev,
4168 offsetof(struct virtio_net_config,
4170 if (mtu < dev->min_mtu) {
4171 /* Should never trigger: MTU was previously validated
4172 * in virtnet_validate.
4175 "device MTU appears to have changed it is now %d < %d",
4185 virtnet_set_big_packets(vi, mtu);
4187 if (vi->any_header_sg)
4188 dev->needed_headroom = vi->hdr_len;
4190 /* Enable multiqueue by default */
4191 if (num_online_cpus() >= max_queue_pairs)
4192 vi->curr_queue_pairs = max_queue_pairs;
4194 vi->curr_queue_pairs = num_online_cpus();
4195 vi->max_queue_pairs = max_queue_pairs;
4197 /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
4203 if (vi->mergeable_rx_bufs)
4204 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
4206 netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
4207 netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
4209 virtnet_init_settings(dev);
4211 if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
4212 vi->failover = net_failover_create(vi->dev);
4213 if (IS_ERR(vi->failover)) {
4214 err = PTR_ERR(vi->failover);
4219 if (vi->has_rss || vi->has_rss_hash_report)
4220 virtnet_init_default_rss(vi);
4222 /* serialize netdev register + virtio_device_ready() with ndo_open() */
4225 err = register_netdevice(dev);
4227 pr_debug("virtio_net: registering device failed\n");
4232 virtio_device_ready(vdev);
4234 _virtnet_set_queues(vi, vi->curr_queue_pairs);
4236 /* a random MAC address has been assigned, notify the device.
4237 * We don't fail probe if VIRTIO_NET_F_CTRL_MAC_ADDR is not there
4238 * because many devices work fine without getting MAC explicitly
4240 if (!virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
4241 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
4242 struct scatterlist sg;
4244 sg_init_one(&sg, dev->dev_addr, dev->addr_len);
4245 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
4246 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
4247 pr_debug("virtio_net: setting MAC address failed\n");
4250 goto free_unregister_netdev;
4256 err = virtnet_cpu_notif_add(vi);
4258 pr_debug("virtio_net: registering cpu notifier failed\n");
4259 goto free_unregister_netdev;
4262 /* Assume link up if device can't report link status,
4263 otherwise get link status from config. */
4264 netif_carrier_off(dev);
4265 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
4266 schedule_work(&vi->config_work);
4268 vi->status = VIRTIO_NET_S_LINK_UP;
4269 virtnet_update_settings(vi);
4270 netif_carrier_on(dev);
4273 for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
4274 if (virtio_has_feature(vi->vdev, guest_offloads[i]))
4275 set_bit(guest_offloads[i], &vi->guest_offloads);
4276 vi->guest_offloads_capable = vi->guest_offloads;
4278 pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
4279 dev->name, max_queue_pairs);
4283 free_unregister_netdev:
4284 unregister_netdev(dev);
4286 net_failover_destroy(vi->failover);
4288 virtio_reset_device(vdev);
4289 cancel_delayed_work_sync(&vi->refill);
4290 free_receive_page_frags(vi);
4291 virtnet_del_vqs(vi);
4297 static void remove_vq_common(struct virtnet_info *vi)
4299 virtio_reset_device(vi->vdev);
4301 /* Free unused buffers in both send and recv, if any. */
4302 free_unused_bufs(vi);
4304 free_receive_bufs(vi);
4306 free_receive_page_frags(vi);
4308 virtnet_del_vqs(vi);
4311 static void virtnet_remove(struct virtio_device *vdev)
4313 struct virtnet_info *vi = vdev->priv;
4315 virtnet_cpu_notif_remove(vi);
4317 /* Make sure no work handler is accessing the device. */
4318 flush_work(&vi->config_work);
4320 unregister_netdev(vi->dev);
4322 net_failover_destroy(vi->failover);
4324 remove_vq_common(vi);
4326 free_netdev(vi->dev);
4329 static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
4331 struct virtnet_info *vi = vdev->priv;
4333 virtnet_cpu_notif_remove(vi);
4334 virtnet_freeze_down(vdev);
4335 remove_vq_common(vi);
4340 static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
4342 struct virtnet_info *vi = vdev->priv;
4345 err = virtnet_restore_up(vdev);
4348 virtnet_set_queues(vi, vi->curr_queue_pairs);
4350 err = virtnet_cpu_notif_add(vi);
4352 virtnet_freeze_down(vdev);
4353 remove_vq_common(vi);
4360 static struct virtio_device_id id_table[] = {
4361 { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
4365 #define VIRTNET_FEATURES \
4366 VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
4368 VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
4369 VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
4370 VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
4371 VIRTIO_NET_F_HOST_USO, VIRTIO_NET_F_GUEST_USO4, VIRTIO_NET_F_GUEST_USO6, \
4372 VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
4373 VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
4374 VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
4375 VIRTIO_NET_F_CTRL_MAC_ADDR, \
4376 VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
4377 VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY, \
4378 VIRTIO_NET_F_RSS, VIRTIO_NET_F_HASH_REPORT, VIRTIO_NET_F_NOTF_COAL, \
4379 VIRTIO_NET_F_GUEST_HDRLEN
4381 static unsigned int features[] = {
4385 static unsigned int features_legacy[] = {
4388 VIRTIO_F_ANY_LAYOUT,
4391 static struct virtio_driver virtio_net_driver = {
4392 .feature_table = features,
4393 .feature_table_size = ARRAY_SIZE(features),
4394 .feature_table_legacy = features_legacy,
4395 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
4396 .driver.name = KBUILD_MODNAME,
4397 .driver.owner = THIS_MODULE,
4398 .id_table = id_table,
4399 .validate = virtnet_validate,
4400 .probe = virtnet_probe,
4401 .remove = virtnet_remove,
4402 .config_changed = virtnet_config_changed,
4403 #ifdef CONFIG_PM_SLEEP
4404 .freeze = virtnet_freeze,
4405 .restore = virtnet_restore,
4409 static __init int virtio_net_driver_init(void)
4413 ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
4415 virtnet_cpu_down_prep);
4418 virtionet_online = ret;
4419 ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
4420 NULL, virtnet_cpu_dead);
4423 ret = register_virtio_driver(&virtio_net_driver);
4428 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4430 cpuhp_remove_multi_state(virtionet_online);
4434 module_init(virtio_net_driver_init);
4436 static __exit void virtio_net_driver_exit(void)
4438 unregister_virtio_driver(&virtio_net_driver);
4439 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
4440 cpuhp_remove_multi_state(virtionet_online);
4442 module_exit(virtio_net_driver_exit);
4444 MODULE_DEVICE_TABLE(virtio, id_table);
4445 MODULE_DESCRIPTION("Virtio network driver");
4446 MODULE_LICENSE("GPL");