1 /* A network driver using virtio.
3 * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 #include <linux/netdevice.h>
20 #include <linux/etherdevice.h>
21 #include <linux/ethtool.h>
22 #include <linux/module.h>
23 #include <linux/virtio.h>
24 #include <linux/virtio_net.h>
25 #include <linux/bpf.h>
26 #include <linux/bpf_trace.h>
27 #include <linux/scatterlist.h>
28 #include <linux/if_vlan.h>
29 #include <linux/slab.h>
30 #include <linux/cpu.h>
31 #include <linux/average.h>
33 static int napi_weight = NAPI_POLL_WEIGHT;
34 module_param(napi_weight, int, 0444);
36 static bool csum = true, gso = true;
37 module_param(csum, bool, 0444);
38 module_param(gso, bool, 0444);
40 /* FIXME: MTU in config. */
41 #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
42 #define GOOD_COPY_LEN 128
44 #define VIRTNET_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
46 /* Amount of XDP headroom to prepend to packets for use by xdp_adjust_head */
47 #define VIRTIO_XDP_HEADROOM 256
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, 1, 64)
56 /* With mergeable buffers we align buffer address and use the low bits to
57 * encode its true size. Buffer size is up to 1 page so we need to align to
58 * square root of page size to ensure we reserve enough bits to encode the true
61 #define MERGEABLE_BUFFER_MIN_ALIGN_SHIFT ((PAGE_SHIFT + 1) / 2)
63 /* Minimum alignment for mergeable packet buffers. */
64 #define MERGEABLE_BUFFER_ALIGN max(L1_CACHE_BYTES, \
65 1 << MERGEABLE_BUFFER_MIN_ALIGN_SHIFT)
67 #define VIRTNET_DRIVER_VERSION "1.0.0"
69 struct virtnet_stats {
70 struct u64_stats_sync tx_syncp;
71 struct u64_stats_sync rx_syncp;
79 /* Internal representation of a send virtqueue */
81 /* Virtqueue associated with this send _queue */
84 /* TX: fragments + linear part + virtio header */
85 struct scatterlist sg[MAX_SKB_FRAGS + 2];
87 /* Name of the send queue: output.$index */
91 /* Internal representation of a receive virtqueue */
92 struct receive_queue {
93 /* Virtqueue associated with this receive_queue */
96 struct napi_struct napi;
98 struct bpf_prog __rcu *xdp_prog;
100 /* Chain pages by the private ptr. */
103 /* Average packet length for mergeable receive buffers. */
104 struct ewma_pkt_len mrg_avg_pkt_len;
106 /* Page frag for packet buffer allocation. */
107 struct page_frag alloc_frag;
109 /* RX: fragments + linear part + virtio header */
110 struct scatterlist sg[MAX_SKB_FRAGS + 2];
112 /* Name of this receive queue: input.$index */
116 struct virtnet_info {
117 struct virtio_device *vdev;
118 struct virtqueue *cvq;
119 struct net_device *dev;
120 struct send_queue *sq;
121 struct receive_queue *rq;
124 /* Max # of queue pairs supported by the device */
127 /* # of queue pairs currently used by the driver */
128 u16 curr_queue_pairs;
130 /* # of XDP queue pairs currently used by the driver */
133 /* I like... big packets and I cannot lie! */
136 /* Host will merge rx buffers for big packets (shake it! shake it!) */
137 bool mergeable_rx_bufs;
139 /* Has control virtqueue */
142 /* Host can handle any s/g split between our header and packet data */
145 /* Packet virtio header size */
148 /* Active statistics */
149 struct virtnet_stats __percpu *stats;
151 /* Work struct for refilling if we run low on memory. */
152 struct delayed_work refill;
154 /* Work struct for config space updates */
155 struct work_struct config_work;
157 /* Does the affinity hint is set for virtqueues? */
158 bool affinity_hint_set;
160 /* CPU hotplug instances for online & dead */
161 struct hlist_node node;
162 struct hlist_node node_dead;
164 /* Control VQ buffers: protected by the rtnl lock */
165 struct virtio_net_ctrl_hdr ctrl_hdr;
166 virtio_net_ctrl_ack ctrl_status;
167 struct virtio_net_ctrl_mq ctrl_mq;
172 /* Ethtool settings */
177 struct padded_vnet_hdr {
178 struct virtio_net_hdr_mrg_rxbuf hdr;
180 * hdr is in a separate sg buffer, and data sg buffer shares same page
181 * with this header sg. This padding makes next sg 16 byte aligned
187 /* Converting between virtqueue no. and kernel tx/rx queue no.
188 * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
190 static int vq2txq(struct virtqueue *vq)
192 return (vq->index - 1) / 2;
195 static int txq2vq(int txq)
200 static int vq2rxq(struct virtqueue *vq)
202 return vq->index / 2;
205 static int rxq2vq(int rxq)
210 static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
212 return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
216 * private is used to chain pages for big packets, put the whole
217 * most recent used list in the beginning for reuse
219 static void give_pages(struct receive_queue *rq, struct page *page)
223 /* Find end of list, sew whole thing into vi->rq.pages. */
224 for (end = page; end->private; end = (struct page *)end->private);
225 end->private = (unsigned long)rq->pages;
229 static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
231 struct page *p = rq->pages;
234 rq->pages = (struct page *)p->private;
235 /* clear private here, it is used to chain pages */
238 p = alloc_page(gfp_mask);
242 static void skb_xmit_done(struct virtqueue *vq)
244 struct virtnet_info *vi = vq->vdev->priv;
246 /* Suppress further interrupts. */
247 virtqueue_disable_cb(vq);
249 /* We were probably waiting for more output buffers. */
250 netif_wake_subqueue(vi->dev, vq2txq(vq));
253 static unsigned int mergeable_ctx_to_buf_truesize(unsigned long mrg_ctx)
255 unsigned int truesize = mrg_ctx & (MERGEABLE_BUFFER_ALIGN - 1);
256 return (truesize + 1) * MERGEABLE_BUFFER_ALIGN;
259 static void *mergeable_ctx_to_buf_address(unsigned long mrg_ctx)
261 return (void *)(mrg_ctx & -MERGEABLE_BUFFER_ALIGN);
265 static unsigned long mergeable_buf_to_ctx(void *buf, unsigned int truesize)
267 unsigned int size = truesize / MERGEABLE_BUFFER_ALIGN;
268 return (unsigned long)buf | (size - 1);
271 /* Called from bottom half context */
272 static struct sk_buff *page_to_skb(struct virtnet_info *vi,
273 struct receive_queue *rq,
274 struct page *page, unsigned int offset,
275 unsigned int len, unsigned int truesize)
278 struct virtio_net_hdr_mrg_rxbuf *hdr;
279 unsigned int copy, hdr_len, hdr_padded_len;
282 p = page_address(page) + offset;
284 /* copy small packet so we can reuse these pages for small data */
285 skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
289 hdr = skb_vnet_hdr(skb);
291 hdr_len = vi->hdr_len;
292 if (vi->mergeable_rx_bufs)
293 hdr_padded_len = sizeof *hdr;
295 hdr_padded_len = sizeof(struct padded_vnet_hdr);
297 memcpy(hdr, p, hdr_len);
300 offset += hdr_padded_len;
304 if (copy > skb_tailroom(skb))
305 copy = skb_tailroom(skb);
306 memcpy(skb_put(skb, copy), p, copy);
311 if (vi->mergeable_rx_bufs) {
313 skb_add_rx_frag(skb, 0, page, offset, len, truesize);
320 * Verify that we can indeed put this data into a skb.
321 * This is here to handle cases when the device erroneously
322 * tries to receive more than is possible. This is usually
323 * the case of a broken device.
325 if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
326 net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
330 BUG_ON(offset >= PAGE_SIZE);
332 unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
333 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
334 frag_size, truesize);
336 page = (struct page *)page->private;
341 give_pages(rq, page);
346 static bool virtnet_xdp_xmit(struct virtnet_info *vi,
347 struct receive_queue *rq,
348 struct xdp_buff *xdp)
350 struct virtio_net_hdr_mrg_rxbuf *hdr;
352 struct send_queue *sq;
357 qp = vi->curr_queue_pairs - vi->xdp_queue_pairs + smp_processor_id();
360 /* Free up any pending old buffers before queueing new ones. */
361 while ((xdp_sent = virtqueue_get_buf(sq->vq, &len)) != NULL) {
362 struct page *sent_page = virt_to_head_page(xdp_sent);
367 xdp->data -= vi->hdr_len;
368 /* Zero header and leave csum up to XDP layers */
370 memset(hdr, 0, vi->hdr_len);
372 sg_init_one(sq->sg, xdp->data, xdp->data_end - xdp->data);
374 err = virtqueue_add_outbuf(sq->vq, sq->sg, 1, xdp->data, GFP_ATOMIC);
376 struct page *page = virt_to_head_page(xdp->data);
382 virtqueue_kick(sq->vq);
386 static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
388 return vi->xdp_queue_pairs ? VIRTIO_XDP_HEADROOM : 0;
391 static struct sk_buff *receive_small(struct net_device *dev,
392 struct virtnet_info *vi,
393 struct receive_queue *rq,
394 void *buf, unsigned int len)
397 struct bpf_prog *xdp_prog;
398 unsigned int xdp_headroom = virtnet_get_headroom(vi);
399 unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
400 unsigned int headroom = vi->hdr_len + header_offset;
401 unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
402 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
403 unsigned int delta = 0;
407 xdp_prog = rcu_dereference(rq->xdp_prog);
409 struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
414 if (unlikely(hdr->hdr.gso_type || hdr->hdr.flags))
417 xdp.data_hard_start = buf + VIRTNET_RX_PAD + vi->hdr_len;
418 xdp.data = xdp.data_hard_start + xdp_headroom;
419 xdp.data_end = xdp.data + len;
420 orig_data = xdp.data;
421 act = bpf_prog_run_xdp(xdp_prog, &xdp);
425 /* Recalculate length in case bpf program changed it */
426 delta = orig_data - xdp.data;
429 if (unlikely(!virtnet_xdp_xmit(vi, rq, &xdp)))
430 trace_xdp_exception(vi->dev, xdp_prog, act);
434 bpf_warn_invalid_xdp_action(act);
436 trace_xdp_exception(vi->dev, xdp_prog, act);
443 skb = build_skb(buf, buflen);
445 put_page(virt_to_head_page(buf));
448 skb_reserve(skb, headroom - delta);
449 skb_put(skb, len + delta);
451 buf += header_offset;
452 memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
453 } /* keep zeroed vnet hdr since packet was changed by bpf */
460 dev->stats.rx_dropped++;
461 put_page(virt_to_head_page(buf));
466 static struct sk_buff *receive_big(struct net_device *dev,
467 struct virtnet_info *vi,
468 struct receive_queue *rq,
472 struct page *page = buf;
473 struct sk_buff *skb = page_to_skb(vi, rq, page, 0, len, PAGE_SIZE);
481 dev->stats.rx_dropped++;
482 give_pages(rq, page);
486 /* The conditions to enable XDP should preclude the underlying device from
487 * sending packets across multiple buffers (num_buf > 1). However per spec
488 * it does not appear to be illegal to do so but rather just against convention.
489 * So in order to avoid making a system unresponsive the packets are pushed
490 * into a page and the XDP program is run. This will be extremely slow and we
491 * push a warning to the user to fix this as soon as possible. Fixing this may
492 * require resolving the underlying hardware to determine why multiple buffers
493 * are being received or simply loading the XDP program in the ingress stack
494 * after the skb is built because there is no advantage to running it here
497 static struct page *xdp_linearize_page(struct receive_queue *rq,
503 struct page *page = alloc_page(GFP_ATOMIC);
504 unsigned int page_off = VIRTIO_XDP_HEADROOM;
509 memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
518 ctx = (unsigned long)virtqueue_get_buf(rq->vq, &buflen);
522 buf = mergeable_ctx_to_buf_address(ctx);
523 p = virt_to_head_page(buf);
524 off = buf - page_address(p);
526 /* guard against a misconfigured or uncooperative backend that
527 * is sending packet larger than the MTU.
529 if ((page_off + buflen) > PAGE_SIZE) {
534 memcpy(page_address(page) + page_off,
535 page_address(p) + off, buflen);
540 /* Headroom does not contribute to packet length */
541 *len = page_off - VIRTIO_XDP_HEADROOM;
544 __free_pages(page, 0);
548 static struct sk_buff *receive_mergeable(struct net_device *dev,
549 struct virtnet_info *vi,
550 struct receive_queue *rq,
554 void *buf = mergeable_ctx_to_buf_address(ctx);
555 struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
556 u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
557 struct page *page = virt_to_head_page(buf);
558 int offset = buf - page_address(page);
559 struct sk_buff *head_skb, *curr_skb;
560 struct bpf_prog *xdp_prog;
561 unsigned int truesize;
566 xdp_prog = rcu_dereference(rq->xdp_prog);
568 struct page *xdp_page;
573 /* This happens when rx buffer size is underestimated */
574 if (unlikely(num_buf > 1)) {
575 /* linearize data for XDP */
576 xdp_page = xdp_linearize_page(rq, &num_buf,
580 offset = VIRTIO_XDP_HEADROOM;
585 /* Transient failure which in theory could occur if
586 * in-flight packets from before XDP was enabled reach
587 * the receive path after XDP is loaded. In practice I
588 * was not able to create this condition.
590 if (unlikely(hdr->hdr.gso_type))
593 /* Allow consuming headroom but reserve enough space to push
594 * the descriptor on if we get an XDP_TX return code.
596 data = page_address(xdp_page) + offset;
597 xdp.data_hard_start = data - VIRTIO_XDP_HEADROOM + vi->hdr_len;
598 xdp.data = data + vi->hdr_len;
599 xdp.data_end = xdp.data + (len - vi->hdr_len);
600 act = bpf_prog_run_xdp(xdp_prog, &xdp);
604 /* recalculate offset to account for any header
605 * adjustments. Note other cases do not build an
606 * skb and avoid using offset
609 page_address(xdp_page) - vi->hdr_len;
611 /* We can only create skb based on xdp_page. */
612 if (unlikely(xdp_page != page)) {
615 head_skb = page_to_skb(vi, rq, xdp_page,
616 offset, len, PAGE_SIZE);
617 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, len);
622 if (unlikely(!virtnet_xdp_xmit(vi, rq, &xdp)))
623 trace_xdp_exception(vi->dev, xdp_prog, act);
624 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, len);
625 if (unlikely(xdp_page != page))
630 bpf_warn_invalid_xdp_action(act);
632 trace_xdp_exception(vi->dev, xdp_prog, act);
634 if (unlikely(xdp_page != page))
635 __free_pages(xdp_page, 0);
636 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, len);
642 truesize = max(len, mergeable_ctx_to_buf_truesize(ctx));
643 head_skb = page_to_skb(vi, rq, page, offset, len, truesize);
646 if (unlikely(!curr_skb))
651 ctx = (unsigned long)virtqueue_get_buf(rq->vq, &len);
652 if (unlikely(!ctx)) {
653 pr_debug("%s: rx error: %d buffers out of %d missing\n",
655 virtio16_to_cpu(vi->vdev,
657 dev->stats.rx_length_errors++;
661 buf = mergeable_ctx_to_buf_address(ctx);
662 page = virt_to_head_page(buf);
664 num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
665 if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
666 struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
670 if (curr_skb == head_skb)
671 skb_shinfo(curr_skb)->frag_list = nskb;
673 curr_skb->next = nskb;
675 head_skb->truesize += nskb->truesize;
678 truesize = max(len, mergeable_ctx_to_buf_truesize(ctx));
679 if (curr_skb != head_skb) {
680 head_skb->data_len += len;
681 head_skb->len += len;
682 head_skb->truesize += truesize;
684 offset = buf - page_address(page);
685 if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
687 skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
690 skb_add_rx_frag(curr_skb, num_skb_frags, page,
691 offset, len, truesize);
695 ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
703 ctx = (unsigned long)virtqueue_get_buf(rq->vq, &len);
704 if (unlikely(!ctx)) {
705 pr_debug("%s: rx error: %d buffers missing\n",
707 dev->stats.rx_length_errors++;
710 page = virt_to_head_page(mergeable_ctx_to_buf_address(ctx));
714 dev->stats.rx_dropped++;
715 dev_kfree_skb(head_skb);
720 static int receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
721 void *buf, unsigned int len)
723 struct net_device *dev = vi->dev;
725 struct virtio_net_hdr_mrg_rxbuf *hdr;
728 if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
729 pr_debug("%s: short packet %i\n", dev->name, len);
730 dev->stats.rx_length_errors++;
731 if (vi->mergeable_rx_bufs) {
732 unsigned long ctx = (unsigned long)buf;
733 void *base = mergeable_ctx_to_buf_address(ctx);
734 put_page(virt_to_head_page(base));
735 } else if (vi->big_packets) {
738 put_page(virt_to_head_page(buf));
743 if (vi->mergeable_rx_bufs)
744 skb = receive_mergeable(dev, vi, rq, (unsigned long)buf, len);
745 else if (vi->big_packets)
746 skb = receive_big(dev, vi, rq, buf, len);
748 skb = receive_small(dev, vi, rq, buf, len);
753 hdr = skb_vnet_hdr(skb);
757 if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
758 skb->ip_summed = CHECKSUM_UNNECESSARY;
760 if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
761 virtio_is_little_endian(vi->vdev))) {
762 net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
763 dev->name, hdr->hdr.gso_type,
768 skb->protocol = eth_type_trans(skb, dev);
769 pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
770 ntohs(skb->protocol), skb->len, skb->pkt_type);
772 napi_gro_receive(&rq->napi, skb);
776 dev->stats.rx_frame_errors++;
781 static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
784 struct page_frag *alloc_frag = &rq->alloc_frag;
786 unsigned int xdp_headroom = virtnet_get_headroom(vi);
787 int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
790 len = SKB_DATA_ALIGN(len) +
791 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
792 if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
795 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
796 get_page(alloc_frag->page);
797 alloc_frag->offset += len;
798 sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
799 vi->hdr_len + GOOD_PACKET_LEN);
800 err = virtqueue_add_inbuf(rq->vq, rq->sg, 1, buf, gfp);
802 put_page(virt_to_head_page(buf));
807 static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
810 struct page *first, *list = NULL;
814 sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
816 /* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
817 for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
818 first = get_a_page(rq, gfp);
821 give_pages(rq, list);
824 sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
826 /* chain new page in list head to match sg */
827 first->private = (unsigned long)list;
831 first = get_a_page(rq, gfp);
833 give_pages(rq, list);
836 p = page_address(first);
838 /* rq->sg[0], rq->sg[1] share the same page */
839 /* a separated rq->sg[0] for header - required in case !any_header_sg */
840 sg_set_buf(&rq->sg[0], p, vi->hdr_len);
842 /* rq->sg[1] for data packet, from offset */
843 offset = sizeof(struct padded_vnet_hdr);
844 sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
846 /* chain first in list head */
847 first->private = (unsigned long)list;
848 err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
851 give_pages(rq, first);
856 static unsigned int get_mergeable_buf_len(struct ewma_pkt_len *avg_pkt_len)
858 const size_t hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
861 len = hdr_len + clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
862 GOOD_PACKET_LEN, PAGE_SIZE - hdr_len);
863 return ALIGN(len, MERGEABLE_BUFFER_ALIGN);
866 static int add_recvbuf_mergeable(struct virtnet_info *vi,
867 struct receive_queue *rq, gfp_t gfp)
869 struct page_frag *alloc_frag = &rq->alloc_frag;
870 unsigned int headroom = virtnet_get_headroom(vi);
874 unsigned int len, hole;
876 len = get_mergeable_buf_len(&rq->mrg_avg_pkt_len);
877 if (unlikely(!skb_page_frag_refill(len + headroom, alloc_frag, gfp)))
880 buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
881 buf += headroom; /* advance address leaving hole at front of pkt */
882 ctx = mergeable_buf_to_ctx(buf, len);
883 get_page(alloc_frag->page);
884 alloc_frag->offset += len + headroom;
885 hole = alloc_frag->size - alloc_frag->offset;
886 if (hole < len + headroom) {
887 /* To avoid internal fragmentation, if there is very likely not
888 * enough space for another buffer, add the remaining space to
889 * the current buffer. This extra space is not included in
890 * the truesize stored in ctx.
893 alloc_frag->offset += hole;
896 sg_init_one(rq->sg, buf, len);
897 err = virtqueue_add_inbuf(rq->vq, rq->sg, 1, (void *)ctx, gfp);
899 put_page(virt_to_head_page(buf));
905 * Returns false if we couldn't fill entirely (OOM).
907 * Normally run in the receive path, but can also be run from ndo_open
908 * before we're receiving packets, or from refill_work which is
909 * careful to disable receiving (using napi_disable).
911 static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
919 if (vi->mergeable_rx_bufs)
920 err = add_recvbuf_mergeable(vi, rq, gfp);
921 else if (vi->big_packets)
922 err = add_recvbuf_big(vi, rq, gfp);
924 err = add_recvbuf_small(vi, rq, gfp);
926 oom = err == -ENOMEM;
929 } while (rq->vq->num_free);
930 virtqueue_kick(rq->vq);
934 static void skb_recv_done(struct virtqueue *rvq)
936 struct virtnet_info *vi = rvq->vdev->priv;
937 struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
939 /* Schedule NAPI, Suppress further interrupts if successful. */
940 if (napi_schedule_prep(&rq->napi)) {
941 virtqueue_disable_cb(rvq);
942 __napi_schedule(&rq->napi);
946 static void virtnet_napi_enable(struct receive_queue *rq)
948 napi_enable(&rq->napi);
950 /* If all buffers were filled by other side before we napi_enabled, we
951 * won't get another interrupt, so process any outstanding packets
952 * now. virtnet_poll wants re-enable the queue, so we disable here.
953 * We synchronize against interrupts via NAPI_STATE_SCHED */
954 if (napi_schedule_prep(&rq->napi)) {
955 virtqueue_disable_cb(rq->vq);
957 __napi_schedule(&rq->napi);
962 static void refill_work(struct work_struct *work)
964 struct virtnet_info *vi =
965 container_of(work, struct virtnet_info, refill.work);
969 for (i = 0; i < vi->curr_queue_pairs; i++) {
970 struct receive_queue *rq = &vi->rq[i];
972 napi_disable(&rq->napi);
973 still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
974 virtnet_napi_enable(rq);
976 /* In theory, this can happen: if we don't get any buffers in
977 * we will *never* try to fill again.
980 schedule_delayed_work(&vi->refill, HZ/2);
984 static int virtnet_receive(struct receive_queue *rq, int budget)
986 struct virtnet_info *vi = rq->vq->vdev->priv;
987 unsigned int len, received = 0, bytes = 0;
989 struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
991 while (received < budget &&
992 (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
993 bytes += receive_buf(vi, rq, buf, len);
997 if (rq->vq->num_free > virtqueue_get_vring_size(rq->vq) / 2) {
998 if (!try_fill_recv(vi, rq, GFP_ATOMIC))
999 schedule_delayed_work(&vi->refill, 0);
1002 u64_stats_update_begin(&stats->rx_syncp);
1003 stats->rx_bytes += bytes;
1004 stats->rx_packets += received;
1005 u64_stats_update_end(&stats->rx_syncp);
1010 static int virtnet_poll(struct napi_struct *napi, int budget)
1012 struct receive_queue *rq =
1013 container_of(napi, struct receive_queue, napi);
1014 unsigned int r, received;
1016 received = virtnet_receive(rq, budget);
1018 /* Out of packets? */
1019 if (received < budget) {
1020 r = virtqueue_enable_cb_prepare(rq->vq);
1021 if (napi_complete_done(napi, received)) {
1022 if (unlikely(virtqueue_poll(rq->vq, r)) &&
1023 napi_schedule_prep(napi)) {
1024 virtqueue_disable_cb(rq->vq);
1025 __napi_schedule(napi);
1033 static int virtnet_open(struct net_device *dev)
1035 struct virtnet_info *vi = netdev_priv(dev);
1038 for (i = 0; i < vi->max_queue_pairs; i++) {
1039 if (i < vi->curr_queue_pairs)
1040 /* Make sure we have some buffers: if oom use wq. */
1041 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1042 schedule_delayed_work(&vi->refill, 0);
1043 virtnet_napi_enable(&vi->rq[i]);
1049 static void free_old_xmit_skbs(struct send_queue *sq)
1051 struct sk_buff *skb;
1053 struct virtnet_info *vi = sq->vq->vdev->priv;
1054 struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
1055 unsigned int packets = 0;
1056 unsigned int bytes = 0;
1058 while ((skb = virtqueue_get_buf(sq->vq, &len)) != NULL) {
1059 pr_debug("Sent skb %p\n", skb);
1064 dev_kfree_skb_any(skb);
1067 /* Avoid overhead when no packets have been processed
1068 * happens when called speculatively from start_xmit.
1073 u64_stats_update_begin(&stats->tx_syncp);
1074 stats->tx_bytes += bytes;
1075 stats->tx_packets += packets;
1076 u64_stats_update_end(&stats->tx_syncp);
1079 static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1081 struct virtio_net_hdr_mrg_rxbuf *hdr;
1082 const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1083 struct virtnet_info *vi = sq->vq->vdev->priv;
1085 unsigned hdr_len = vi->hdr_len;
1088 pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1090 can_push = vi->any_header_sg &&
1091 !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1092 !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1093 /* Even if we can, don't push here yet as this would skew
1094 * csum_start offset below. */
1096 hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1098 hdr = skb_vnet_hdr(skb);
1100 if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1101 virtio_is_little_endian(vi->vdev), false))
1104 if (vi->mergeable_rx_bufs)
1105 hdr->num_buffers = 0;
1107 sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1109 __skb_push(skb, hdr_len);
1110 num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1111 /* Pull header back to avoid skew in tx bytes calculations. */
1112 __skb_pull(skb, hdr_len);
1114 sg_set_buf(sq->sg, hdr, hdr_len);
1115 num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len) + 1;
1117 return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
1120 static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
1122 struct virtnet_info *vi = netdev_priv(dev);
1123 int qnum = skb_get_queue_mapping(skb);
1124 struct send_queue *sq = &vi->sq[qnum];
1126 struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
1127 bool kick = !skb->xmit_more;
1129 /* Free up any pending old buffers before queueing new ones. */
1130 free_old_xmit_skbs(sq);
1132 /* timestamp packet in software */
1133 skb_tx_timestamp(skb);
1135 /* Try to transmit */
1136 err = xmit_skb(sq, skb);
1138 /* This should not happen! */
1139 if (unlikely(err)) {
1140 dev->stats.tx_fifo_errors++;
1141 if (net_ratelimit())
1143 "Unexpected TXQ (%d) queue failure: %d\n", qnum, err);
1144 dev->stats.tx_dropped++;
1145 dev_kfree_skb_any(skb);
1146 return NETDEV_TX_OK;
1149 /* Don't wait up for transmitted skbs to be freed. */
1153 /* If running out of space, stop queue to avoid getting packets that we
1154 * are then unable to transmit.
1155 * An alternative would be to force queuing layer to requeue the skb by
1156 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
1157 * returned in a normal path of operation: it means that driver is not
1158 * maintaining the TX queue stop/start state properly, and causes
1159 * the stack to do a non-trivial amount of useless work.
1160 * Since most packets only take 1 or 2 ring slots, stopping the queue
1161 * early means 16 slots are typically wasted.
1163 if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1164 netif_stop_subqueue(dev, qnum);
1165 if (unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
1166 /* More just got used, free them then recheck. */
1167 free_old_xmit_skbs(sq);
1168 if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1169 netif_start_subqueue(dev, qnum);
1170 virtqueue_disable_cb(sq->vq);
1175 if (kick || netif_xmit_stopped(txq))
1176 virtqueue_kick(sq->vq);
1178 return NETDEV_TX_OK;
1182 * Send command via the control virtqueue and check status. Commands
1183 * supported by the hypervisor, as indicated by feature bits, should
1184 * never fail unless improperly formatted.
1186 static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1187 struct scatterlist *out)
1189 struct scatterlist *sgs[4], hdr, stat;
1190 unsigned out_num = 0, tmp;
1192 /* Caller should know better */
1193 BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
1195 vi->ctrl_status = ~0;
1196 vi->ctrl_hdr.class = class;
1197 vi->ctrl_hdr.cmd = cmd;
1199 sg_init_one(&hdr, &vi->ctrl_hdr, sizeof(vi->ctrl_hdr));
1200 sgs[out_num++] = &hdr;
1203 sgs[out_num++] = out;
1205 /* Add return status. */
1206 sg_init_one(&stat, &vi->ctrl_status, sizeof(vi->ctrl_status));
1207 sgs[out_num] = &stat;
1209 BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1210 virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
1212 if (unlikely(!virtqueue_kick(vi->cvq)))
1213 return vi->ctrl_status == VIRTIO_NET_OK;
1215 /* Spin for a response, the kick causes an ioport write, trapping
1216 * into the hypervisor, so the request should be handled immediately.
1218 while (!virtqueue_get_buf(vi->cvq, &tmp) &&
1219 !virtqueue_is_broken(vi->cvq))
1222 return vi->ctrl_status == VIRTIO_NET_OK;
1225 static int virtnet_set_mac_address(struct net_device *dev, void *p)
1227 struct virtnet_info *vi = netdev_priv(dev);
1228 struct virtio_device *vdev = vi->vdev;
1230 struct sockaddr *addr;
1231 struct scatterlist sg;
1233 addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
1237 ret = eth_prepare_mac_addr_change(dev, addr);
1241 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
1242 sg_init_one(&sg, addr->sa_data, dev->addr_len);
1243 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1244 VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
1245 dev_warn(&vdev->dev,
1246 "Failed to set mac address by vq command.\n");
1250 } else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
1251 !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1254 /* Naturally, this has an atomicity problem. */
1255 for (i = 0; i < dev->addr_len; i++)
1256 virtio_cwrite8(vdev,
1257 offsetof(struct virtio_net_config, mac) +
1258 i, addr->sa_data[i]);
1261 eth_commit_mac_addr_change(dev, p);
1269 static void virtnet_stats(struct net_device *dev,
1270 struct rtnl_link_stats64 *tot)
1272 struct virtnet_info *vi = netdev_priv(dev);
1276 for_each_possible_cpu(cpu) {
1277 struct virtnet_stats *stats = per_cpu_ptr(vi->stats, cpu);
1278 u64 tpackets, tbytes, rpackets, rbytes;
1281 start = u64_stats_fetch_begin_irq(&stats->tx_syncp);
1282 tpackets = stats->tx_packets;
1283 tbytes = stats->tx_bytes;
1284 } while (u64_stats_fetch_retry_irq(&stats->tx_syncp, start));
1287 start = u64_stats_fetch_begin_irq(&stats->rx_syncp);
1288 rpackets = stats->rx_packets;
1289 rbytes = stats->rx_bytes;
1290 } while (u64_stats_fetch_retry_irq(&stats->rx_syncp, start));
1292 tot->rx_packets += rpackets;
1293 tot->tx_packets += tpackets;
1294 tot->rx_bytes += rbytes;
1295 tot->tx_bytes += tbytes;
1298 tot->tx_dropped = dev->stats.tx_dropped;
1299 tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
1300 tot->rx_dropped = dev->stats.rx_dropped;
1301 tot->rx_length_errors = dev->stats.rx_length_errors;
1302 tot->rx_frame_errors = dev->stats.rx_frame_errors;
1305 #ifdef CONFIG_NET_POLL_CONTROLLER
1306 static void virtnet_netpoll(struct net_device *dev)
1308 struct virtnet_info *vi = netdev_priv(dev);
1311 for (i = 0; i < vi->curr_queue_pairs; i++)
1312 napi_schedule(&vi->rq[i].napi);
1316 static void virtnet_ack_link_announce(struct virtnet_info *vi)
1319 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
1320 VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
1321 dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
1325 static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1327 struct scatterlist sg;
1328 struct net_device *dev = vi->dev;
1330 if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
1333 vi->ctrl_mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
1334 sg_init_one(&sg, &vi->ctrl_mq, sizeof(vi->ctrl_mq));
1336 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
1337 VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
1338 dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
1342 vi->curr_queue_pairs = queue_pairs;
1343 /* virtnet_open() will refill when device is going to up. */
1344 if (dev->flags & IFF_UP)
1345 schedule_delayed_work(&vi->refill, 0);
1351 static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1356 err = _virtnet_set_queues(vi, queue_pairs);
1361 static int virtnet_close(struct net_device *dev)
1363 struct virtnet_info *vi = netdev_priv(dev);
1366 /* Make sure refill_work doesn't re-enable napi! */
1367 cancel_delayed_work_sync(&vi->refill);
1369 for (i = 0; i < vi->max_queue_pairs; i++)
1370 napi_disable(&vi->rq[i].napi);
1375 static void virtnet_set_rx_mode(struct net_device *dev)
1377 struct virtnet_info *vi = netdev_priv(dev);
1378 struct scatterlist sg[2];
1379 struct virtio_net_ctrl_mac *mac_data;
1380 struct netdev_hw_addr *ha;
1386 /* We can't dynamically set ndo_set_rx_mode, so return gracefully */
1387 if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
1390 vi->ctrl_promisc = ((dev->flags & IFF_PROMISC) != 0);
1391 vi->ctrl_allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
1393 sg_init_one(sg, &vi->ctrl_promisc, sizeof(vi->ctrl_promisc));
1395 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1396 VIRTIO_NET_CTRL_RX_PROMISC, sg))
1397 dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
1398 vi->ctrl_promisc ? "en" : "dis");
1400 sg_init_one(sg, &vi->ctrl_allmulti, sizeof(vi->ctrl_allmulti));
1402 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1403 VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
1404 dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
1405 vi->ctrl_allmulti ? "en" : "dis");
1407 uc_count = netdev_uc_count(dev);
1408 mc_count = netdev_mc_count(dev);
1409 /* MAC filter - use one buffer for both lists */
1410 buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
1411 (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
1416 sg_init_table(sg, 2);
1418 /* Store the unicast list and count in the front of the buffer */
1419 mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
1421 netdev_for_each_uc_addr(ha, dev)
1422 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1424 sg_set_buf(&sg[0], mac_data,
1425 sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
1427 /* multicast list and count fill the end */
1428 mac_data = (void *)&mac_data->macs[uc_count][0];
1430 mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
1432 netdev_for_each_mc_addr(ha, dev)
1433 memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1435 sg_set_buf(&sg[1], mac_data,
1436 sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
1438 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1439 VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
1440 dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
1445 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
1446 __be16 proto, u16 vid)
1448 struct virtnet_info *vi = netdev_priv(dev);
1449 struct scatterlist sg;
1452 sg_init_one(&sg, &vi->ctrl_vid, sizeof(vi->ctrl_vid));
1454 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1455 VIRTIO_NET_CTRL_VLAN_ADD, &sg))
1456 dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
1460 static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
1461 __be16 proto, u16 vid)
1463 struct virtnet_info *vi = netdev_priv(dev);
1464 struct scatterlist sg;
1467 sg_init_one(&sg, &vi->ctrl_vid, sizeof(vi->ctrl_vid));
1469 if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1470 VIRTIO_NET_CTRL_VLAN_DEL, &sg))
1471 dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
1475 static void virtnet_clean_affinity(struct virtnet_info *vi, long hcpu)
1479 if (vi->affinity_hint_set) {
1480 for (i = 0; i < vi->max_queue_pairs; i++) {
1481 virtqueue_set_affinity(vi->rq[i].vq, -1);
1482 virtqueue_set_affinity(vi->sq[i].vq, -1);
1485 vi->affinity_hint_set = false;
1489 static void virtnet_set_affinity(struct virtnet_info *vi)
1494 /* In multiqueue mode, when the number of cpu is equal to the number of
1495 * queue pairs, we let the queue pairs to be private to one cpu by
1496 * setting the affinity hint to eliminate the contention.
1498 if (vi->curr_queue_pairs == 1 ||
1499 vi->max_queue_pairs != num_online_cpus()) {
1500 virtnet_clean_affinity(vi, -1);
1505 for_each_online_cpu(cpu) {
1506 virtqueue_set_affinity(vi->rq[i].vq, cpu);
1507 virtqueue_set_affinity(vi->sq[i].vq, cpu);
1508 netif_set_xps_queue(vi->dev, cpumask_of(cpu), i);
1512 vi->affinity_hint_set = true;
1515 static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
1517 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1519 virtnet_set_affinity(vi);
1523 static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
1525 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1527 virtnet_set_affinity(vi);
1531 static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
1533 struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
1536 virtnet_clean_affinity(vi, cpu);
1540 static enum cpuhp_state virtionet_online;
1542 static int virtnet_cpu_notif_add(struct virtnet_info *vi)
1546 ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
1549 ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
1553 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
1557 static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
1559 cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
1560 cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
1564 static void virtnet_get_ringparam(struct net_device *dev,
1565 struct ethtool_ringparam *ring)
1567 struct virtnet_info *vi = netdev_priv(dev);
1569 ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
1570 ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
1571 ring->rx_pending = ring->rx_max_pending;
1572 ring->tx_pending = ring->tx_max_pending;
1576 static void virtnet_get_drvinfo(struct net_device *dev,
1577 struct ethtool_drvinfo *info)
1579 struct virtnet_info *vi = netdev_priv(dev);
1580 struct virtio_device *vdev = vi->vdev;
1582 strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
1583 strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
1584 strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
1588 /* TODO: Eliminate OOO packets during switching */
1589 static int virtnet_set_channels(struct net_device *dev,
1590 struct ethtool_channels *channels)
1592 struct virtnet_info *vi = netdev_priv(dev);
1593 u16 queue_pairs = channels->combined_count;
1596 /* We don't support separate rx/tx channels.
1597 * We don't allow setting 'other' channels.
1599 if (channels->rx_count || channels->tx_count || channels->other_count)
1602 if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
1605 /* For now we don't support modifying channels while XDP is loaded
1606 * also when XDP is loaded all RX queues have XDP programs so we only
1607 * need to check a single RX queue.
1609 if (vi->rq[0].xdp_prog)
1613 err = _virtnet_set_queues(vi, queue_pairs);
1615 netif_set_real_num_tx_queues(dev, queue_pairs);
1616 netif_set_real_num_rx_queues(dev, queue_pairs);
1618 virtnet_set_affinity(vi);
1625 static void virtnet_get_channels(struct net_device *dev,
1626 struct ethtool_channels *channels)
1628 struct virtnet_info *vi = netdev_priv(dev);
1630 channels->combined_count = vi->curr_queue_pairs;
1631 channels->max_combined = vi->max_queue_pairs;
1632 channels->max_other = 0;
1633 channels->rx_count = 0;
1634 channels->tx_count = 0;
1635 channels->other_count = 0;
1638 /* Check if the user is trying to change anything besides speed/duplex */
1639 static bool virtnet_validate_ethtool_cmd(const struct ethtool_cmd *cmd)
1641 struct ethtool_cmd diff1 = *cmd;
1642 struct ethtool_cmd diff2 = {};
1644 /* cmd is always set so we need to clear it, validate the port type
1645 * and also without autonegotiation we can ignore advertising
1647 ethtool_cmd_speed_set(&diff1, 0);
1648 diff2.port = PORT_OTHER;
1649 diff1.advertising = 0;
1653 return !memcmp(&diff1, &diff2, sizeof(diff1));
1656 static int virtnet_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1658 struct virtnet_info *vi = netdev_priv(dev);
1661 speed = ethtool_cmd_speed(cmd);
1662 /* don't allow custom speed and duplex */
1663 if (!ethtool_validate_speed(speed) ||
1664 !ethtool_validate_duplex(cmd->duplex) ||
1665 !virtnet_validate_ethtool_cmd(cmd))
1668 vi->duplex = cmd->duplex;
1673 static int virtnet_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
1675 struct virtnet_info *vi = netdev_priv(dev);
1677 ethtool_cmd_speed_set(cmd, vi->speed);
1678 cmd->duplex = vi->duplex;
1679 cmd->port = PORT_OTHER;
1684 static void virtnet_init_settings(struct net_device *dev)
1686 struct virtnet_info *vi = netdev_priv(dev);
1688 vi->speed = SPEED_UNKNOWN;
1689 vi->duplex = DUPLEX_UNKNOWN;
1692 static const struct ethtool_ops virtnet_ethtool_ops = {
1693 .get_drvinfo = virtnet_get_drvinfo,
1694 .get_link = ethtool_op_get_link,
1695 .get_ringparam = virtnet_get_ringparam,
1696 .set_channels = virtnet_set_channels,
1697 .get_channels = virtnet_get_channels,
1698 .get_ts_info = ethtool_op_get_ts_info,
1699 .get_settings = virtnet_get_settings,
1700 .set_settings = virtnet_set_settings,
1703 static void virtnet_freeze_down(struct virtio_device *vdev)
1705 struct virtnet_info *vi = vdev->priv;
1708 /* Make sure no work handler is accessing the device */
1709 flush_work(&vi->config_work);
1711 netif_device_detach(vi->dev);
1712 cancel_delayed_work_sync(&vi->refill);
1714 if (netif_running(vi->dev)) {
1715 for (i = 0; i < vi->max_queue_pairs; i++)
1716 napi_disable(&vi->rq[i].napi);
1720 static int init_vqs(struct virtnet_info *vi);
1721 static void _remove_vq_common(struct virtnet_info *vi);
1723 static int virtnet_restore_up(struct virtio_device *vdev)
1725 struct virtnet_info *vi = vdev->priv;
1732 virtio_device_ready(vdev);
1734 if (netif_running(vi->dev)) {
1735 for (i = 0; i < vi->curr_queue_pairs; i++)
1736 if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1737 schedule_delayed_work(&vi->refill, 0);
1739 for (i = 0; i < vi->max_queue_pairs; i++)
1740 virtnet_napi_enable(&vi->rq[i]);
1743 netif_device_attach(vi->dev);
1747 static int virtnet_reset(struct virtnet_info *vi, int curr_qp, int xdp_qp)
1749 struct virtio_device *dev = vi->vdev;
1752 virtio_config_disable(dev);
1753 dev->failed = dev->config->get_status(dev) & VIRTIO_CONFIG_S_FAILED;
1754 virtnet_freeze_down(dev);
1755 _remove_vq_common(vi);
1757 dev->config->reset(dev);
1758 virtio_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE);
1759 virtio_add_status(dev, VIRTIO_CONFIG_S_DRIVER);
1761 ret = virtio_finalize_features(dev);
1765 vi->xdp_queue_pairs = xdp_qp;
1766 ret = virtnet_restore_up(dev);
1769 ret = _virtnet_set_queues(vi, curr_qp);
1773 virtio_add_status(dev, VIRTIO_CONFIG_S_DRIVER_OK);
1774 virtio_config_enable(dev);
1777 virtio_add_status(dev, VIRTIO_CONFIG_S_FAILED);
1781 static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog)
1783 unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
1784 struct virtnet_info *vi = netdev_priv(dev);
1785 struct bpf_prog *old_prog;
1786 u16 xdp_qp = 0, curr_qp;
1789 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
1790 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
1791 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
1792 virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO)) {
1793 netdev_warn(dev, "can't set XDP while host is implementing LRO, disable LRO first\n");
1797 if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
1798 netdev_warn(dev, "XDP expects header/data in single page, any_header_sg required\n");
1802 if (dev->mtu > max_sz) {
1803 netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
1807 curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
1809 xdp_qp = nr_cpu_ids;
1811 /* XDP requires extra queues for XDP_TX */
1812 if (curr_qp + xdp_qp > vi->max_queue_pairs) {
1813 netdev_warn(dev, "request %i queues but max is %i\n",
1814 curr_qp + xdp_qp, vi->max_queue_pairs);
1819 prog = bpf_prog_add(prog, vi->max_queue_pairs - 1);
1821 return PTR_ERR(prog);
1824 /* Changing the headroom in buffers is a disruptive operation because
1825 * existing buffers must be flushed and reallocated. This will happen
1826 * when a xdp program is initially added or xdp is disabled by removing
1827 * the xdp program resulting in number of XDP queues changing.
1829 if (vi->xdp_queue_pairs != xdp_qp) {
1830 err = virtnet_reset(vi, curr_qp + xdp_qp, xdp_qp);
1832 dev_warn(&dev->dev, "XDP reset failure.\n");
1833 goto virtio_reset_err;
1837 netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
1839 for (i = 0; i < vi->max_queue_pairs; i++) {
1840 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
1841 rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
1843 bpf_prog_put(old_prog);
1849 /* On reset error do our best to unwind XDP changes inflight and return
1850 * error up to user space for resolution. The underlying reset hung on
1851 * us so not much we can do here.
1854 bpf_prog_sub(prog, vi->max_queue_pairs - 1);
1858 static bool virtnet_xdp_query(struct net_device *dev)
1860 struct virtnet_info *vi = netdev_priv(dev);
1863 for (i = 0; i < vi->max_queue_pairs; i++) {
1864 if (vi->rq[i].xdp_prog)
1870 static int virtnet_xdp(struct net_device *dev, struct netdev_xdp *xdp)
1872 switch (xdp->command) {
1873 case XDP_SETUP_PROG:
1874 return virtnet_xdp_set(dev, xdp->prog);
1875 case XDP_QUERY_PROG:
1876 xdp->prog_attached = virtnet_xdp_query(dev);
1883 static const struct net_device_ops virtnet_netdev = {
1884 .ndo_open = virtnet_open,
1885 .ndo_stop = virtnet_close,
1886 .ndo_start_xmit = start_xmit,
1887 .ndo_validate_addr = eth_validate_addr,
1888 .ndo_set_mac_address = virtnet_set_mac_address,
1889 .ndo_set_rx_mode = virtnet_set_rx_mode,
1890 .ndo_get_stats64 = virtnet_stats,
1891 .ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
1892 .ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
1893 #ifdef CONFIG_NET_POLL_CONTROLLER
1894 .ndo_poll_controller = virtnet_netpoll,
1896 .ndo_xdp = virtnet_xdp,
1899 static void virtnet_config_changed_work(struct work_struct *work)
1901 struct virtnet_info *vi =
1902 container_of(work, struct virtnet_info, config_work);
1905 if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
1906 struct virtio_net_config, status, &v) < 0)
1909 if (v & VIRTIO_NET_S_ANNOUNCE) {
1910 netdev_notify_peers(vi->dev);
1911 virtnet_ack_link_announce(vi);
1914 /* Ignore unknown (future) status bits */
1915 v &= VIRTIO_NET_S_LINK_UP;
1917 if (vi->status == v)
1922 if (vi->status & VIRTIO_NET_S_LINK_UP) {
1923 netif_carrier_on(vi->dev);
1924 netif_tx_wake_all_queues(vi->dev);
1926 netif_carrier_off(vi->dev);
1927 netif_tx_stop_all_queues(vi->dev);
1931 static void virtnet_config_changed(struct virtio_device *vdev)
1933 struct virtnet_info *vi = vdev->priv;
1935 schedule_work(&vi->config_work);
1938 static void virtnet_free_queues(struct virtnet_info *vi)
1942 for (i = 0; i < vi->max_queue_pairs; i++) {
1943 napi_hash_del(&vi->rq[i].napi);
1944 netif_napi_del(&vi->rq[i].napi);
1947 /* We called napi_hash_del() before netif_napi_del(),
1948 * we need to respect an RCU grace period before freeing vi->rq
1956 static void _free_receive_bufs(struct virtnet_info *vi)
1958 struct bpf_prog *old_prog;
1961 for (i = 0; i < vi->max_queue_pairs; i++) {
1962 while (vi->rq[i].pages)
1963 __free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
1965 old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
1966 RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
1968 bpf_prog_put(old_prog);
1972 static void free_receive_bufs(struct virtnet_info *vi)
1975 _free_receive_bufs(vi);
1979 static void free_receive_page_frags(struct virtnet_info *vi)
1982 for (i = 0; i < vi->max_queue_pairs; i++)
1983 if (vi->rq[i].alloc_frag.page)
1984 put_page(vi->rq[i].alloc_frag.page);
1987 static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
1989 if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
1991 else if (q < vi->curr_queue_pairs)
1997 static void free_unused_bufs(struct virtnet_info *vi)
2002 for (i = 0; i < vi->max_queue_pairs; i++) {
2003 struct virtqueue *vq = vi->sq[i].vq;
2004 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2005 if (!is_xdp_raw_buffer_queue(vi, i))
2008 put_page(virt_to_head_page(buf));
2012 for (i = 0; i < vi->max_queue_pairs; i++) {
2013 struct virtqueue *vq = vi->rq[i].vq;
2015 while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2016 if (vi->mergeable_rx_bufs) {
2017 unsigned long ctx = (unsigned long)buf;
2018 void *base = mergeable_ctx_to_buf_address(ctx);
2019 put_page(virt_to_head_page(base));
2020 } else if (vi->big_packets) {
2021 give_pages(&vi->rq[i], buf);
2023 put_page(virt_to_head_page(buf));
2029 static void virtnet_del_vqs(struct virtnet_info *vi)
2031 struct virtio_device *vdev = vi->vdev;
2033 virtnet_clean_affinity(vi, -1);
2035 vdev->config->del_vqs(vdev);
2037 virtnet_free_queues(vi);
2040 static int virtnet_find_vqs(struct virtnet_info *vi)
2042 vq_callback_t **callbacks;
2043 struct virtqueue **vqs;
2048 /* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
2049 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
2050 * possible control vq.
2052 total_vqs = vi->max_queue_pairs * 2 +
2053 virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
2055 /* Allocate space for find_vqs parameters */
2056 vqs = kzalloc(total_vqs * sizeof(*vqs), GFP_KERNEL);
2059 callbacks = kmalloc(total_vqs * sizeof(*callbacks), GFP_KERNEL);
2062 names = kmalloc(total_vqs * sizeof(*names), GFP_KERNEL);
2066 /* Parameters for control virtqueue, if any */
2068 callbacks[total_vqs - 1] = NULL;
2069 names[total_vqs - 1] = "control";
2072 /* Allocate/initialize parameters for send/receive virtqueues */
2073 for (i = 0; i < vi->max_queue_pairs; i++) {
2074 callbacks[rxq2vq(i)] = skb_recv_done;
2075 callbacks[txq2vq(i)] = skb_xmit_done;
2076 sprintf(vi->rq[i].name, "input.%d", i);
2077 sprintf(vi->sq[i].name, "output.%d", i);
2078 names[rxq2vq(i)] = vi->rq[i].name;
2079 names[txq2vq(i)] = vi->sq[i].name;
2082 ret = vi->vdev->config->find_vqs(vi->vdev, total_vqs, vqs, callbacks,
2088 vi->cvq = vqs[total_vqs - 1];
2089 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
2090 vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
2093 for (i = 0; i < vi->max_queue_pairs; i++) {
2094 vi->rq[i].vq = vqs[rxq2vq(i)];
2095 vi->sq[i].vq = vqs[txq2vq(i)];
2114 static int virtnet_alloc_queues(struct virtnet_info *vi)
2118 vi->sq = kzalloc(sizeof(*vi->sq) * vi->max_queue_pairs, GFP_KERNEL);
2121 vi->rq = kzalloc(sizeof(*vi->rq) * vi->max_queue_pairs, GFP_KERNEL);
2125 INIT_DELAYED_WORK(&vi->refill, refill_work);
2126 for (i = 0; i < vi->max_queue_pairs; i++) {
2127 vi->rq[i].pages = NULL;
2128 netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
2131 sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
2132 ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
2133 sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
2144 static int init_vqs(struct virtnet_info *vi)
2148 /* Allocate send & receive queues */
2149 ret = virtnet_alloc_queues(vi);
2153 ret = virtnet_find_vqs(vi);
2158 virtnet_set_affinity(vi);
2164 virtnet_free_queues(vi);
2170 static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
2171 struct rx_queue_attribute *attribute, char *buf)
2173 struct virtnet_info *vi = netdev_priv(queue->dev);
2174 unsigned int queue_index = get_netdev_rx_queue_index(queue);
2175 struct ewma_pkt_len *avg;
2177 BUG_ON(queue_index >= vi->max_queue_pairs);
2178 avg = &vi->rq[queue_index].mrg_avg_pkt_len;
2179 return sprintf(buf, "%u\n", get_mergeable_buf_len(avg));
2182 static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
2183 __ATTR_RO(mergeable_rx_buffer_size);
2185 static struct attribute *virtio_net_mrg_rx_attrs[] = {
2186 &mergeable_rx_buffer_size_attribute.attr,
2190 static const struct attribute_group virtio_net_mrg_rx_group = {
2191 .name = "virtio_net",
2192 .attrs = virtio_net_mrg_rx_attrs
2196 static bool virtnet_fail_on_feature(struct virtio_device *vdev,
2198 const char *fname, const char *dname)
2200 if (!virtio_has_feature(vdev, fbit))
2203 dev_err(&vdev->dev, "device advertises feature %s but not %s",
2209 #define VIRTNET_FAIL_ON(vdev, fbit, dbit) \
2210 virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
2212 static bool virtnet_validate_features(struct virtio_device *vdev)
2214 if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
2215 (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
2216 "VIRTIO_NET_F_CTRL_VQ") ||
2217 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
2218 "VIRTIO_NET_F_CTRL_VQ") ||
2219 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
2220 "VIRTIO_NET_F_CTRL_VQ") ||
2221 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
2222 VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
2223 "VIRTIO_NET_F_CTRL_VQ"))) {
2230 #define MIN_MTU ETH_MIN_MTU
2231 #define MAX_MTU ETH_MAX_MTU
2233 static int virtnet_probe(struct virtio_device *vdev)
2236 struct net_device *dev;
2237 struct virtnet_info *vi;
2238 u16 max_queue_pairs;
2241 if (!vdev->config->get) {
2242 dev_err(&vdev->dev, "%s failure: config access disabled\n",
2247 if (!virtnet_validate_features(vdev))
2250 /* Find if host supports multiqueue virtio_net device */
2251 err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
2252 struct virtio_net_config,
2253 max_virtqueue_pairs, &max_queue_pairs);
2255 /* We need at least 2 queue's */
2256 if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
2257 max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
2258 !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
2259 max_queue_pairs = 1;
2261 /* Allocate ourselves a network device with room for our info */
2262 dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
2266 /* Set up network device as normal. */
2267 dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
2268 dev->netdev_ops = &virtnet_netdev;
2269 dev->features = NETIF_F_HIGHDMA;
2271 dev->ethtool_ops = &virtnet_ethtool_ops;
2272 SET_NETDEV_DEV(dev, &vdev->dev);
2274 /* Do we support "hardware" checksums? */
2275 if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
2276 /* This opens up the world of extra features. */
2277 dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
2279 dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
2281 if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
2282 dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
2283 | NETIF_F_TSO_ECN | NETIF_F_TSO6;
2285 /* Individual feature bits: what can host handle? */
2286 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
2287 dev->hw_features |= NETIF_F_TSO;
2288 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
2289 dev->hw_features |= NETIF_F_TSO6;
2290 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
2291 dev->hw_features |= NETIF_F_TSO_ECN;
2292 if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
2293 dev->hw_features |= NETIF_F_UFO;
2295 dev->features |= NETIF_F_GSO_ROBUST;
2298 dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
2299 /* (!csum && gso) case will be fixed by register_netdev() */
2301 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
2302 dev->features |= NETIF_F_RXCSUM;
2304 dev->vlan_features = dev->features;
2306 /* MTU range: 68 - 65535 */
2307 dev->min_mtu = MIN_MTU;
2308 dev->max_mtu = MAX_MTU;
2310 /* Configuration may specify what MAC to use. Otherwise random. */
2311 if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
2312 virtio_cread_bytes(vdev,
2313 offsetof(struct virtio_net_config, mac),
2314 dev->dev_addr, dev->addr_len);
2316 eth_hw_addr_random(dev);
2318 /* Set up our device-specific information */
2319 vi = netdev_priv(dev);
2323 vi->stats = alloc_percpu(struct virtnet_stats);
2325 if (vi->stats == NULL)
2328 for_each_possible_cpu(i) {
2329 struct virtnet_stats *virtnet_stats;
2330 virtnet_stats = per_cpu_ptr(vi->stats, i);
2331 u64_stats_init(&virtnet_stats->tx_syncp);
2332 u64_stats_init(&virtnet_stats->rx_syncp);
2335 INIT_WORK(&vi->config_work, virtnet_config_changed_work);
2337 /* If we can receive ANY GSO packets, we must allocate large ones. */
2338 if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
2339 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
2340 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
2341 virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
2342 vi->big_packets = true;
2344 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
2345 vi->mergeable_rx_bufs = true;
2347 if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
2348 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
2349 vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2351 vi->hdr_len = sizeof(struct virtio_net_hdr);
2353 if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
2354 virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
2355 vi->any_header_sg = true;
2357 if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
2360 if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
2361 mtu = virtio_cread16(vdev,
2362 offsetof(struct virtio_net_config,
2364 if (mtu < dev->min_mtu) {
2365 __virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
2372 if (vi->any_header_sg)
2373 dev->needed_headroom = vi->hdr_len;
2375 /* Enable multiqueue by default */
2376 if (num_online_cpus() >= max_queue_pairs)
2377 vi->curr_queue_pairs = max_queue_pairs;
2379 vi->curr_queue_pairs = num_online_cpus();
2380 vi->max_queue_pairs = max_queue_pairs;
2382 /* Allocate/initialize the rx/tx queues, and invoke find_vqs */
2388 if (vi->mergeable_rx_bufs)
2389 dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
2391 netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
2392 netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
2394 virtnet_init_settings(dev);
2396 err = register_netdev(dev);
2398 pr_debug("virtio_net: registering device failed\n");
2402 virtio_device_ready(vdev);
2404 err = virtnet_cpu_notif_add(vi);
2406 pr_debug("virtio_net: registering cpu notifier failed\n");
2407 goto free_unregister_netdev;
2410 virtnet_set_queues(vi, vi->curr_queue_pairs);
2412 /* Assume link up if device can't report link status,
2413 otherwise get link status from config. */
2414 if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
2415 netif_carrier_off(dev);
2416 schedule_work(&vi->config_work);
2418 vi->status = VIRTIO_NET_S_LINK_UP;
2419 netif_carrier_on(dev);
2422 pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
2423 dev->name, max_queue_pairs);
2427 free_unregister_netdev:
2428 vi->vdev->config->reset(vdev);
2430 unregister_netdev(dev);
2432 cancel_delayed_work_sync(&vi->refill);
2433 free_receive_page_frags(vi);
2434 virtnet_del_vqs(vi);
2436 free_percpu(vi->stats);
2442 static void _remove_vq_common(struct virtnet_info *vi)
2444 vi->vdev->config->reset(vi->vdev);
2445 free_unused_bufs(vi);
2446 _free_receive_bufs(vi);
2447 free_receive_page_frags(vi);
2448 virtnet_del_vqs(vi);
2451 static void remove_vq_common(struct virtnet_info *vi)
2453 vi->vdev->config->reset(vi->vdev);
2455 /* Free unused buffers in both send and recv, if any. */
2456 free_unused_bufs(vi);
2458 free_receive_bufs(vi);
2460 free_receive_page_frags(vi);
2462 virtnet_del_vqs(vi);
2465 static void virtnet_remove(struct virtio_device *vdev)
2467 struct virtnet_info *vi = vdev->priv;
2469 virtnet_cpu_notif_remove(vi);
2471 /* Make sure no work handler is accessing the device. */
2472 flush_work(&vi->config_work);
2474 unregister_netdev(vi->dev);
2476 remove_vq_common(vi);
2478 free_percpu(vi->stats);
2479 free_netdev(vi->dev);
2482 #ifdef CONFIG_PM_SLEEP
2483 static int virtnet_freeze(struct virtio_device *vdev)
2485 struct virtnet_info *vi = vdev->priv;
2487 virtnet_cpu_notif_remove(vi);
2488 virtnet_freeze_down(vdev);
2489 remove_vq_common(vi);
2494 static int virtnet_restore(struct virtio_device *vdev)
2496 struct virtnet_info *vi = vdev->priv;
2499 err = virtnet_restore_up(vdev);
2502 virtnet_set_queues(vi, vi->curr_queue_pairs);
2504 err = virtnet_cpu_notif_add(vi);
2512 static struct virtio_device_id id_table[] = {
2513 { VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
2517 #define VIRTNET_FEATURES \
2518 VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
2520 VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
2521 VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
2522 VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
2523 VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
2524 VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
2525 VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
2526 VIRTIO_NET_F_CTRL_MAC_ADDR, \
2529 static unsigned int features[] = {
2533 static unsigned int features_legacy[] = {
2536 VIRTIO_F_ANY_LAYOUT,
2539 static struct virtio_driver virtio_net_driver = {
2540 .feature_table = features,
2541 .feature_table_size = ARRAY_SIZE(features),
2542 .feature_table_legacy = features_legacy,
2543 .feature_table_size_legacy = ARRAY_SIZE(features_legacy),
2544 .driver.name = KBUILD_MODNAME,
2545 .driver.owner = THIS_MODULE,
2546 .id_table = id_table,
2547 .probe = virtnet_probe,
2548 .remove = virtnet_remove,
2549 .config_changed = virtnet_config_changed,
2550 #ifdef CONFIG_PM_SLEEP
2551 .freeze = virtnet_freeze,
2552 .restore = virtnet_restore,
2556 static __init int virtio_net_driver_init(void)
2560 ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
2562 virtnet_cpu_down_prep);
2565 virtionet_online = ret;
2566 ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
2567 NULL, virtnet_cpu_dead);
2571 ret = register_virtio_driver(&virtio_net_driver);
2576 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
2578 cpuhp_remove_multi_state(virtionet_online);
2582 module_init(virtio_net_driver_init);
2584 static __exit void virtio_net_driver_exit(void)
2586 cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
2587 cpuhp_remove_multi_state(virtionet_online);
2588 unregister_virtio_driver(&virtio_net_driver);
2590 module_exit(virtio_net_driver_exit);
2592 MODULE_DEVICE_TABLE(virtio, id_table);
2593 MODULE_DESCRIPTION("Virtio network driver");
2594 MODULE_LICENSE("GPL");