xref: /openbmc/linux/drivers/net/virtio_net.c (revision df561f6688fef775baa341a0f5d960becd248b11)
11ccea77eSThomas Gleixner // SPDX-License-Identifier: GPL-2.0-or-later
248925e37SRusty Russell /* A network driver using virtio.
3296f96fcSRusty Russell  *
4296f96fcSRusty Russell  * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
5296f96fcSRusty Russell  */
6296f96fcSRusty Russell //#define DEBUG
7296f96fcSRusty Russell #include <linux/netdevice.h>
8296f96fcSRusty Russell #include <linux/etherdevice.h>
9a9ea3fc6SHerbert Xu #include <linux/ethtool.h>
10296f96fcSRusty Russell #include <linux/module.h>
11296f96fcSRusty Russell #include <linux/virtio.h>
12296f96fcSRusty Russell #include <linux/virtio_net.h>
13f600b690SJohn Fastabend #include <linux/bpf.h>
14a67edbf4SDaniel Borkmann #include <linux/bpf_trace.h>
15296f96fcSRusty Russell #include <linux/scatterlist.h>
16e918085aSAlex Williamson #include <linux/if_vlan.h>
175a0e3ad6STejun Heo #include <linux/slab.h>
188de4b2f3SWanlong Gao #include <linux/cpu.h>
19ab7db917SMichael Dalton #include <linux/average.h>
20186b3c99SJason Wang #include <linux/filter.h>
212ca653d6SCaleb Raitto #include <linux/kernel.h>
22d85b758fSMichael S. Tsirkin #include <net/route.h>
23754b8a21SJesper Dangaard Brouer #include <net/xdp.h>
24ba5e4426SSridhar Samudrala #include <net/net_failover.h>
25296f96fcSRusty Russell 
26d34710e3SAmerigo Wang static int napi_weight = NAPI_POLL_WEIGHT;
276c0cd7c0SDor Laor module_param(napi_weight, int, 0444);
286c0cd7c0SDor Laor 
2931c03aefSWillem de Bruijn static bool csum = true, gso = true, napi_tx = true;
3034a48579SRusty Russell module_param(csum, bool, 0444);
3134a48579SRusty Russell module_param(gso, bool, 0444);
32b92f1e67SWillem de Bruijn module_param(napi_tx, bool, 0644);
3334a48579SRusty Russell 
34296f96fcSRusty Russell /* FIXME: MTU in config. */
355061de36SMichael Dalton #define GOOD_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
363f2c31d9SMark McLoughlin #define GOOD_COPY_LEN	128
37296f96fcSRusty Russell 
38f6b10209SJason Wang #define VIRTNET_RX_PAD (NET_IP_ALIGN + NET_SKB_PAD)
39f6b10209SJason Wang 
402de2f7f4SJohn Fastabend /* Amount of XDP headroom to prepend to packets for use by xdp_adjust_head */
412de2f7f4SJohn Fastabend #define VIRTIO_XDP_HEADROOM 256
422de2f7f4SJohn Fastabend 
432471c75eSJesper Dangaard Brouer /* Separating two types of XDP xmit */
442471c75eSJesper Dangaard Brouer #define VIRTIO_XDP_TX		BIT(0)
452471c75eSJesper Dangaard Brouer #define VIRTIO_XDP_REDIR	BIT(1)
462471c75eSJesper Dangaard Brouer 
475050471dSToshiaki Makita #define VIRTIO_XDP_FLAG	BIT(0)
485050471dSToshiaki Makita 
495377d758SJohannes Berg /* RX packet size EWMA. The average packet size is used to determine the packet
505377d758SJohannes Berg  * buffer size when refilling RX rings. As the entire RX ring may be refilled
515377d758SJohannes Berg  * at once, the weight is chosen so that the EWMA will be insensitive to short-
525377d758SJohannes Berg  * term, transient changes in packet size.
53ab7db917SMichael Dalton  */
54eb1e011aSJohannes Berg DECLARE_EWMA(pkt_len, 0, 64)
55ab7db917SMichael Dalton 
5666846048SRick Jones #define VIRTNET_DRIVER_VERSION "1.0.0"
572a41f71dSAlex Williamson 
587acd4329SColin Ian King static const unsigned long guest_offloads[] = {
597acd4329SColin Ian King 	VIRTIO_NET_F_GUEST_TSO4,
603f93522fSJason Wang 	VIRTIO_NET_F_GUEST_TSO6,
613f93522fSJason Wang 	VIRTIO_NET_F_GUEST_ECN,
62e59ff2c4SJason Wang 	VIRTIO_NET_F_GUEST_UFO,
63e59ff2c4SJason Wang 	VIRTIO_NET_F_GUEST_CSUM
647acd4329SColin Ian King };
653f93522fSJason Wang 
66d7dfc5cfSToshiaki Makita struct virtnet_stat_desc {
67d7dfc5cfSToshiaki Makita 	char desc[ETH_GSTRING_LEN];
68d7dfc5cfSToshiaki Makita 	size_t offset;
693fa2a1dfSstephen hemminger };
703fa2a1dfSstephen hemminger 
71d7dfc5cfSToshiaki Makita struct virtnet_sq_stats {
72d7dfc5cfSToshiaki Makita 	struct u64_stats_sync syncp;
73d7dfc5cfSToshiaki Makita 	u64 packets;
74d7dfc5cfSToshiaki Makita 	u64 bytes;
755b8f3c8dSToshiaki Makita 	u64 xdp_tx;
765b8f3c8dSToshiaki Makita 	u64 xdp_tx_drops;
77461f03dcSToshiaki Makita 	u64 kicks;
78d7dfc5cfSToshiaki Makita };
79d7dfc5cfSToshiaki Makita 
80d46eeeafSJason Wang struct virtnet_rq_stats {
81d46eeeafSJason Wang 	struct u64_stats_sync syncp;
82d7dfc5cfSToshiaki Makita 	u64 packets;
83d7dfc5cfSToshiaki Makita 	u64 bytes;
842c4a2f7dSToshiaki Makita 	u64 drops;
855b8f3c8dSToshiaki Makita 	u64 xdp_packets;
865b8f3c8dSToshiaki Makita 	u64 xdp_tx;
875b8f3c8dSToshiaki Makita 	u64 xdp_redirects;
885b8f3c8dSToshiaki Makita 	u64 xdp_drops;
89461f03dcSToshiaki Makita 	u64 kicks;
90d7dfc5cfSToshiaki Makita };
91d7dfc5cfSToshiaki Makita 
92d7dfc5cfSToshiaki Makita #define VIRTNET_SQ_STAT(m)	offsetof(struct virtnet_sq_stats, m)
93d46eeeafSJason Wang #define VIRTNET_RQ_STAT(m)	offsetof(struct virtnet_rq_stats, m)
94d7dfc5cfSToshiaki Makita 
95d7dfc5cfSToshiaki Makita static const struct virtnet_stat_desc virtnet_sq_stats_desc[] = {
96d7dfc5cfSToshiaki Makita 	{ "packets",		VIRTNET_SQ_STAT(packets) },
97d7dfc5cfSToshiaki Makita 	{ "bytes",		VIRTNET_SQ_STAT(bytes) },
985b8f3c8dSToshiaki Makita 	{ "xdp_tx",		VIRTNET_SQ_STAT(xdp_tx) },
995b8f3c8dSToshiaki Makita 	{ "xdp_tx_drops",	VIRTNET_SQ_STAT(xdp_tx_drops) },
100461f03dcSToshiaki Makita 	{ "kicks",		VIRTNET_SQ_STAT(kicks) },
101d7dfc5cfSToshiaki Makita };
102d7dfc5cfSToshiaki Makita 
103d7dfc5cfSToshiaki Makita static const struct virtnet_stat_desc virtnet_rq_stats_desc[] = {
104d7dfc5cfSToshiaki Makita 	{ "packets",		VIRTNET_RQ_STAT(packets) },
105d7dfc5cfSToshiaki Makita 	{ "bytes",		VIRTNET_RQ_STAT(bytes) },
1062c4a2f7dSToshiaki Makita 	{ "drops",		VIRTNET_RQ_STAT(drops) },
1075b8f3c8dSToshiaki Makita 	{ "xdp_packets",	VIRTNET_RQ_STAT(xdp_packets) },
1085b8f3c8dSToshiaki Makita 	{ "xdp_tx",		VIRTNET_RQ_STAT(xdp_tx) },
1095b8f3c8dSToshiaki Makita 	{ "xdp_redirects",	VIRTNET_RQ_STAT(xdp_redirects) },
1105b8f3c8dSToshiaki Makita 	{ "xdp_drops",		VIRTNET_RQ_STAT(xdp_drops) },
111461f03dcSToshiaki Makita 	{ "kicks",		VIRTNET_RQ_STAT(kicks) },
112d7dfc5cfSToshiaki Makita };
113d7dfc5cfSToshiaki Makita 
114d7dfc5cfSToshiaki Makita #define VIRTNET_SQ_STATS_LEN	ARRAY_SIZE(virtnet_sq_stats_desc)
115d7dfc5cfSToshiaki Makita #define VIRTNET_RQ_STATS_LEN	ARRAY_SIZE(virtnet_rq_stats_desc)
116d7dfc5cfSToshiaki Makita 
117e9d7417bSJason Wang /* Internal representation of a send virtqueue */
118e9d7417bSJason Wang struct send_queue {
119e9d7417bSJason Wang 	/* Virtqueue associated with this send _queue */
120e9d7417bSJason Wang 	struct virtqueue *vq;
121e9d7417bSJason Wang 
122e9d7417bSJason Wang 	/* TX: fragments + linear part + virtio header */
123e9d7417bSJason Wang 	struct scatterlist sg[MAX_SKB_FRAGS + 2];
124986a4f4dSJason Wang 
125986a4f4dSJason Wang 	/* Name of the send queue: output.$index */
126986a4f4dSJason Wang 	char name[40];
127b92f1e67SWillem de Bruijn 
128d7dfc5cfSToshiaki Makita 	struct virtnet_sq_stats stats;
129d7dfc5cfSToshiaki Makita 
130b92f1e67SWillem de Bruijn 	struct napi_struct napi;
131e9d7417bSJason Wang };
132e9d7417bSJason Wang 
133e9d7417bSJason Wang /* Internal representation of a receive virtqueue */
134e9d7417bSJason Wang struct receive_queue {
135e9d7417bSJason Wang 	/* Virtqueue associated with this receive_queue */
136e9d7417bSJason Wang 	struct virtqueue *vq;
137e9d7417bSJason Wang 
138296f96fcSRusty Russell 	struct napi_struct napi;
139296f96fcSRusty Russell 
140f600b690SJohn Fastabend 	struct bpf_prog __rcu *xdp_prog;
141f600b690SJohn Fastabend 
142d7dfc5cfSToshiaki Makita 	struct virtnet_rq_stats stats;
143d7dfc5cfSToshiaki Makita 
144e9d7417bSJason Wang 	/* Chain pages by the private ptr. */
145e9d7417bSJason Wang 	struct page *pages;
146e9d7417bSJason Wang 
147ab7db917SMichael Dalton 	/* Average packet length for mergeable receive buffers. */
1485377d758SJohannes Berg 	struct ewma_pkt_len mrg_avg_pkt_len;
149ab7db917SMichael Dalton 
150fb51879dSMichael Dalton 	/* Page frag for packet buffer allocation. */
151fb51879dSMichael Dalton 	struct page_frag alloc_frag;
152fb51879dSMichael Dalton 
153e9d7417bSJason Wang 	/* RX: fragments + linear part + virtio header */
154e9d7417bSJason Wang 	struct scatterlist sg[MAX_SKB_FRAGS + 2];
155986a4f4dSJason Wang 
156d85b758fSMichael S. Tsirkin 	/* Min single buffer size for mergeable buffers case. */
157d85b758fSMichael S. Tsirkin 	unsigned int min_buf_len;
158d85b758fSMichael S. Tsirkin 
159986a4f4dSJason Wang 	/* Name of this receive queue: input.$index */
160986a4f4dSJason Wang 	char name[40];
161754b8a21SJesper Dangaard Brouer 
162754b8a21SJesper Dangaard Brouer 	struct xdp_rxq_info xdp_rxq;
163e9d7417bSJason Wang };
164e9d7417bSJason Wang 
16512e57169SMichael S. Tsirkin /* Control VQ buffers: protected by the rtnl lock */
16612e57169SMichael S. Tsirkin struct control_buf {
16712e57169SMichael S. Tsirkin 	struct virtio_net_ctrl_hdr hdr;
16812e57169SMichael S. Tsirkin 	virtio_net_ctrl_ack status;
16912e57169SMichael S. Tsirkin 	struct virtio_net_ctrl_mq mq;
17012e57169SMichael S. Tsirkin 	u8 promisc;
17112e57169SMichael S. Tsirkin 	u8 allmulti;
172d7fad4c8SMichael S. Tsirkin 	__virtio16 vid;
173f4ee703aSMichael S. Tsirkin 	__virtio64 offloads;
17412e57169SMichael S. Tsirkin };
17512e57169SMichael S. Tsirkin 
176e9d7417bSJason Wang struct virtnet_info {
177e9d7417bSJason Wang 	struct virtio_device *vdev;
178e9d7417bSJason Wang 	struct virtqueue *cvq;
179e9d7417bSJason Wang 	struct net_device *dev;
180986a4f4dSJason Wang 	struct send_queue *sq;
181986a4f4dSJason Wang 	struct receive_queue *rq;
182e9d7417bSJason Wang 	unsigned int status;
183e9d7417bSJason Wang 
184986a4f4dSJason Wang 	/* Max # of queue pairs supported by the device */
185986a4f4dSJason Wang 	u16 max_queue_pairs;
186986a4f4dSJason Wang 
187986a4f4dSJason Wang 	/* # of queue pairs currently used by the driver */
188986a4f4dSJason Wang 	u16 curr_queue_pairs;
189986a4f4dSJason Wang 
190672aafd5SJohn Fastabend 	/* # of XDP queue pairs currently used by the driver */
191672aafd5SJohn Fastabend 	u16 xdp_queue_pairs;
192672aafd5SJohn Fastabend 
19397402b96SHerbert Xu 	/* I like... big packets and I cannot lie! */
19497402b96SHerbert Xu 	bool big_packets;
19597402b96SHerbert Xu 
1963f2c31d9SMark McLoughlin 	/* Host will merge rx buffers for big packets (shake it! shake it!) */
1973f2c31d9SMark McLoughlin 	bool mergeable_rx_bufs;
1983f2c31d9SMark McLoughlin 
199986a4f4dSJason Wang 	/* Has control virtqueue */
200986a4f4dSJason Wang 	bool has_cvq;
201986a4f4dSJason Wang 
202e7428e95SMichael S. Tsirkin 	/* Host can handle any s/g split between our header and packet data */
203e7428e95SMichael S. Tsirkin 	bool any_header_sg;
204e7428e95SMichael S. Tsirkin 
205012873d0SMichael S. Tsirkin 	/* Packet virtio header size */
206012873d0SMichael S. Tsirkin 	u8 hdr_len;
207012873d0SMichael S. Tsirkin 
2083161e453SRusty Russell 	/* Work struct for refilling if we run low on memory. */
2093161e453SRusty Russell 	struct delayed_work refill;
2103161e453SRusty Russell 
211586d17c5SJason Wang 	/* Work struct for config space updates */
212586d17c5SJason Wang 	struct work_struct config_work;
213586d17c5SJason Wang 
214986a4f4dSJason Wang 	/* Does the affinity hint is set for virtqueues? */
215986a4f4dSJason Wang 	bool affinity_hint_set;
21647be2479SWanlong Gao 
2178017c279SSebastian Andrzej Siewior 	/* CPU hotplug instances for online & dead */
2188017c279SSebastian Andrzej Siewior 	struct hlist_node node;
2198017c279SSebastian Andrzej Siewior 	struct hlist_node node_dead;
2202ac46030SMichael S. Tsirkin 
22112e57169SMichael S. Tsirkin 	struct control_buf *ctrl;
22216032be5SNikolay Aleksandrov 
22316032be5SNikolay Aleksandrov 	/* Ethtool settings */
22416032be5SNikolay Aleksandrov 	u8 duplex;
22516032be5SNikolay Aleksandrov 	u32 speed;
2263f93522fSJason Wang 
2273f93522fSJason Wang 	unsigned long guest_offloads;
228a02e8964SWillem de Bruijn 	unsigned long guest_offloads_capable;
229ba5e4426SSridhar Samudrala 
230ba5e4426SSridhar Samudrala 	/* failover when STANDBY feature enabled */
231ba5e4426SSridhar Samudrala 	struct failover *failover;
232296f96fcSRusty Russell };
233296f96fcSRusty Russell 
2349ab86bbcSShirley Ma struct padded_vnet_hdr {
235012873d0SMichael S. Tsirkin 	struct virtio_net_hdr_mrg_rxbuf hdr;
2369ab86bbcSShirley Ma 	/*
237012873d0SMichael S. Tsirkin 	 * hdr is in a separate sg buffer, and data sg buffer shares same page
238012873d0SMichael S. Tsirkin 	 * with this header sg. This padding makes next sg 16 byte aligned
239012873d0SMichael S. Tsirkin 	 * after the header.
2409ab86bbcSShirley Ma 	 */
241012873d0SMichael S. Tsirkin 	char padding[4];
2429ab86bbcSShirley Ma };
2439ab86bbcSShirley Ma 
2445050471dSToshiaki Makita static bool is_xdp_frame(void *ptr)
2455050471dSToshiaki Makita {
2465050471dSToshiaki Makita 	return (unsigned long)ptr & VIRTIO_XDP_FLAG;
2475050471dSToshiaki Makita }
2485050471dSToshiaki Makita 
2495050471dSToshiaki Makita static void *xdp_to_ptr(struct xdp_frame *ptr)
2505050471dSToshiaki Makita {
2515050471dSToshiaki Makita 	return (void *)((unsigned long)ptr | VIRTIO_XDP_FLAG);
2525050471dSToshiaki Makita }
2535050471dSToshiaki Makita 
2545050471dSToshiaki Makita static struct xdp_frame *ptr_to_xdp(void *ptr)
2555050471dSToshiaki Makita {
2565050471dSToshiaki Makita 	return (struct xdp_frame *)((unsigned long)ptr & ~VIRTIO_XDP_FLAG);
2575050471dSToshiaki Makita }
2585050471dSToshiaki Makita 
259986a4f4dSJason Wang /* Converting between virtqueue no. and kernel tx/rx queue no.
260986a4f4dSJason Wang  * 0:rx0 1:tx0 2:rx1 3:tx1 ... 2N:rxN 2N+1:txN 2N+2:cvq
261986a4f4dSJason Wang  */
262986a4f4dSJason Wang static int vq2txq(struct virtqueue *vq)
263986a4f4dSJason Wang {
2649d0ca6edSRusty Russell 	return (vq->index - 1) / 2;
265986a4f4dSJason Wang }
266986a4f4dSJason Wang 
267986a4f4dSJason Wang static int txq2vq(int txq)
268986a4f4dSJason Wang {
269986a4f4dSJason Wang 	return txq * 2 + 1;
270986a4f4dSJason Wang }
271986a4f4dSJason Wang 
272986a4f4dSJason Wang static int vq2rxq(struct virtqueue *vq)
273986a4f4dSJason Wang {
2749d0ca6edSRusty Russell 	return vq->index / 2;
275986a4f4dSJason Wang }
276986a4f4dSJason Wang 
277986a4f4dSJason Wang static int rxq2vq(int rxq)
278986a4f4dSJason Wang {
279986a4f4dSJason Wang 	return rxq * 2;
280986a4f4dSJason Wang }
281986a4f4dSJason Wang 
282012873d0SMichael S. Tsirkin static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
283296f96fcSRusty Russell {
284012873d0SMichael S. Tsirkin 	return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
285296f96fcSRusty Russell }
286296f96fcSRusty Russell 
2879ab86bbcSShirley Ma /*
2889ab86bbcSShirley Ma  * private is used to chain pages for big packets, put the whole
2899ab86bbcSShirley Ma  * most recent used list in the beginning for reuse
2909ab86bbcSShirley Ma  */
291e9d7417bSJason Wang static void give_pages(struct receive_queue *rq, struct page *page)
292fb6813f4SRusty Russell {
2939ab86bbcSShirley Ma 	struct page *end;
2949ab86bbcSShirley Ma 
295e9d7417bSJason Wang 	/* Find end of list, sew whole thing into vi->rq.pages. */
2969ab86bbcSShirley Ma 	for (end = page; end->private; end = (struct page *)end->private);
297e9d7417bSJason Wang 	end->private = (unsigned long)rq->pages;
298e9d7417bSJason Wang 	rq->pages = page;
299fb6813f4SRusty Russell }
300fb6813f4SRusty Russell 
301e9d7417bSJason Wang static struct page *get_a_page(struct receive_queue *rq, gfp_t gfp_mask)
302fb6813f4SRusty Russell {
303e9d7417bSJason Wang 	struct page *p = rq->pages;
304fb6813f4SRusty Russell 
3059ab86bbcSShirley Ma 	if (p) {
306e9d7417bSJason Wang 		rq->pages = (struct page *)p->private;
3079ab86bbcSShirley Ma 		/* clear private here, it is used to chain pages */
3089ab86bbcSShirley Ma 		p->private = 0;
3099ab86bbcSShirley Ma 	} else
310fb6813f4SRusty Russell 		p = alloc_page(gfp_mask);
311fb6813f4SRusty Russell 	return p;
312fb6813f4SRusty Russell }
313fb6813f4SRusty Russell 
314e4e8452aSWillem de Bruijn static void virtqueue_napi_schedule(struct napi_struct *napi,
315e4e8452aSWillem de Bruijn 				    struct virtqueue *vq)
316e4e8452aSWillem de Bruijn {
317e4e8452aSWillem de Bruijn 	if (napi_schedule_prep(napi)) {
318e4e8452aSWillem de Bruijn 		virtqueue_disable_cb(vq);
319e4e8452aSWillem de Bruijn 		__napi_schedule(napi);
320e4e8452aSWillem de Bruijn 	}
321e4e8452aSWillem de Bruijn }
322e4e8452aSWillem de Bruijn 
323e4e8452aSWillem de Bruijn static void virtqueue_napi_complete(struct napi_struct *napi,
324e4e8452aSWillem de Bruijn 				    struct virtqueue *vq, int processed)
325e4e8452aSWillem de Bruijn {
326e4e8452aSWillem de Bruijn 	int opaque;
327e4e8452aSWillem de Bruijn 
328e4e8452aSWillem de Bruijn 	opaque = virtqueue_enable_cb_prepare(vq);
329fdaa767aSToshiaki Makita 	if (napi_complete_done(napi, processed)) {
330fdaa767aSToshiaki Makita 		if (unlikely(virtqueue_poll(vq, opaque)))
331e4e8452aSWillem de Bruijn 			virtqueue_napi_schedule(napi, vq);
332fdaa767aSToshiaki Makita 	} else {
333fdaa767aSToshiaki Makita 		virtqueue_disable_cb(vq);
334fdaa767aSToshiaki Makita 	}
335e4e8452aSWillem de Bruijn }
336e4e8452aSWillem de Bruijn 
337e9d7417bSJason Wang static void skb_xmit_done(struct virtqueue *vq)
338296f96fcSRusty Russell {
339e9d7417bSJason Wang 	struct virtnet_info *vi = vq->vdev->priv;
340b92f1e67SWillem de Bruijn 	struct napi_struct *napi = &vi->sq[vq2txq(vq)].napi;
341296f96fcSRusty Russell 
3422cb9c6baSRusty Russell 	/* Suppress further interrupts. */
343e9d7417bSJason Wang 	virtqueue_disable_cb(vq);
34411a3a154SRusty Russell 
345b92f1e67SWillem de Bruijn 	if (napi->weight)
346b92f1e67SWillem de Bruijn 		virtqueue_napi_schedule(napi, vq);
347b92f1e67SWillem de Bruijn 	else
348363f1514SRusty Russell 		/* We were probably waiting for more output buffers. */
349986a4f4dSJason Wang 		netif_wake_subqueue(vi->dev, vq2txq(vq));
350296f96fcSRusty Russell }
351296f96fcSRusty Russell 
35228b39bc7SJason Wang #define MRG_CTX_HEADER_SHIFT 22
35328b39bc7SJason Wang static void *mergeable_len_to_ctx(unsigned int truesize,
35428b39bc7SJason Wang 				  unsigned int headroom)
35528b39bc7SJason Wang {
35628b39bc7SJason Wang 	return (void *)(unsigned long)((headroom << MRG_CTX_HEADER_SHIFT) | truesize);
35728b39bc7SJason Wang }
35828b39bc7SJason Wang 
35928b39bc7SJason Wang static unsigned int mergeable_ctx_to_headroom(void *mrg_ctx)
36028b39bc7SJason Wang {
36128b39bc7SJason Wang 	return (unsigned long)mrg_ctx >> MRG_CTX_HEADER_SHIFT;
36228b39bc7SJason Wang }
36328b39bc7SJason Wang 
36428b39bc7SJason Wang static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx)
36528b39bc7SJason Wang {
36628b39bc7SJason Wang 	return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1);
36728b39bc7SJason Wang }
36828b39bc7SJason Wang 
3693464645aSMike Waychison /* Called from bottom half context */
370946fa564SMichael S. Tsirkin static struct sk_buff *page_to_skb(struct virtnet_info *vi,
371946fa564SMichael S. Tsirkin 				   struct receive_queue *rq,
3722613af0eSMichael Dalton 				   struct page *page, unsigned int offset,
373436c9453SJason Wang 				   unsigned int len, unsigned int truesize,
374503d539aSYuya Kusakabe 				   bool hdr_valid, unsigned int metasize)
3759ab86bbcSShirley Ma {
3769ab86bbcSShirley Ma 	struct sk_buff *skb;
377012873d0SMichael S. Tsirkin 	struct virtio_net_hdr_mrg_rxbuf *hdr;
3782613af0eSMichael Dalton 	unsigned int copy, hdr_len, hdr_padded_len;
3799ab86bbcSShirley Ma 	char *p;
3809ab86bbcSShirley Ma 
3812613af0eSMichael Dalton 	p = page_address(page) + offset;
3829ab86bbcSShirley Ma 
3839ab86bbcSShirley Ma 	/* copy small packet so we can reuse these pages for small data */
384c67f5db8SPaolo Abeni 	skb = napi_alloc_skb(&rq->napi, GOOD_COPY_LEN);
3859ab86bbcSShirley Ma 	if (unlikely(!skb))
3869ab86bbcSShirley Ma 		return NULL;
3879ab86bbcSShirley Ma 
3889ab86bbcSShirley Ma 	hdr = skb_vnet_hdr(skb);
3899ab86bbcSShirley Ma 
390012873d0SMichael S. Tsirkin 	hdr_len = vi->hdr_len;
391012873d0SMichael S. Tsirkin 	if (vi->mergeable_rx_bufs)
392a4a76503Sstephen hemminger 		hdr_padded_len = sizeof(*hdr);
393012873d0SMichael S. Tsirkin 	else
3942613af0eSMichael Dalton 		hdr_padded_len = sizeof(struct padded_vnet_hdr);
3953f2c31d9SMark McLoughlin 
396503d539aSYuya Kusakabe 	/* hdr_valid means no XDP, so we can copy the vnet header */
397436c9453SJason Wang 	if (hdr_valid)
3989ab86bbcSShirley Ma 		memcpy(hdr, p, hdr_len);
3993f2c31d9SMark McLoughlin 
4009ab86bbcSShirley Ma 	len -= hdr_len;
4012613af0eSMichael Dalton 	offset += hdr_padded_len;
4022613af0eSMichael Dalton 	p += hdr_padded_len;
4033f2c31d9SMark McLoughlin 
4043f2c31d9SMark McLoughlin 	copy = len;
4053f2c31d9SMark McLoughlin 	if (copy > skb_tailroom(skb))
4063f2c31d9SMark McLoughlin 		copy = skb_tailroom(skb);
40759ae1d12SJohannes Berg 	skb_put_data(skb, p, copy);
4083f2c31d9SMark McLoughlin 
409503d539aSYuya Kusakabe 	if (metasize) {
410503d539aSYuya Kusakabe 		__skb_pull(skb, metasize);
411503d539aSYuya Kusakabe 		skb_metadata_set(skb, metasize);
412503d539aSYuya Kusakabe 	}
413503d539aSYuya Kusakabe 
4143f2c31d9SMark McLoughlin 	len -= copy;
4159ab86bbcSShirley Ma 	offset += copy;
4163f2c31d9SMark McLoughlin 
4172613af0eSMichael Dalton 	if (vi->mergeable_rx_bufs) {
4182613af0eSMichael Dalton 		if (len)
4192613af0eSMichael Dalton 			skb_add_rx_frag(skb, 0, page, offset, len, truesize);
4202613af0eSMichael Dalton 		else
4212613af0eSMichael Dalton 			put_page(page);
4222613af0eSMichael Dalton 		return skb;
4232613af0eSMichael Dalton 	}
4242613af0eSMichael Dalton 
425e878d78bSSasha Levin 	/*
426e878d78bSSasha Levin 	 * Verify that we can indeed put this data into a skb.
427e878d78bSSasha Levin 	 * This is here to handle cases when the device erroneously
428e878d78bSSasha Levin 	 * tries to receive more than is possible. This is usually
429e878d78bSSasha Levin 	 * the case of a broken device.
430e878d78bSSasha Levin 	 */
431e878d78bSSasha Levin 	if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
432be443899SAmerigo Wang 		net_dbg_ratelimited("%s: too much data\n", skb->dev->name);
433e878d78bSSasha Levin 		dev_kfree_skb(skb);
434e878d78bSSasha Levin 		return NULL;
435e878d78bSSasha Levin 	}
4362613af0eSMichael Dalton 	BUG_ON(offset >= PAGE_SIZE);
4379ab86bbcSShirley Ma 	while (len) {
4382613af0eSMichael Dalton 		unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len);
4392613af0eSMichael Dalton 		skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset,
4402613af0eSMichael Dalton 				frag_size, truesize);
4412613af0eSMichael Dalton 		len -= frag_size;
4429ab86bbcSShirley Ma 		page = (struct page *)page->private;
4439ab86bbcSShirley Ma 		offset = 0;
4443f2c31d9SMark McLoughlin 	}
4453f2c31d9SMark McLoughlin 
4469ab86bbcSShirley Ma 	if (page)
447e9d7417bSJason Wang 		give_pages(rq, page);
4483f2c31d9SMark McLoughlin 
4499ab86bbcSShirley Ma 	return skb;
4509ab86bbcSShirley Ma }
4519ab86bbcSShirley Ma 
452735fc405SJesper Dangaard Brouer static int __virtnet_xdp_xmit_one(struct virtnet_info *vi,
453735fc405SJesper Dangaard Brouer 				   struct send_queue *sq,
45444fa2dbdSJesper Dangaard Brouer 				   struct xdp_frame *xdpf)
45556434a01SJohn Fastabend {
45656434a01SJohn Fastabend 	struct virtio_net_hdr_mrg_rxbuf *hdr;
45756434a01SJohn Fastabend 	int err;
45856434a01SJohn Fastabend 
459cac320c8SJesper Dangaard Brouer 	if (unlikely(xdpf->headroom < vi->hdr_len))
460cac320c8SJesper Dangaard Brouer 		return -EOVERFLOW;
461cac320c8SJesper Dangaard Brouer 
462cac320c8SJesper Dangaard Brouer 	/* Make room for virtqueue hdr (also change xdpf->headroom?) */
463cac320c8SJesper Dangaard Brouer 	xdpf->data -= vi->hdr_len;
46456434a01SJohn Fastabend 	/* Zero header and leave csum up to XDP layers */
465cac320c8SJesper Dangaard Brouer 	hdr = xdpf->data;
46656434a01SJohn Fastabend 	memset(hdr, 0, vi->hdr_len);
467cac320c8SJesper Dangaard Brouer 	xdpf->len   += vi->hdr_len;
46856434a01SJohn Fastabend 
469cac320c8SJesper Dangaard Brouer 	sg_init_one(sq->sg, xdpf->data, xdpf->len);
470bb91accfSJason Wang 
4715050471dSToshiaki Makita 	err = virtqueue_add_outbuf(sq->vq, sq->sg, 1, xdp_to_ptr(xdpf),
4725050471dSToshiaki Makita 				   GFP_ATOMIC);
47311b7d897SJesper Dangaard Brouer 	if (unlikely(err))
474cac320c8SJesper Dangaard Brouer 		return -ENOSPC; /* Caller handle free/refcnt */
47556434a01SJohn Fastabend 
476cac320c8SJesper Dangaard Brouer 	return 0;
47756434a01SJohn Fastabend }
47856434a01SJohn Fastabend 
4792a43565cSToshiaki Makita static struct send_queue *virtnet_xdp_sq(struct virtnet_info *vi)
4802a43565cSToshiaki Makita {
4812a43565cSToshiaki Makita 	unsigned int qp;
4822a43565cSToshiaki Makita 
4832a43565cSToshiaki Makita 	qp = vi->curr_queue_pairs - vi->xdp_queue_pairs + smp_processor_id();
4842a43565cSToshiaki Makita 	return &vi->sq[qp];
4852a43565cSToshiaki Makita }
4862a43565cSToshiaki Makita 
487735fc405SJesper Dangaard Brouer static int virtnet_xdp_xmit(struct net_device *dev,
48842b33468SJesper Dangaard Brouer 			    int n, struct xdp_frame **frames, u32 flags)
489186b3c99SJason Wang {
490186b3c99SJason Wang 	struct virtnet_info *vi = netdev_priv(dev);
4918dcc5b0aSJesper Dangaard Brouer 	struct receive_queue *rq = vi->rq;
4928dcc5b0aSJesper Dangaard Brouer 	struct bpf_prog *xdp_prog;
493735fc405SJesper Dangaard Brouer 	struct send_queue *sq;
494735fc405SJesper Dangaard Brouer 	unsigned int len;
495546f2897SToshiaki Makita 	int packets = 0;
496546f2897SToshiaki Makita 	int bytes = 0;
497735fc405SJesper Dangaard Brouer 	int drops = 0;
498461f03dcSToshiaki Makita 	int kicks = 0;
4995b8f3c8dSToshiaki Makita 	int ret, err;
5005050471dSToshiaki Makita 	void *ptr;
501735fc405SJesper Dangaard Brouer 	int i;
502735fc405SJesper Dangaard Brouer 
5038dcc5b0aSJesper Dangaard Brouer 	/* Only allow ndo_xdp_xmit if XDP is loaded on dev, as this
5048dcc5b0aSJesper Dangaard Brouer 	 * indicate XDP resources have been successfully allocated.
5058dcc5b0aSJesper Dangaard Brouer 	 */
5069719c6b9SJohn Fastabend 	xdp_prog = rcu_access_pointer(rq->xdp_prog);
5071667c08aSToshiaki Makita 	if (!xdp_prog)
5081667c08aSToshiaki Makita 		return -ENXIO;
5091667c08aSToshiaki Makita 
5109ab86bbcSShirley Ma 	sq = virtnet_xdp_sq(vi);
5119ab86bbcSShirley Ma 
5129ab86bbcSShirley Ma 	if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK)) {
513186b3c99SJason Wang 		ret = -EINVAL;
514186b3c99SJason Wang 		drops = n;
515186b3c99SJason Wang 		goto out;
516186b3c99SJason Wang 	}
517186b3c99SJason Wang 
518735fc405SJesper Dangaard Brouer 	/* Free up any pending old buffers before queueing new ones. */
5195050471dSToshiaki Makita 	while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
520546f2897SToshiaki Makita 		if (likely(is_xdp_frame(ptr))) {
521546f2897SToshiaki Makita 			struct xdp_frame *frame = ptr_to_xdp(ptr);
522546f2897SToshiaki Makita 
523546f2897SToshiaki Makita 			bytes += frame->len;
524546f2897SToshiaki Makita 			xdp_return_frame(frame);
525546f2897SToshiaki Makita 		} else {
526546f2897SToshiaki Makita 			struct sk_buff *skb = ptr;
527546f2897SToshiaki Makita 
528546f2897SToshiaki Makita 			bytes += skb->len;
529546f2897SToshiaki Makita 			napi_consume_skb(skb, false);
530546f2897SToshiaki Makita 		}
531546f2897SToshiaki Makita 		packets++;
5325050471dSToshiaki Makita 	}
533735fc405SJesper Dangaard Brouer 
534735fc405SJesper Dangaard Brouer 	for (i = 0; i < n; i++) {
535735fc405SJesper Dangaard Brouer 		struct xdp_frame *xdpf = frames[i];
536735fc405SJesper Dangaard Brouer 
537735fc405SJesper Dangaard Brouer 		err = __virtnet_xdp_xmit_one(vi, sq, xdpf);
538735fc405SJesper Dangaard Brouer 		if (err) {
539735fc405SJesper Dangaard Brouer 			xdp_return_frame_rx_napi(xdpf);
540735fc405SJesper Dangaard Brouer 			drops++;
541735fc405SJesper Dangaard Brouer 		}
542735fc405SJesper Dangaard Brouer 	}
5435b8f3c8dSToshiaki Makita 	ret = n - drops;
5445d274cb4SJesper Dangaard Brouer 
545461f03dcSToshiaki Makita 	if (flags & XDP_XMIT_FLUSH) {
546461f03dcSToshiaki Makita 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq))
547461f03dcSToshiaki Makita 			kicks = 1;
548461f03dcSToshiaki Makita 	}
5495b8f3c8dSToshiaki Makita out:
5505b8f3c8dSToshiaki Makita 	u64_stats_update_begin(&sq->stats.syncp);
551546f2897SToshiaki Makita 	sq->stats.bytes += bytes;
552546f2897SToshiaki Makita 	sq->stats.packets += packets;
5535b8f3c8dSToshiaki Makita 	sq->stats.xdp_tx += n;
5545b8f3c8dSToshiaki Makita 	sq->stats.xdp_tx_drops += drops;
555461f03dcSToshiaki Makita 	sq->stats.kicks += kicks;
5565b8f3c8dSToshiaki Makita 	u64_stats_update_end(&sq->stats.syncp);
5575d274cb4SJesper Dangaard Brouer 
5585b8f3c8dSToshiaki Makita 	return ret;
559186b3c99SJason Wang }
560186b3c99SJason Wang 
561f6b10209SJason Wang static unsigned int virtnet_get_headroom(struct virtnet_info *vi)
562f6b10209SJason Wang {
563f6b10209SJason Wang 	return vi->xdp_queue_pairs ? VIRTIO_XDP_HEADROOM : 0;
564f6b10209SJason Wang }
565f6b10209SJason Wang 
5664941d472SJason Wang /* We copy the packet for XDP in the following cases:
5674941d472SJason Wang  *
5684941d472SJason Wang  * 1) Packet is scattered across multiple rx buffers.
5694941d472SJason Wang  * 2) Headroom space is insufficient.
5704941d472SJason Wang  *
5714941d472SJason Wang  * This is inefficient but it's a temporary condition that
5724941d472SJason Wang  * we hit right after XDP is enabled and until queue is refilled
5734941d472SJason Wang  * with large buffers with sufficient headroom - so it should affect
5744941d472SJason Wang  * at most queue size packets.
5754941d472SJason Wang  * Afterwards, the conditions to enable
5764941d472SJason Wang  * XDP should preclude the underlying device from sending packets
5774941d472SJason Wang  * across multiple buffers (num_buf > 1), and we make sure buffers
5784941d472SJason Wang  * have enough headroom.
57972979a6cSJohn Fastabend  */
58072979a6cSJohn Fastabend static struct page *xdp_linearize_page(struct receive_queue *rq,
58156a86f84SJason Wang 				       u16 *num_buf,
58272979a6cSJohn Fastabend 				       struct page *p,
58372979a6cSJohn Fastabend 				       int offset,
5844941d472SJason Wang 				       int page_off,
58572979a6cSJohn Fastabend 				       unsigned int *len)
58672979a6cSJohn Fastabend {
58772979a6cSJohn Fastabend 	struct page *page = alloc_page(GFP_ATOMIC);
58872979a6cSJohn Fastabend 
58972979a6cSJohn Fastabend 	if (!page)
59072979a6cSJohn Fastabend 		return NULL;
59172979a6cSJohn Fastabend 
59272979a6cSJohn Fastabend 	memcpy(page_address(page) + page_off, page_address(p) + offset, *len);
59372979a6cSJohn Fastabend 	page_off += *len;
59472979a6cSJohn Fastabend 
59556a86f84SJason Wang 	while (--*num_buf) {
5963cc81a9aSJason Wang 		int tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
59772979a6cSJohn Fastabend 		unsigned int buflen;
59872979a6cSJohn Fastabend 		void *buf;
59972979a6cSJohn Fastabend 		int off;
60072979a6cSJohn Fastabend 
601680557cfSMichael S. Tsirkin 		buf = virtqueue_get_buf(rq->vq, &buflen);
602680557cfSMichael S. Tsirkin 		if (unlikely(!buf))
60372979a6cSJohn Fastabend 			goto err_buf;
60472979a6cSJohn Fastabend 
60572979a6cSJohn Fastabend 		p = virt_to_head_page(buf);
60672979a6cSJohn Fastabend 		off = buf - page_address(p);
60772979a6cSJohn Fastabend 
60856a86f84SJason Wang 		/* guard against a misconfigured or uncooperative backend that
60956a86f84SJason Wang 		 * is sending packet larger than the MTU.
61056a86f84SJason Wang 		 */
6113cc81a9aSJason Wang 		if ((page_off + buflen + tailroom) > PAGE_SIZE) {
61256a86f84SJason Wang 			put_page(p);
61356a86f84SJason Wang 			goto err_buf;
61456a86f84SJason Wang 		}
61556a86f84SJason Wang 
61672979a6cSJohn Fastabend 		memcpy(page_address(page) + page_off,
61772979a6cSJohn Fastabend 		       page_address(p) + off, buflen);
61872979a6cSJohn Fastabend 		page_off += buflen;
61956a86f84SJason Wang 		put_page(p);
62072979a6cSJohn Fastabend 	}
62172979a6cSJohn Fastabend 
6222de2f7f4SJohn Fastabend 	/* Headroom does not contribute to packet length */
6232de2f7f4SJohn Fastabend 	*len = page_off - VIRTIO_XDP_HEADROOM;
62472979a6cSJohn Fastabend 	return page;
62572979a6cSJohn Fastabend err_buf:
62672979a6cSJohn Fastabend 	__free_pages(page, 0);
62772979a6cSJohn Fastabend 	return NULL;
62872979a6cSJohn Fastabend }
62972979a6cSJohn Fastabend 
6304941d472SJason Wang static struct sk_buff *receive_small(struct net_device *dev,
6314941d472SJason Wang 				     struct virtnet_info *vi,
6324941d472SJason Wang 				     struct receive_queue *rq,
6334941d472SJason Wang 				     void *buf, void *ctx,
634186b3c99SJason Wang 				     unsigned int len,
6357d9d60fdSToshiaki Makita 				     unsigned int *xdp_xmit,
636d46eeeafSJason Wang 				     struct virtnet_rq_stats *stats)
6374941d472SJason Wang {
6384941d472SJason Wang 	struct sk_buff *skb;
6394941d472SJason Wang 	struct bpf_prog *xdp_prog;
6404941d472SJason Wang 	unsigned int xdp_headroom = (unsigned long)ctx;
6414941d472SJason Wang 	unsigned int header_offset = VIRTNET_RX_PAD + xdp_headroom;
6424941d472SJason Wang 	unsigned int headroom = vi->hdr_len + header_offset;
6434941d472SJason Wang 	unsigned int buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
6444941d472SJason Wang 			      SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
6454941d472SJason Wang 	struct page *page = virt_to_head_page(buf);
64611b7d897SJesper Dangaard Brouer 	unsigned int delta = 0;
6474941d472SJason Wang 	struct page *xdp_page;
64811b7d897SJesper Dangaard Brouer 	int err;
649503d539aSYuya Kusakabe 	unsigned int metasize = 0;
65011b7d897SJesper Dangaard Brouer 
6514941d472SJason Wang 	len -= vi->hdr_len;
652d46eeeafSJason Wang 	stats->bytes += len;
6534941d472SJason Wang 
6544941d472SJason Wang 	rcu_read_lock();
6554941d472SJason Wang 	xdp_prog = rcu_dereference(rq->xdp_prog);
6564941d472SJason Wang 	if (xdp_prog) {
6574941d472SJason Wang 		struct virtio_net_hdr_mrg_rxbuf *hdr = buf + header_offset;
65844fa2dbdSJesper Dangaard Brouer 		struct xdp_frame *xdpf;
6594941d472SJason Wang 		struct xdp_buff xdp;
6604941d472SJason Wang 		void *orig_data;
6614941d472SJason Wang 		u32 act;
6624941d472SJason Wang 
66395dbe9e7SJesper Dangaard Brouer 		if (unlikely(hdr->hdr.gso_type))
6644941d472SJason Wang 			goto err_xdp;
6654941d472SJason Wang 
6664941d472SJason Wang 		if (unlikely(xdp_headroom < virtnet_get_headroom(vi))) {
6674941d472SJason Wang 			int offset = buf - page_address(page) + header_offset;
6684941d472SJason Wang 			unsigned int tlen = len + vi->hdr_len;
6694941d472SJason Wang 			u16 num_buf = 1;
6704941d472SJason Wang 
6714941d472SJason Wang 			xdp_headroom = virtnet_get_headroom(vi);
6724941d472SJason Wang 			header_offset = VIRTNET_RX_PAD + xdp_headroom;
6734941d472SJason Wang 			headroom = vi->hdr_len + header_offset;
6744941d472SJason Wang 			buflen = SKB_DATA_ALIGN(GOOD_PACKET_LEN + headroom) +
6754941d472SJason Wang 				 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
6764941d472SJason Wang 			xdp_page = xdp_linearize_page(rq, &num_buf, page,
6774941d472SJason Wang 						      offset, header_offset,
6784941d472SJason Wang 						      &tlen);
6794941d472SJason Wang 			if (!xdp_page)
6804941d472SJason Wang 				goto err_xdp;
6814941d472SJason Wang 
6824941d472SJason Wang 			buf = page_address(xdp_page);
6834941d472SJason Wang 			put_page(page);
6844941d472SJason Wang 			page = xdp_page;
6854941d472SJason Wang 		}
6864941d472SJason Wang 
6874941d472SJason Wang 		xdp.data_hard_start = buf + VIRTNET_RX_PAD + vi->hdr_len;
6884941d472SJason Wang 		xdp.data = xdp.data_hard_start + xdp_headroom;
6894941d472SJason Wang 		xdp.data_end = xdp.data + len;
690503d539aSYuya Kusakabe 		xdp.data_meta = xdp.data;
691754b8a21SJesper Dangaard Brouer 		xdp.rxq = &rq->xdp_rxq;
6929ce6146eSJesper Dangaard Brouer 		xdp.frame_sz = buflen;
6934941d472SJason Wang 		orig_data = xdp.data;
6944941d472SJason Wang 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
695d46eeeafSJason Wang 		stats->xdp_packets++;
6964941d472SJason Wang 
6974941d472SJason Wang 		switch (act) {
6984941d472SJason Wang 		case XDP_PASS:
6994941d472SJason Wang 			/* Recalculate length in case bpf program changed it */
7004941d472SJason Wang 			delta = orig_data - xdp.data;
7016870de43SNikita V. Shirokov 			len = xdp.data_end - xdp.data;
702503d539aSYuya Kusakabe 			metasize = xdp.data - xdp.data_meta;
7034941d472SJason Wang 			break;
7044941d472SJason Wang 		case XDP_TX:
705d46eeeafSJason Wang 			stats->xdp_tx++;
7061b698fa5SLorenzo Bianconi 			xdpf = xdp_convert_buff_to_frame(&xdp);
70744fa2dbdSJesper Dangaard Brouer 			if (unlikely(!xdpf))
70844fa2dbdSJesper Dangaard Brouer 				goto err_xdp;
709ca9e83b4SJason Wang 			err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
710ca9e83b4SJason Wang 			if (unlikely(err < 0)) {
7114941d472SJason Wang 				trace_xdp_exception(vi->dev, xdp_prog, act);
71211b7d897SJesper Dangaard Brouer 				goto err_xdp;
71311b7d897SJesper Dangaard Brouer 			}
7142471c75eSJesper Dangaard Brouer 			*xdp_xmit |= VIRTIO_XDP_TX;
715186b3c99SJason Wang 			rcu_read_unlock();
716186b3c99SJason Wang 			goto xdp_xmit;
717186b3c99SJason Wang 		case XDP_REDIRECT:
718d46eeeafSJason Wang 			stats->xdp_redirects++;
719186b3c99SJason Wang 			err = xdp_do_redirect(dev, &xdp, xdp_prog);
72011b7d897SJesper Dangaard Brouer 			if (err)
72111b7d897SJesper Dangaard Brouer 				goto err_xdp;
7222471c75eSJesper Dangaard Brouer 			*xdp_xmit |= VIRTIO_XDP_REDIR;
7234941d472SJason Wang 			rcu_read_unlock();
7244941d472SJason Wang 			goto xdp_xmit;
7254941d472SJason Wang 		default:
7264941d472SJason Wang 			bpf_warn_invalid_xdp_action(act);
727*df561f66SGustavo A. R. Silva 			fallthrough;
7284941d472SJason Wang 		case XDP_ABORTED:
7294941d472SJason Wang 			trace_xdp_exception(vi->dev, xdp_prog, act);
7304941d472SJason Wang 		case XDP_DROP:
7314941d472SJason Wang 			goto err_xdp;
7324941d472SJason Wang 		}
7334941d472SJason Wang 	}
7344941d472SJason Wang 	rcu_read_unlock();
7354941d472SJason Wang 
7364941d472SJason Wang 	skb = build_skb(buf, buflen);
7374941d472SJason Wang 	if (!skb) {
7384941d472SJason Wang 		put_page(page);
7394941d472SJason Wang 		goto err;
7404941d472SJason Wang 	}
7414941d472SJason Wang 	skb_reserve(skb, headroom - delta);
7426870de43SNikita V. Shirokov 	skb_put(skb, len);
743f1d4884dSYuya Kusakabe 	if (!xdp_prog) {
7444941d472SJason Wang 		buf += header_offset;
7454941d472SJason Wang 		memcpy(skb_vnet_hdr(skb), buf, vi->hdr_len);
746f1d4884dSYuya Kusakabe 	} /* keep zeroed vnet hdr since XDP is loaded */
7474941d472SJason Wang 
748503d539aSYuya Kusakabe 	if (metasize)
749503d539aSYuya Kusakabe 		skb_metadata_set(skb, metasize);
750503d539aSYuya Kusakabe 
7514941d472SJason Wang err:
7524941d472SJason Wang 	return skb;
7534941d472SJason Wang 
7544941d472SJason Wang err_xdp:
7554941d472SJason Wang 	rcu_read_unlock();
756d46eeeafSJason Wang 	stats->xdp_drops++;
757d46eeeafSJason Wang 	stats->drops++;
7584941d472SJason Wang 	put_page(page);
7594941d472SJason Wang xdp_xmit:
7604941d472SJason Wang 	return NULL;
7614941d472SJason Wang }
7624941d472SJason Wang 
7634941d472SJason Wang static struct sk_buff *receive_big(struct net_device *dev,
7644941d472SJason Wang 				   struct virtnet_info *vi,
7654941d472SJason Wang 				   struct receive_queue *rq,
7664941d472SJason Wang 				   void *buf,
7677d9d60fdSToshiaki Makita 				   unsigned int len,
768d46eeeafSJason Wang 				   struct virtnet_rq_stats *stats)
7694941d472SJason Wang {
7704941d472SJason Wang 	struct page *page = buf;
771503d539aSYuya Kusakabe 	struct sk_buff *skb =
772503d539aSYuya Kusakabe 		page_to_skb(vi, rq, page, 0, len, PAGE_SIZE, true, 0);
7734941d472SJason Wang 
774d46eeeafSJason Wang 	stats->bytes += len - vi->hdr_len;
7754941d472SJason Wang 	if (unlikely(!skb))
7764941d472SJason Wang 		goto err;
7774941d472SJason Wang 
7784941d472SJason Wang 	return skb;
7794941d472SJason Wang 
7804941d472SJason Wang err:
781d46eeeafSJason Wang 	stats->drops++;
7824941d472SJason Wang 	give_pages(rq, page);
7834941d472SJason Wang 	return NULL;
7844941d472SJason Wang }
7854941d472SJason Wang 
7868fc3b9e9SMichael S. Tsirkin static struct sk_buff *receive_mergeable(struct net_device *dev,
787fdd819b2SMichael S. Tsirkin 					 struct virtnet_info *vi,
7888fc3b9e9SMichael S. Tsirkin 					 struct receive_queue *rq,
789680557cfSMichael S. Tsirkin 					 void *buf,
790680557cfSMichael S. Tsirkin 					 void *ctx,
791186b3c99SJason Wang 					 unsigned int len,
7927d9d60fdSToshiaki Makita 					 unsigned int *xdp_xmit,
793d46eeeafSJason Wang 					 struct virtnet_rq_stats *stats)
7949ab86bbcSShirley Ma {
795012873d0SMichael S. Tsirkin 	struct virtio_net_hdr_mrg_rxbuf *hdr = buf;
796012873d0SMichael S. Tsirkin 	u16 num_buf = virtio16_to_cpu(vi->vdev, hdr->num_buffers);
7978fc3b9e9SMichael S. Tsirkin 	struct page *page = virt_to_head_page(buf);
7988fc3b9e9SMichael S. Tsirkin 	int offset = buf - page_address(page);
799f600b690SJohn Fastabend 	struct sk_buff *head_skb, *curr_skb;
800f600b690SJohn Fastabend 	struct bpf_prog *xdp_prog;
8019ce6146eSJesper Dangaard Brouer 	unsigned int truesize = mergeable_ctx_to_truesize(ctx);
8024941d472SJason Wang 	unsigned int headroom = mergeable_ctx_to_headroom(ctx);
803503d539aSYuya Kusakabe 	unsigned int metasize = 0;
8049ce6146eSJesper Dangaard Brouer 	unsigned int frame_sz;
8059ce6146eSJesper Dangaard Brouer 	int err;
806ab7db917SMichael Dalton 
80756434a01SJohn Fastabend 	head_skb = NULL;
808d46eeeafSJason Wang 	stats->bytes += len - vi->hdr_len;
80956434a01SJohn Fastabend 
810f600b690SJohn Fastabend 	rcu_read_lock();
811f600b690SJohn Fastabend 	xdp_prog = rcu_dereference(rq->xdp_prog);
812f600b690SJohn Fastabend 	if (xdp_prog) {
81344fa2dbdSJesper Dangaard Brouer 		struct xdp_frame *xdpf;
81472979a6cSJohn Fastabend 		struct page *xdp_page;
8150354e4d1SJohn Fastabend 		struct xdp_buff xdp;
8160354e4d1SJohn Fastabend 		void *data;
817f600b690SJohn Fastabend 		u32 act;
818f600b690SJohn Fastabend 
8193d62b2a0SJason Wang 		/* Transient failure which in theory could occur if
8203d62b2a0SJason Wang 		 * in-flight packets from before XDP was enabled reach
8213d62b2a0SJason Wang 		 * the receive path after XDP is loaded.
8223d62b2a0SJason Wang 		 */
8233d62b2a0SJason Wang 		if (unlikely(hdr->hdr.gso_type))
8243d62b2a0SJason Wang 			goto err_xdp;
8253d62b2a0SJason Wang 
8269ce6146eSJesper Dangaard Brouer 		/* Buffers with headroom use PAGE_SIZE as alloc size,
8279ce6146eSJesper Dangaard Brouer 		 * see add_recvbuf_mergeable() + get_mergeable_buf_len()
8289ce6146eSJesper Dangaard Brouer 		 */
8299ce6146eSJesper Dangaard Brouer 		frame_sz = headroom ? PAGE_SIZE : truesize;
8309ce6146eSJesper Dangaard Brouer 
8313cc81a9aSJason Wang 		/* This happens when rx buffer size is underestimated
8323cc81a9aSJason Wang 		 * or headroom is not enough because of the buffer
8333cc81a9aSJason Wang 		 * was refilled before XDP is set. This should only
8343cc81a9aSJason Wang 		 * happen for the first several packets, so we don't
8353cc81a9aSJason Wang 		 * care much about its performance.
8363cc81a9aSJason Wang 		 */
8374941d472SJason Wang 		if (unlikely(num_buf > 1 ||
8384941d472SJason Wang 			     headroom < virtnet_get_headroom(vi))) {
83972979a6cSJohn Fastabend 			/* linearize data for XDP */
84056a86f84SJason Wang 			xdp_page = xdp_linearize_page(rq, &num_buf,
8414941d472SJason Wang 						      page, offset,
8424941d472SJason Wang 						      VIRTIO_XDP_HEADROOM,
8434941d472SJason Wang 						      &len);
8449ce6146eSJesper Dangaard Brouer 			frame_sz = PAGE_SIZE;
8459ce6146eSJesper Dangaard Brouer 
84672979a6cSJohn Fastabend 			if (!xdp_page)
847f600b690SJohn Fastabend 				goto err_xdp;
8482de2f7f4SJohn Fastabend 			offset = VIRTIO_XDP_HEADROOM;
84972979a6cSJohn Fastabend 		} else {
85072979a6cSJohn Fastabend 			xdp_page = page;
851f600b690SJohn Fastabend 		}
852f600b690SJohn Fastabend 
8532de2f7f4SJohn Fastabend 		/* Allow consuming headroom but reserve enough space to push
8542de2f7f4SJohn Fastabend 		 * the descriptor on if we get an XDP_TX return code.
8552de2f7f4SJohn Fastabend 		 */
8560354e4d1SJohn Fastabend 		data = page_address(xdp_page) + offset;
8572de2f7f4SJohn Fastabend 		xdp.data_hard_start = data - VIRTIO_XDP_HEADROOM + vi->hdr_len;
8580354e4d1SJohn Fastabend 		xdp.data = data + vi->hdr_len;
8590354e4d1SJohn Fastabend 		xdp.data_end = xdp.data + (len - vi->hdr_len);
860503d539aSYuya Kusakabe 		xdp.data_meta = xdp.data;
861754b8a21SJesper Dangaard Brouer 		xdp.rxq = &rq->xdp_rxq;
8629ce6146eSJesper Dangaard Brouer 		xdp.frame_sz = frame_sz - vi->hdr_len;
863754b8a21SJesper Dangaard Brouer 
8640354e4d1SJohn Fastabend 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
865d46eeeafSJason Wang 		stats->xdp_packets++;
8660354e4d1SJohn Fastabend 
86756434a01SJohn Fastabend 		switch (act) {
86856434a01SJohn Fastabend 		case XDP_PASS:
869503d539aSYuya Kusakabe 			metasize = xdp.data - xdp.data_meta;
8702de2f7f4SJohn Fastabend 
871503d539aSYuya Kusakabe 			/* recalculate offset to account for any header
872503d539aSYuya Kusakabe 			 * adjustments and minus the metasize to copy the
873503d539aSYuya Kusakabe 			 * metadata in page_to_skb(). Note other cases do not
874503d539aSYuya Kusakabe 			 * build an skb and avoid using offset
8756870de43SNikita V. Shirokov 			 */
876503d539aSYuya Kusakabe 			offset = xdp.data - page_address(xdp_page) -
877503d539aSYuya Kusakabe 				 vi->hdr_len - metasize;
878503d539aSYuya Kusakabe 
879503d539aSYuya Kusakabe 			/* recalculate len if xdp.data, xdp.data_end or
880503d539aSYuya Kusakabe 			 * xdp.data_meta were adjusted
881503d539aSYuya Kusakabe 			 */
882503d539aSYuya Kusakabe 			len = xdp.data_end - xdp.data + vi->hdr_len + metasize;
8831830f893SJason Wang 			/* We can only create skb based on xdp_page. */
8841830f893SJason Wang 			if (unlikely(xdp_page != page)) {
8851830f893SJason Wang 				rcu_read_unlock();
8861830f893SJason Wang 				put_page(page);
887503d539aSYuya Kusakabe 				head_skb = page_to_skb(vi, rq, xdp_page, offset,
888503d539aSYuya Kusakabe 						       len, PAGE_SIZE, false,
889503d539aSYuya Kusakabe 						       metasize);
8901830f893SJason Wang 				return head_skb;
8911830f893SJason Wang 			}
89256434a01SJohn Fastabend 			break;
89356434a01SJohn Fastabend 		case XDP_TX:
894d46eeeafSJason Wang 			stats->xdp_tx++;
8951b698fa5SLorenzo Bianconi 			xdpf = xdp_convert_buff_to_frame(&xdp);
89644fa2dbdSJesper Dangaard Brouer 			if (unlikely(!xdpf))
89744fa2dbdSJesper Dangaard Brouer 				goto err_xdp;
898ca9e83b4SJason Wang 			err = virtnet_xdp_xmit(dev, 1, &xdpf, 0);
899ca9e83b4SJason Wang 			if (unlikely(err < 0)) {
9000354e4d1SJohn Fastabend 				trace_xdp_exception(vi->dev, xdp_prog, act);
90111b7d897SJesper Dangaard Brouer 				if (unlikely(xdp_page != page))
90211b7d897SJesper Dangaard Brouer 					put_page(xdp_page);
90311b7d897SJesper Dangaard Brouer 				goto err_xdp;
90411b7d897SJesper Dangaard Brouer 			}
9052471c75eSJesper Dangaard Brouer 			*xdp_xmit |= VIRTIO_XDP_TX;
90672979a6cSJohn Fastabend 			if (unlikely(xdp_page != page))
9075d458a13SJason Wang 				put_page(page);
90856434a01SJohn Fastabend 			rcu_read_unlock();
90956434a01SJohn Fastabend 			goto xdp_xmit;
9103cc81a9aSJason Wang 		case XDP_REDIRECT:
911d46eeeafSJason Wang 			stats->xdp_redirects++;
9123cc81a9aSJason Wang 			err = xdp_do_redirect(dev, &xdp, xdp_prog);
9133cc81a9aSJason Wang 			if (err) {
9143cc81a9aSJason Wang 				if (unlikely(xdp_page != page))
9153cc81a9aSJason Wang 					put_page(xdp_page);
9163cc81a9aSJason Wang 				goto err_xdp;
9173cc81a9aSJason Wang 			}
9182471c75eSJesper Dangaard Brouer 			*xdp_xmit |= VIRTIO_XDP_REDIR;
9193cc81a9aSJason Wang 			if (unlikely(xdp_page != page))
9206890418bSJason Wang 				put_page(page);
9213cc81a9aSJason Wang 			rcu_read_unlock();
9223cc81a9aSJason Wang 			goto xdp_xmit;
92356434a01SJohn Fastabend 		default:
9240354e4d1SJohn Fastabend 			bpf_warn_invalid_xdp_action(act);
925*df561f66SGustavo A. R. Silva 			fallthrough;
9260354e4d1SJohn Fastabend 		case XDP_ABORTED:
9270354e4d1SJohn Fastabend 			trace_xdp_exception(vi->dev, xdp_prog, act);
928*df561f66SGustavo A. R. Silva 			fallthrough;
9290354e4d1SJohn Fastabend 		case XDP_DROP:
93072979a6cSJohn Fastabend 			if (unlikely(xdp_page != page))
93172979a6cSJohn Fastabend 				__free_pages(xdp_page, 0);
932f600b690SJohn Fastabend 			goto err_xdp;
933f600b690SJohn Fastabend 		}
93456434a01SJohn Fastabend 	}
935f600b690SJohn Fastabend 	rcu_read_unlock();
936f600b690SJohn Fastabend 
93728b39bc7SJason Wang 	if (unlikely(len > truesize)) {
93856da5fd0SDan Carpenter 		pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
939680557cfSMichael S. Tsirkin 			 dev->name, len, (unsigned long)ctx);
940680557cfSMichael S. Tsirkin 		dev->stats.rx_length_errors++;
941680557cfSMichael S. Tsirkin 		goto err_skb;
942680557cfSMichael S. Tsirkin 	}
94328b39bc7SJason Wang 
944503d539aSYuya Kusakabe 	head_skb = page_to_skb(vi, rq, page, offset, len, truesize, !xdp_prog,
945503d539aSYuya Kusakabe 			       metasize);
946f600b690SJohn Fastabend 	curr_skb = head_skb;
9479ab86bbcSShirley Ma 
9488fc3b9e9SMichael S. Tsirkin 	if (unlikely(!curr_skb))
9498fc3b9e9SMichael S. Tsirkin 		goto err_skb;
9509ab86bbcSShirley Ma 	while (--num_buf) {
9518fc3b9e9SMichael S. Tsirkin 		int num_skb_frags;
9528fc3b9e9SMichael S. Tsirkin 
953680557cfSMichael S. Tsirkin 		buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx);
95403e9f8a0SYunjian Wang 		if (unlikely(!buf)) {
9558fc3b9e9SMichael S. Tsirkin 			pr_debug("%s: rx error: %d buffers out of %d missing\n",
956fdd819b2SMichael S. Tsirkin 				 dev->name, num_buf,
957012873d0SMichael S. Tsirkin 				 virtio16_to_cpu(vi->vdev,
958012873d0SMichael S. Tsirkin 						 hdr->num_buffers));
9598fc3b9e9SMichael S. Tsirkin 			dev->stats.rx_length_errors++;
9608fc3b9e9SMichael S. Tsirkin 			goto err_buf;
9613f2c31d9SMark McLoughlin 		}
9628fc3b9e9SMichael S. Tsirkin 
963d46eeeafSJason Wang 		stats->bytes += len;
9648fc3b9e9SMichael S. Tsirkin 		page = virt_to_head_page(buf);
96528b39bc7SJason Wang 
96628b39bc7SJason Wang 		truesize = mergeable_ctx_to_truesize(ctx);
96728b39bc7SJason Wang 		if (unlikely(len > truesize)) {
96856da5fd0SDan Carpenter 			pr_debug("%s: rx error: len %u exceeds truesize %lu\n",
969680557cfSMichael S. Tsirkin 				 dev->name, len, (unsigned long)ctx);
970680557cfSMichael S. Tsirkin 			dev->stats.rx_length_errors++;
971680557cfSMichael S. Tsirkin 			goto err_skb;
972680557cfSMichael S. Tsirkin 		}
9738fc3b9e9SMichael S. Tsirkin 
9748fc3b9e9SMichael S. Tsirkin 		num_skb_frags = skb_shinfo(curr_skb)->nr_frags;
9752613af0eSMichael Dalton 		if (unlikely(num_skb_frags == MAX_SKB_FRAGS)) {
9762613af0eSMichael Dalton 			struct sk_buff *nskb = alloc_skb(0, GFP_ATOMIC);
9778fc3b9e9SMichael S. Tsirkin 
9788fc3b9e9SMichael S. Tsirkin 			if (unlikely(!nskb))
9798fc3b9e9SMichael S. Tsirkin 				goto err_skb;
9802613af0eSMichael Dalton 			if (curr_skb == head_skb)
9812613af0eSMichael Dalton 				skb_shinfo(curr_skb)->frag_list = nskb;
9822613af0eSMichael Dalton 			else
9832613af0eSMichael Dalton 				curr_skb->next = nskb;
9842613af0eSMichael Dalton 			curr_skb = nskb;
9852613af0eSMichael Dalton 			head_skb->truesize += nskb->truesize;
9862613af0eSMichael Dalton 			num_skb_frags = 0;
9872613af0eSMichael Dalton 		}
9882613af0eSMichael Dalton 		if (curr_skb != head_skb) {
9892613af0eSMichael Dalton 			head_skb->data_len += len;
9902613af0eSMichael Dalton 			head_skb->len += len;
991fb51879dSMichael Dalton 			head_skb->truesize += truesize;
9922613af0eSMichael Dalton 		}
9938fc3b9e9SMichael S. Tsirkin 		offset = buf - page_address(page);
994ba275241SJason Wang 		if (skb_can_coalesce(curr_skb, num_skb_frags, page, offset)) {
995ba275241SJason Wang 			put_page(page);
996ba275241SJason Wang 			skb_coalesce_rx_frag(curr_skb, num_skb_frags - 1,
997fb51879dSMichael Dalton 					     len, truesize);
998ba275241SJason Wang 		} else {
9992613af0eSMichael Dalton 			skb_add_rx_frag(curr_skb, num_skb_frags, page,
1000fb51879dSMichael Dalton 					offset, len, truesize);
1001ba275241SJason Wang 		}
10028fc3b9e9SMichael S. Tsirkin 	}
10038fc3b9e9SMichael S. Tsirkin 
10045377d758SJohannes Berg 	ewma_pkt_len_add(&rq->mrg_avg_pkt_len, head_skb->len);
10058fc3b9e9SMichael S. Tsirkin 	return head_skb;
10068fc3b9e9SMichael S. Tsirkin 
1007f600b690SJohn Fastabend err_xdp:
1008f600b690SJohn Fastabend 	rcu_read_unlock();
1009d46eeeafSJason Wang 	stats->xdp_drops++;
10108fc3b9e9SMichael S. Tsirkin err_skb:
10118fc3b9e9SMichael S. Tsirkin 	put_page(page);
1012850e088dSJason Wang 	while (num_buf-- > 1) {
1013680557cfSMichael S. Tsirkin 		buf = virtqueue_get_buf(rq->vq, &len);
1014680557cfSMichael S. Tsirkin 		if (unlikely(!buf)) {
10158fc3b9e9SMichael S. Tsirkin 			pr_debug("%s: rx error: %d buffers missing\n",
10168fc3b9e9SMichael S. Tsirkin 				 dev->name, num_buf);
10178fc3b9e9SMichael S. Tsirkin 			dev->stats.rx_length_errors++;
10188fc3b9e9SMichael S. Tsirkin 			break;
10198fc3b9e9SMichael S. Tsirkin 		}
1020d46eeeafSJason Wang 		stats->bytes += len;
1021680557cfSMichael S. Tsirkin 		page = virt_to_head_page(buf);
10228fc3b9e9SMichael S. Tsirkin 		put_page(page);
10233f2c31d9SMark McLoughlin 	}
10248fc3b9e9SMichael S. Tsirkin err_buf:
1025d46eeeafSJason Wang 	stats->drops++;
10268fc3b9e9SMichael S. Tsirkin 	dev_kfree_skb(head_skb);
102756434a01SJohn Fastabend xdp_xmit:
10288fc3b9e9SMichael S. Tsirkin 	return NULL;
10299ab86bbcSShirley Ma }
10309ab86bbcSShirley Ma 
10317d9d60fdSToshiaki Makita static void receive_buf(struct virtnet_info *vi, struct receive_queue *rq,
10322471c75eSJesper Dangaard Brouer 			void *buf, unsigned int len, void **ctx,
1033a0929a44SToshiaki Makita 			unsigned int *xdp_xmit,
1034d46eeeafSJason Wang 			struct virtnet_rq_stats *stats)
10359ab86bbcSShirley Ma {
1036e9d7417bSJason Wang 	struct net_device *dev = vi->dev;
10379ab86bbcSShirley Ma 	struct sk_buff *skb;
1038012873d0SMichael S. Tsirkin 	struct virtio_net_hdr_mrg_rxbuf *hdr;
10399ab86bbcSShirley Ma 
1040bcff3162SMichael S. Tsirkin 	if (unlikely(len < vi->hdr_len + ETH_HLEN)) {
10419ab86bbcSShirley Ma 		pr_debug("%s: short packet %i\n", dev->name, len);
10429ab86bbcSShirley Ma 		dev->stats.rx_length_errors++;
1043ab7db917SMichael Dalton 		if (vi->mergeable_rx_bufs) {
1044680557cfSMichael S. Tsirkin 			put_page(virt_to_head_page(buf));
1045ab7db917SMichael Dalton 		} else if (vi->big_packets) {
104698bfd23cSMichael Dalton 			give_pages(rq, buf);
1047ab7db917SMichael Dalton 		} else {
1048f6b10209SJason Wang 			put_page(virt_to_head_page(buf));
1049ab7db917SMichael Dalton 		}
10507d9d60fdSToshiaki Makita 		return;
10519ab86bbcSShirley Ma 	}
10529ab86bbcSShirley Ma 
1053f121159dSMichael S. Tsirkin 	if (vi->mergeable_rx_bufs)
10547d9d60fdSToshiaki Makita 		skb = receive_mergeable(dev, vi, rq, buf, ctx, len, xdp_xmit,
1055a0929a44SToshiaki Makita 					stats);
1056f121159dSMichael S. Tsirkin 	else if (vi->big_packets)
1057a0929a44SToshiaki Makita 		skb = receive_big(dev, vi, rq, buf, len, stats);
1058f121159dSMichael S. Tsirkin 	else
1059a0929a44SToshiaki Makita 		skb = receive_small(dev, vi, rq, buf, ctx, len, xdp_xmit, stats);
1060f121159dSMichael S. Tsirkin 
10618fc3b9e9SMichael S. Tsirkin 	if (unlikely(!skb))
10627d9d60fdSToshiaki Makita 		return;
10633f2c31d9SMark McLoughlin 
10649ab86bbcSShirley Ma 	hdr = skb_vnet_hdr(skb);
10653fa2a1dfSstephen hemminger 
1066e858fae2SMike Rapoport 	if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID)
106710a8d94aSJason Wang 		skb->ip_summed = CHECKSUM_UNNECESSARY;
1068296f96fcSRusty Russell 
1069e858fae2SMike Rapoport 	if (virtio_net_hdr_to_skb(skb, &hdr->hdr,
1070e858fae2SMike Rapoport 				  virtio_is_little_endian(vi->vdev))) {
1071e858fae2SMike Rapoport 		net_warn_ratelimited("%s: bad gso: type: %u, size: %u\n",
1072e858fae2SMike Rapoport 				     dev->name, hdr->hdr.gso_type,
1073fdd819b2SMichael S. Tsirkin 				     hdr->hdr.gso_size);
1074296f96fcSRusty Russell 		goto frame_err;
1075296f96fcSRusty Russell 	}
1076296f96fcSRusty Russell 
1077133bbb18SWillem de Bruijn 	skb_record_rx_queue(skb, vq2rxq(rq->vq));
1078d1dc06dcSMike Rapoport 	skb->protocol = eth_type_trans(skb, dev);
1079d1dc06dcSMike Rapoport 	pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
1080d1dc06dcSMike Rapoport 		 ntohs(skb->protocol), skb->len, skb->pkt_type);
1081d1dc06dcSMike Rapoport 
10820fbd050aSEric Dumazet 	napi_gro_receive(&rq->napi, skb);
10837d9d60fdSToshiaki Makita 	return;
1084296f96fcSRusty Russell 
1085296f96fcSRusty Russell frame_err:
1086296f96fcSRusty Russell 	dev->stats.rx_frame_errors++;
1087296f96fcSRusty Russell 	dev_kfree_skb(skb);
1088296f96fcSRusty Russell }
1089296f96fcSRusty Russell 
1090192f68cfSJason Wang /* Unlike mergeable buffers, all buffers are allocated to the
1091192f68cfSJason Wang  * same size, except for the headroom. For this reason we do
1092192f68cfSJason Wang  * not need to use  mergeable_len_to_ctx here - it is enough
1093192f68cfSJason Wang  * to store the headroom as the context ignoring the truesize.
1094192f68cfSJason Wang  */
1095946fa564SMichael S. Tsirkin static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq,
1096946fa564SMichael S. Tsirkin 			     gfp_t gfp)
1097296f96fcSRusty Russell {
1098f6b10209SJason Wang 	struct page_frag *alloc_frag = &rq->alloc_frag;
1099f6b10209SJason Wang 	char *buf;
11002de2f7f4SJohn Fastabend 	unsigned int xdp_headroom = virtnet_get_headroom(vi);
1101192f68cfSJason Wang 	void *ctx = (void *)(unsigned long)xdp_headroom;
1102f6b10209SJason Wang 	int len = vi->hdr_len + VIRTNET_RX_PAD + GOOD_PACKET_LEN + xdp_headroom;
11039ab86bbcSShirley Ma 	int err;
11043f2c31d9SMark McLoughlin 
1105f6b10209SJason Wang 	len = SKB_DATA_ALIGN(len) +
1106f6b10209SJason Wang 	      SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1107f6b10209SJason Wang 	if (unlikely(!skb_page_frag_refill(len, alloc_frag, gfp)))
11089ab86bbcSShirley Ma 		return -ENOMEM;
1109296f96fcSRusty Russell 
1110f6b10209SJason Wang 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
1111f6b10209SJason Wang 	get_page(alloc_frag->page);
1112f6b10209SJason Wang 	alloc_frag->offset += len;
1113f6b10209SJason Wang 	sg_init_one(rq->sg, buf + VIRTNET_RX_PAD + xdp_headroom,
1114f6b10209SJason Wang 		    vi->hdr_len + GOOD_PACKET_LEN);
1115192f68cfSJason Wang 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
11169ab86bbcSShirley Ma 	if (err < 0)
1117f6b10209SJason Wang 		put_page(virt_to_head_page(buf));
11189ab86bbcSShirley Ma 	return err;
111997402b96SHerbert Xu }
112097402b96SHerbert Xu 
1121012873d0SMichael S. Tsirkin static int add_recvbuf_big(struct virtnet_info *vi, struct receive_queue *rq,
1122012873d0SMichael S. Tsirkin 			   gfp_t gfp)
11239ab86bbcSShirley Ma {
11249ab86bbcSShirley Ma 	struct page *first, *list = NULL;
11259ab86bbcSShirley Ma 	char *p;
11269ab86bbcSShirley Ma 	int i, err, offset;
1127296f96fcSRusty Russell 
1128a5835440SRusty Russell 	sg_init_table(rq->sg, MAX_SKB_FRAGS + 2);
1129a5835440SRusty Russell 
1130e9d7417bSJason Wang 	/* page in rq->sg[MAX_SKB_FRAGS + 1] is list tail */
11319ab86bbcSShirley Ma 	for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
1132e9d7417bSJason Wang 		first = get_a_page(rq, gfp);
11339ab86bbcSShirley Ma 		if (!first) {
11349ab86bbcSShirley Ma 			if (list)
1135e9d7417bSJason Wang 				give_pages(rq, list);
11369ab86bbcSShirley Ma 			return -ENOMEM;
1137296f96fcSRusty Russell 		}
1138e9d7417bSJason Wang 		sg_set_buf(&rq->sg[i], page_address(first), PAGE_SIZE);
11399ab86bbcSShirley Ma 
11409ab86bbcSShirley Ma 		/* chain new page in list head to match sg */
11419ab86bbcSShirley Ma 		first->private = (unsigned long)list;
11429ab86bbcSShirley Ma 		list = first;
11439ab86bbcSShirley Ma 	}
11449ab86bbcSShirley Ma 
1145e9d7417bSJason Wang 	first = get_a_page(rq, gfp);
11469ab86bbcSShirley Ma 	if (!first) {
1147e9d7417bSJason Wang 		give_pages(rq, list);
11489ab86bbcSShirley Ma 		return -ENOMEM;
11499ab86bbcSShirley Ma 	}
11509ab86bbcSShirley Ma 	p = page_address(first);
11519ab86bbcSShirley Ma 
1152e9d7417bSJason Wang 	/* rq->sg[0], rq->sg[1] share the same page */
1153012873d0SMichael S. Tsirkin 	/* a separated rq->sg[0] for header - required in case !any_header_sg */
1154012873d0SMichael S. Tsirkin 	sg_set_buf(&rq->sg[0], p, vi->hdr_len);
11559ab86bbcSShirley Ma 
1156e9d7417bSJason Wang 	/* rq->sg[1] for data packet, from offset */
11579ab86bbcSShirley Ma 	offset = sizeof(struct padded_vnet_hdr);
1158e9d7417bSJason Wang 	sg_set_buf(&rq->sg[1], p + offset, PAGE_SIZE - offset);
11599ab86bbcSShirley Ma 
11609ab86bbcSShirley Ma 	/* chain first in list head */
11619ab86bbcSShirley Ma 	first->private = (unsigned long)list;
11629dc7b9e4SRusty Russell 	err = virtqueue_add_inbuf(rq->vq, rq->sg, MAX_SKB_FRAGS + 2,
1163aa989f5eSMichael S. Tsirkin 				  first, gfp);
11649ab86bbcSShirley Ma 	if (err < 0)
1165e9d7417bSJason Wang 		give_pages(rq, first);
11669ab86bbcSShirley Ma 
11679ab86bbcSShirley Ma 	return err;
11689ab86bbcSShirley Ma }
11699ab86bbcSShirley Ma 
1170d85b758fSMichael S. Tsirkin static unsigned int get_mergeable_buf_len(struct receive_queue *rq,
11713cc81a9aSJason Wang 					  struct ewma_pkt_len *avg_pkt_len,
11723cc81a9aSJason Wang 					  unsigned int room)
11739ab86bbcSShirley Ma {
1174ab7db917SMichael Dalton 	const size_t hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1175fbf28d78SMichael Dalton 	unsigned int len;
1176fbf28d78SMichael Dalton 
11773cc81a9aSJason Wang 	if (room)
11783cc81a9aSJason Wang 		return PAGE_SIZE - room;
11793cc81a9aSJason Wang 
11805377d758SJohannes Berg 	len = hdr_len +	clamp_t(unsigned int, ewma_pkt_len_read(avg_pkt_len),
1181f0c3192cSMichael S. Tsirkin 				rq->min_buf_len, PAGE_SIZE - hdr_len);
11823cc81a9aSJason Wang 
1183e377fcc8SMichael S. Tsirkin 	return ALIGN(len, L1_CACHE_BYTES);
1184fbf28d78SMichael Dalton }
1185fbf28d78SMichael Dalton 
11862de2f7f4SJohn Fastabend static int add_recvbuf_mergeable(struct virtnet_info *vi,
11872de2f7f4SJohn Fastabend 				 struct receive_queue *rq, gfp_t gfp)
1188fbf28d78SMichael Dalton {
1189fb51879dSMichael Dalton 	struct page_frag *alloc_frag = &rq->alloc_frag;
11902de2f7f4SJohn Fastabend 	unsigned int headroom = virtnet_get_headroom(vi);
11913cc81a9aSJason Wang 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
11923cc81a9aSJason Wang 	unsigned int room = SKB_DATA_ALIGN(headroom + tailroom);
1193fb51879dSMichael Dalton 	char *buf;
1194680557cfSMichael S. Tsirkin 	void *ctx;
11959ab86bbcSShirley Ma 	int err;
1196fb51879dSMichael Dalton 	unsigned int len, hole;
11979ab86bbcSShirley Ma 
11983cc81a9aSJason Wang 	/* Extra tailroom is needed to satisfy XDP's assumption. This
11993cc81a9aSJason Wang 	 * means rx frags coalescing won't work, but consider we've
12003cc81a9aSJason Wang 	 * disabled GSO for XDP, it won't be a big issue.
12013cc81a9aSJason Wang 	 */
12023cc81a9aSJason Wang 	len = get_mergeable_buf_len(rq, &rq->mrg_avg_pkt_len, room);
12033cc81a9aSJason Wang 	if (unlikely(!skb_page_frag_refill(len + room, alloc_frag, gfp)))
12049ab86bbcSShirley Ma 		return -ENOMEM;
1205ab7db917SMichael Dalton 
1206fb51879dSMichael Dalton 	buf = (char *)page_address(alloc_frag->page) + alloc_frag->offset;
12072de2f7f4SJohn Fastabend 	buf += headroom; /* advance address leaving hole at front of pkt */
1208fb51879dSMichael Dalton 	get_page(alloc_frag->page);
12093cc81a9aSJason Wang 	alloc_frag->offset += len + room;
1210fb51879dSMichael Dalton 	hole = alloc_frag->size - alloc_frag->offset;
12113cc81a9aSJason Wang 	if (hole < len + room) {
1212ab7db917SMichael Dalton 		/* To avoid internal fragmentation, if there is very likely not
1213ab7db917SMichael Dalton 		 * enough space for another buffer, add the remaining space to
12141daa8790SMichael S. Tsirkin 		 * the current buffer.
1215ab7db917SMichael Dalton 		 */
1216fb51879dSMichael Dalton 		len += hole;
1217fb51879dSMichael Dalton 		alloc_frag->offset += hole;
1218fb51879dSMichael Dalton 	}
12199ab86bbcSShirley Ma 
1220fb51879dSMichael Dalton 	sg_init_one(rq->sg, buf, len);
122129fda25aSDavid S. Miller 	ctx = mergeable_len_to_ctx(len, headroom);
1222680557cfSMichael S. Tsirkin 	err = virtqueue_add_inbuf_ctx(rq->vq, rq->sg, 1, buf, ctx, gfp);
12239ab86bbcSShirley Ma 	if (err < 0)
12242613af0eSMichael Dalton 		put_page(virt_to_head_page(buf));
12259ab86bbcSShirley Ma 
12269ab86bbcSShirley Ma 	return err;
1227296f96fcSRusty Russell }
1228296f96fcSRusty Russell 
1229b2baed69SRusty Russell /*
1230b2baed69SRusty Russell  * Returns false if we couldn't fill entirely (OOM).
1231b2baed69SRusty Russell  *
1232b2baed69SRusty Russell  * Normally run in the receive path, but can also be run from ndo_open
1233b2baed69SRusty Russell  * before we're receiving packets, or from refill_work which is
1234b2baed69SRusty Russell  * careful to disable receiving (using napi_disable).
1235b2baed69SRusty Russell  */
1236946fa564SMichael S. Tsirkin static bool try_fill_recv(struct virtnet_info *vi, struct receive_queue *rq,
1237946fa564SMichael S. Tsirkin 			  gfp_t gfp)
12383f2c31d9SMark McLoughlin {
12393f2c31d9SMark McLoughlin 	int err;
12401788f495SMichael S. Tsirkin 	bool oom;
12413f2c31d9SMark McLoughlin 
12420aea51c3SAmit Shah 	do {
12439ab86bbcSShirley Ma 		if (vi->mergeable_rx_bufs)
12442de2f7f4SJohn Fastabend 			err = add_recvbuf_mergeable(vi, rq, gfp);
12459ab86bbcSShirley Ma 		else if (vi->big_packets)
1246012873d0SMichael S. Tsirkin 			err = add_recvbuf_big(vi, rq, gfp);
12479ab86bbcSShirley Ma 		else
1248946fa564SMichael S. Tsirkin 			err = add_recvbuf_small(vi, rq, gfp);
12493f2c31d9SMark McLoughlin 
12501788f495SMichael S. Tsirkin 		oom = err == -ENOMEM;
12519ed4cb07SRusty Russell 		if (err)
12523f2c31d9SMark McLoughlin 			break;
1253b7dfde95SLinus Torvalds 	} while (rq->vq->num_free);
1254461f03dcSToshiaki Makita 	if (virtqueue_kick_prepare(rq->vq) && virtqueue_notify(rq->vq)) {
125501c32598SMichael S. Tsirkin 		unsigned long flags;
125601c32598SMichael S. Tsirkin 
125701c32598SMichael S. Tsirkin 		flags = u64_stats_update_begin_irqsave(&rq->stats.syncp);
1258d46eeeafSJason Wang 		rq->stats.kicks++;
125901c32598SMichael S. Tsirkin 		u64_stats_update_end_irqrestore(&rq->stats.syncp, flags);
1260461f03dcSToshiaki Makita 	}
1261461f03dcSToshiaki Makita 
12623161e453SRusty Russell 	return !oom;
12633f2c31d9SMark McLoughlin }
12643f2c31d9SMark McLoughlin 
126518445c4dSRusty Russell static void skb_recv_done(struct virtqueue *rvq)
1266296f96fcSRusty Russell {
1267296f96fcSRusty Russell 	struct virtnet_info *vi = rvq->vdev->priv;
1268986a4f4dSJason Wang 	struct receive_queue *rq = &vi->rq[vq2rxq(rvq)];
1269e9d7417bSJason Wang 
1270e4e8452aSWillem de Bruijn 	virtqueue_napi_schedule(&rq->napi, rvq);
1271296f96fcSRusty Russell }
1272296f96fcSRusty Russell 
1273e4e8452aSWillem de Bruijn static void virtnet_napi_enable(struct virtqueue *vq, struct napi_struct *napi)
12743e9d08ecSBruce Rogers {
1275e4e8452aSWillem de Bruijn 	napi_enable(napi);
12763e9d08ecSBruce Rogers 
12773e9d08ecSBruce Rogers 	/* If all buffers were filled by other side before we napi_enabled, we
1278e4e8452aSWillem de Bruijn 	 * won't get another interrupt, so process any outstanding packets now.
1279e4e8452aSWillem de Bruijn 	 * Call local_bh_enable after to trigger softIRQ processing.
1280e4e8452aSWillem de Bruijn 	 */
1281ec13ee80SMichael S. Tsirkin 	local_bh_disable();
1282e4e8452aSWillem de Bruijn 	virtqueue_napi_schedule(napi, vq);
1283ec13ee80SMichael S. Tsirkin 	local_bh_enable();
12843e9d08ecSBruce Rogers }
12853e9d08ecSBruce Rogers 
1286b92f1e67SWillem de Bruijn static void virtnet_napi_tx_enable(struct virtnet_info *vi,
1287b92f1e67SWillem de Bruijn 				   struct virtqueue *vq,
1288b92f1e67SWillem de Bruijn 				   struct napi_struct *napi)
1289b92f1e67SWillem de Bruijn {
1290b92f1e67SWillem de Bruijn 	if (!napi->weight)
1291b92f1e67SWillem de Bruijn 		return;
1292b92f1e67SWillem de Bruijn 
1293b92f1e67SWillem de Bruijn 	/* Tx napi touches cachelines on the cpu handling tx interrupts. Only
1294b92f1e67SWillem de Bruijn 	 * enable the feature if this is likely affine with the transmit path.
1295b92f1e67SWillem de Bruijn 	 */
1296b92f1e67SWillem de Bruijn 	if (!vi->affinity_hint_set) {
1297b92f1e67SWillem de Bruijn 		napi->weight = 0;
1298b92f1e67SWillem de Bruijn 		return;
1299b92f1e67SWillem de Bruijn 	}
1300b92f1e67SWillem de Bruijn 
1301b92f1e67SWillem de Bruijn 	return virtnet_napi_enable(vq, napi);
1302b92f1e67SWillem de Bruijn }
1303b92f1e67SWillem de Bruijn 
130478a57b48SWillem de Bruijn static void virtnet_napi_tx_disable(struct napi_struct *napi)
130578a57b48SWillem de Bruijn {
130678a57b48SWillem de Bruijn 	if (napi->weight)
130778a57b48SWillem de Bruijn 		napi_disable(napi);
130878a57b48SWillem de Bruijn }
130978a57b48SWillem de Bruijn 
13103161e453SRusty Russell static void refill_work(struct work_struct *work)
13113161e453SRusty Russell {
1312e9d7417bSJason Wang 	struct virtnet_info *vi =
1313e9d7417bSJason Wang 		container_of(work, struct virtnet_info, refill.work);
13143161e453SRusty Russell 	bool still_empty;
1315986a4f4dSJason Wang 	int i;
13163161e453SRusty Russell 
131755257d72SSasha Levin 	for (i = 0; i < vi->curr_queue_pairs; i++) {
1318986a4f4dSJason Wang 		struct receive_queue *rq = &vi->rq[i];
1319986a4f4dSJason Wang 
1320986a4f4dSJason Wang 		napi_disable(&rq->napi);
1321946fa564SMichael S. Tsirkin 		still_empty = !try_fill_recv(vi, rq, GFP_KERNEL);
1322e4e8452aSWillem de Bruijn 		virtnet_napi_enable(rq->vq, &rq->napi);
13233161e453SRusty Russell 
13243161e453SRusty Russell 		/* In theory, this can happen: if we don't get any buffers in
1325986a4f4dSJason Wang 		 * we will *never* try to fill again.
1326986a4f4dSJason Wang 		 */
13273161e453SRusty Russell 		if (still_empty)
13283b07e9caSTejun Heo 			schedule_delayed_work(&vi->refill, HZ/2);
13293161e453SRusty Russell 	}
1330986a4f4dSJason Wang }
13313161e453SRusty Russell 
13322471c75eSJesper Dangaard Brouer static int virtnet_receive(struct receive_queue *rq, int budget,
13332471c75eSJesper Dangaard Brouer 			   unsigned int *xdp_xmit)
1334296f96fcSRusty Russell {
1335e9d7417bSJason Wang 	struct virtnet_info *vi = rq->vq->vdev->priv;
1336d46eeeafSJason Wang 	struct virtnet_rq_stats stats = {};
1337a0929a44SToshiaki Makita 	unsigned int len;
13389ab86bbcSShirley Ma 	void *buf;
1339a0929a44SToshiaki Makita 	int i;
1340296f96fcSRusty Russell 
1341192f68cfSJason Wang 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
1342680557cfSMichael S. Tsirkin 		void *ctx;
1343680557cfSMichael S. Tsirkin 
1344d46eeeafSJason Wang 		while (stats.packets < budget &&
1345680557cfSMichael S. Tsirkin 		       (buf = virtqueue_get_buf_ctx(rq->vq, &len, &ctx))) {
1346a0929a44SToshiaki Makita 			receive_buf(vi, rq, buf, len, ctx, xdp_xmit, &stats);
1347d46eeeafSJason Wang 			stats.packets++;
1348680557cfSMichael S. Tsirkin 		}
1349680557cfSMichael S. Tsirkin 	} else {
1350d46eeeafSJason Wang 		while (stats.packets < budget &&
1351e9d7417bSJason Wang 		       (buf = virtqueue_get_buf(rq->vq, &len)) != NULL) {
1352a0929a44SToshiaki Makita 			receive_buf(vi, rq, buf, len, NULL, xdp_xmit, &stats);
1353d46eeeafSJason Wang 			stats.packets++;
1354296f96fcSRusty Russell 		}
1355680557cfSMichael S. Tsirkin 	}
1356296f96fcSRusty Russell 
1357718be6baS? jiang 	if (rq->vq->num_free > min((unsigned int)budget, virtqueue_get_vring_size(rq->vq)) / 2) {
1358946fa564SMichael S. Tsirkin 		if (!try_fill_recv(vi, rq, GFP_ATOMIC))
13593b07e9caSTejun Heo 			schedule_delayed_work(&vi->refill, 0);
13603161e453SRusty Russell 	}
1361296f96fcSRusty Russell 
1362d7dfc5cfSToshiaki Makita 	u64_stats_update_begin(&rq->stats.syncp);
1363a0929a44SToshiaki Makita 	for (i = 0; i < VIRTNET_RQ_STATS_LEN; i++) {
1364a0929a44SToshiaki Makita 		size_t offset = virtnet_rq_stats_desc[i].offset;
1365a0929a44SToshiaki Makita 		u64 *item;
1366a0929a44SToshiaki Makita 
1367d46eeeafSJason Wang 		item = (u64 *)((u8 *)&rq->stats + offset);
1368d46eeeafSJason Wang 		*item += *(u64 *)((u8 *)&stats + offset);
1369a0929a44SToshiaki Makita 	}
1370d7dfc5cfSToshiaki Makita 	u64_stats_update_end(&rq->stats.syncp);
137161845d20SJason Wang 
1372d46eeeafSJason Wang 	return stats.packets;
13732ffa7598SJason Wang }
13742ffa7598SJason Wang 
1375df133f3fSMichael S. Tsirkin static void free_old_xmit_skbs(struct send_queue *sq, bool in_napi)
1376ea7735d9SWillem de Bruijn {
1377ea7735d9SWillem de Bruijn 	unsigned int len;
1378ea7735d9SWillem de Bruijn 	unsigned int packets = 0;
1379ea7735d9SWillem de Bruijn 	unsigned int bytes = 0;
13805050471dSToshiaki Makita 	void *ptr;
1381ea7735d9SWillem de Bruijn 
13825050471dSToshiaki Makita 	while ((ptr = virtqueue_get_buf(sq->vq, &len)) != NULL) {
13835050471dSToshiaki Makita 		if (likely(!is_xdp_frame(ptr))) {
13845050471dSToshiaki Makita 			struct sk_buff *skb = ptr;
13855050471dSToshiaki Makita 
1386ea7735d9SWillem de Bruijn 			pr_debug("Sent skb %p\n", skb);
1387ea7735d9SWillem de Bruijn 
1388ea7735d9SWillem de Bruijn 			bytes += skb->len;
1389df133f3fSMichael S. Tsirkin 			napi_consume_skb(skb, in_napi);
13905050471dSToshiaki Makita 		} else {
13915050471dSToshiaki Makita 			struct xdp_frame *frame = ptr_to_xdp(ptr);
13925050471dSToshiaki Makita 
13935050471dSToshiaki Makita 			bytes += frame->len;
13945050471dSToshiaki Makita 			xdp_return_frame(frame);
13955050471dSToshiaki Makita 		}
13965050471dSToshiaki Makita 		packets++;
1397ea7735d9SWillem de Bruijn 	}
1398ea7735d9SWillem de Bruijn 
1399ea7735d9SWillem de Bruijn 	/* Avoid overhead when no packets have been processed
1400ea7735d9SWillem de Bruijn 	 * happens when called speculatively from start_xmit.
1401ea7735d9SWillem de Bruijn 	 */
1402ea7735d9SWillem de Bruijn 	if (!packets)
1403ea7735d9SWillem de Bruijn 		return;
1404ea7735d9SWillem de Bruijn 
1405d7dfc5cfSToshiaki Makita 	u64_stats_update_begin(&sq->stats.syncp);
1406d7dfc5cfSToshiaki Makita 	sq->stats.bytes += bytes;
1407d7dfc5cfSToshiaki Makita 	sq->stats.packets += packets;
1408d7dfc5cfSToshiaki Makita 	u64_stats_update_end(&sq->stats.syncp);
1409ea7735d9SWillem de Bruijn }
1410ea7735d9SWillem de Bruijn 
1411534da5e8SToshiaki Makita static bool is_xdp_raw_buffer_queue(struct virtnet_info *vi, int q)
1412534da5e8SToshiaki Makita {
1413534da5e8SToshiaki Makita 	if (q < (vi->curr_queue_pairs - vi->xdp_queue_pairs))
1414534da5e8SToshiaki Makita 		return false;
1415534da5e8SToshiaki Makita 	else if (q < vi->curr_queue_pairs)
1416534da5e8SToshiaki Makita 		return true;
1417534da5e8SToshiaki Makita 	else
1418534da5e8SToshiaki Makita 		return false;
1419534da5e8SToshiaki Makita }
1420534da5e8SToshiaki Makita 
14217b0411efSWillem de Bruijn static void virtnet_poll_cleantx(struct receive_queue *rq)
14227b0411efSWillem de Bruijn {
14237b0411efSWillem de Bruijn 	struct virtnet_info *vi = rq->vq->vdev->priv;
14247b0411efSWillem de Bruijn 	unsigned int index = vq2rxq(rq->vq);
14257b0411efSWillem de Bruijn 	struct send_queue *sq = &vi->sq[index];
14267b0411efSWillem de Bruijn 	struct netdev_queue *txq = netdev_get_tx_queue(vi->dev, index);
14277b0411efSWillem de Bruijn 
1428534da5e8SToshiaki Makita 	if (!sq->napi.weight || is_xdp_raw_buffer_queue(vi, index))
14297b0411efSWillem de Bruijn 		return;
14307b0411efSWillem de Bruijn 
14317b0411efSWillem de Bruijn 	if (__netif_tx_trylock(txq)) {
1432df133f3fSMichael S. Tsirkin 		free_old_xmit_skbs(sq, true);
14337b0411efSWillem de Bruijn 		__netif_tx_unlock(txq);
14347b0411efSWillem de Bruijn 	}
14357b0411efSWillem de Bruijn 
14367b0411efSWillem de Bruijn 	if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
14377b0411efSWillem de Bruijn 		netif_tx_wake_queue(txq);
14387b0411efSWillem de Bruijn }
14397b0411efSWillem de Bruijn 
14402ffa7598SJason Wang static int virtnet_poll(struct napi_struct *napi, int budget)
14412ffa7598SJason Wang {
14422ffa7598SJason Wang 	struct receive_queue *rq =
14432ffa7598SJason Wang 		container_of(napi, struct receive_queue, napi);
14449267c430SJason Wang 	struct virtnet_info *vi = rq->vq->vdev->priv;
14459267c430SJason Wang 	struct send_queue *sq;
14462a43565cSToshiaki Makita 	unsigned int received;
14472471c75eSJesper Dangaard Brouer 	unsigned int xdp_xmit = 0;
14482ffa7598SJason Wang 
14497b0411efSWillem de Bruijn 	virtnet_poll_cleantx(rq);
14507b0411efSWillem de Bruijn 
1451186b3c99SJason Wang 	received = virtnet_receive(rq, budget, &xdp_xmit);
14522ffa7598SJason Wang 
14538329d98eSRusty Russell 	/* Out of packets? */
1454e4e8452aSWillem de Bruijn 	if (received < budget)
1455e4e8452aSWillem de Bruijn 		virtqueue_napi_complete(napi, rq->vq, received);
1456296f96fcSRusty Russell 
14572471c75eSJesper Dangaard Brouer 	if (xdp_xmit & VIRTIO_XDP_REDIR)
14581d233886SToke Høiland-Jørgensen 		xdp_do_flush();
14592471c75eSJesper Dangaard Brouer 
14602471c75eSJesper Dangaard Brouer 	if (xdp_xmit & VIRTIO_XDP_TX) {
14612a43565cSToshiaki Makita 		sq = virtnet_xdp_sq(vi);
1462461f03dcSToshiaki Makita 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1463461f03dcSToshiaki Makita 			u64_stats_update_begin(&sq->stats.syncp);
1464461f03dcSToshiaki Makita 			sq->stats.kicks++;
1465461f03dcSToshiaki Makita 			u64_stats_update_end(&sq->stats.syncp);
1466461f03dcSToshiaki Makita 		}
14679267c430SJason Wang 	}
1468186b3c99SJason Wang 
1469296f96fcSRusty Russell 	return received;
1470296f96fcSRusty Russell }
1471296f96fcSRusty Russell 
1472986a4f4dSJason Wang static int virtnet_open(struct net_device *dev)
1473986a4f4dSJason Wang {
1474986a4f4dSJason Wang 	struct virtnet_info *vi = netdev_priv(dev);
1475754b8a21SJesper Dangaard Brouer 	int i, err;
1476986a4f4dSJason Wang 
1477e4166625SJason Wang 	for (i = 0; i < vi->max_queue_pairs; i++) {
1478e4166625SJason Wang 		if (i < vi->curr_queue_pairs)
1479986a4f4dSJason Wang 			/* Make sure we have some buffers: if oom use wq. */
1480946fa564SMichael S. Tsirkin 			if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
1481986a4f4dSJason Wang 				schedule_delayed_work(&vi->refill, 0);
1482754b8a21SJesper Dangaard Brouer 
1483754b8a21SJesper Dangaard Brouer 		err = xdp_rxq_info_reg(&vi->rq[i].xdp_rxq, dev, i);
1484754b8a21SJesper Dangaard Brouer 		if (err < 0)
1485754b8a21SJesper Dangaard Brouer 			return err;
1486754b8a21SJesper Dangaard Brouer 
14878d5d8852SJesper Dangaard Brouer 		err = xdp_rxq_info_reg_mem_model(&vi->rq[i].xdp_rxq,
14888d5d8852SJesper Dangaard Brouer 						 MEM_TYPE_PAGE_SHARED, NULL);
14898d5d8852SJesper Dangaard Brouer 		if (err < 0) {
14908d5d8852SJesper Dangaard Brouer 			xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
14918d5d8852SJesper Dangaard Brouer 			return err;
14928d5d8852SJesper Dangaard Brouer 		}
14938d5d8852SJesper Dangaard Brouer 
1494e4e8452aSWillem de Bruijn 		virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
1495b92f1e67SWillem de Bruijn 		virtnet_napi_tx_enable(vi, vi->sq[i].vq, &vi->sq[i].napi);
1496986a4f4dSJason Wang 	}
1497986a4f4dSJason Wang 
1498986a4f4dSJason Wang 	return 0;
1499986a4f4dSJason Wang }
1500986a4f4dSJason Wang 
1501b92f1e67SWillem de Bruijn static int virtnet_poll_tx(struct napi_struct *napi, int budget)
1502b92f1e67SWillem de Bruijn {
1503b92f1e67SWillem de Bruijn 	struct send_queue *sq = container_of(napi, struct send_queue, napi);
1504b92f1e67SWillem de Bruijn 	struct virtnet_info *vi = sq->vq->vdev->priv;
1505534da5e8SToshiaki Makita 	unsigned int index = vq2txq(sq->vq);
1506534da5e8SToshiaki Makita 	struct netdev_queue *txq;
1507b92f1e67SWillem de Bruijn 
1508534da5e8SToshiaki Makita 	if (unlikely(is_xdp_raw_buffer_queue(vi, index))) {
1509534da5e8SToshiaki Makita 		/* We don't need to enable cb for XDP */
1510534da5e8SToshiaki Makita 		napi_complete_done(napi, 0);
1511534da5e8SToshiaki Makita 		return 0;
1512534da5e8SToshiaki Makita 	}
1513534da5e8SToshiaki Makita 
1514534da5e8SToshiaki Makita 	txq = netdev_get_tx_queue(vi->dev, index);
1515b92f1e67SWillem de Bruijn 	__netif_tx_lock(txq, raw_smp_processor_id());
1516df133f3fSMichael S. Tsirkin 	free_old_xmit_skbs(sq, true);
1517b92f1e67SWillem de Bruijn 	__netif_tx_unlock(txq);
1518b92f1e67SWillem de Bruijn 
1519b92f1e67SWillem de Bruijn 	virtqueue_napi_complete(napi, sq->vq, 0);
1520b92f1e67SWillem de Bruijn 
1521b92f1e67SWillem de Bruijn 	if (sq->vq->num_free >= 2 + MAX_SKB_FRAGS)
1522b92f1e67SWillem de Bruijn 		netif_tx_wake_queue(txq);
1523b92f1e67SWillem de Bruijn 
1524b92f1e67SWillem de Bruijn 	return 0;
1525b92f1e67SWillem de Bruijn }
1526b92f1e67SWillem de Bruijn 
1527e9d7417bSJason Wang static int xmit_skb(struct send_queue *sq, struct sk_buff *skb)
1528296f96fcSRusty Russell {
1529012873d0SMichael S. Tsirkin 	struct virtio_net_hdr_mrg_rxbuf *hdr;
1530296f96fcSRusty Russell 	const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
1531e9d7417bSJason Wang 	struct virtnet_info *vi = sq->vq->vdev->priv;
1532e2fcad58SJason A. Donenfeld 	int num_sg;
1533012873d0SMichael S. Tsirkin 	unsigned hdr_len = vi->hdr_len;
1534e7428e95SMichael S. Tsirkin 	bool can_push;
1535296f96fcSRusty Russell 
1536e174961cSJohannes Berg 	pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
1537e7428e95SMichael S. Tsirkin 
1538e7428e95SMichael S. Tsirkin 	can_push = vi->any_header_sg &&
1539e7428e95SMichael S. Tsirkin 		!((unsigned long)skb->data & (__alignof__(*hdr) - 1)) &&
1540e7428e95SMichael S. Tsirkin 		!skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len;
1541e7428e95SMichael S. Tsirkin 	/* Even if we can, don't push here yet as this would skew
1542e7428e95SMichael S. Tsirkin 	 * csum_start offset below. */
1543e7428e95SMichael S. Tsirkin 	if (can_push)
1544012873d0SMichael S. Tsirkin 		hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len);
1545e7428e95SMichael S. Tsirkin 	else
1546e7428e95SMichael S. Tsirkin 		hdr = skb_vnet_hdr(skb);
1547296f96fcSRusty Russell 
1548e858fae2SMike Rapoport 	if (virtio_net_hdr_from_skb(skb, &hdr->hdr,
1549fd3a8862SWillem de Bruijn 				    virtio_is_little_endian(vi->vdev), false,
1550fd3a8862SWillem de Bruijn 				    0))
1551296f96fcSRusty Russell 		BUG();
1552296f96fcSRusty Russell 
1553e7428e95SMichael S. Tsirkin 	if (vi->mergeable_rx_bufs)
1554012873d0SMichael S. Tsirkin 		hdr->num_buffers = 0;
15553f2c31d9SMark McLoughlin 
1556547c890cSJason Wang 	sg_init_table(sq->sg, skb_shinfo(skb)->nr_frags + (can_push ? 1 : 2));
1557e7428e95SMichael S. Tsirkin 	if (can_push) {
1558e7428e95SMichael S. Tsirkin 		__skb_push(skb, hdr_len);
1559e7428e95SMichael S. Tsirkin 		num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len);
1560e2fcad58SJason A. Donenfeld 		if (unlikely(num_sg < 0))
1561e2fcad58SJason A. Donenfeld 			return num_sg;
1562e7428e95SMichael S. Tsirkin 		/* Pull header back to avoid skew in tx bytes calculations. */
1563e7428e95SMichael S. Tsirkin 		__skb_pull(skb, hdr_len);
1564e7428e95SMichael S. Tsirkin 	} else {
1565e7428e95SMichael S. Tsirkin 		sg_set_buf(sq->sg, hdr, hdr_len);
1566e2fcad58SJason A. Donenfeld 		num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len);
1567e2fcad58SJason A. Donenfeld 		if (unlikely(num_sg < 0))
1568e2fcad58SJason A. Donenfeld 			return num_sg;
1569e2fcad58SJason A. Donenfeld 		num_sg++;
1570e7428e95SMichael S. Tsirkin 	}
15719dc7b9e4SRusty Russell 	return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC);
157211a3a154SRusty Russell }
157311a3a154SRusty Russell 
1574424efe9cSStephen Hemminger static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
157599ffc696SRusty Russell {
157699ffc696SRusty Russell 	struct virtnet_info *vi = netdev_priv(dev);
1577986a4f4dSJason Wang 	int qnum = skb_get_queue_mapping(skb);
1578986a4f4dSJason Wang 	struct send_queue *sq = &vi->sq[qnum];
15799ed4cb07SRusty Russell 	int err;
15804b7fd2e6SMichael S. Tsirkin 	struct netdev_queue *txq = netdev_get_tx_queue(dev, qnum);
15816b16f9eeSFlorian Westphal 	bool kick = !netdev_xmit_more();
1582b92f1e67SWillem de Bruijn 	bool use_napi = sq->napi.weight;
15832cb9c6baSRusty Russell 
15842cb9c6baSRusty Russell 	/* Free up any pending old buffers before queueing new ones. */
1585df133f3fSMichael S. Tsirkin 	free_old_xmit_skbs(sq, false);
158699ffc696SRusty Russell 
1587bdb12e0dSWillem de Bruijn 	if (use_napi && kick)
1588bdb12e0dSWillem de Bruijn 		virtqueue_enable_cb_delayed(sq->vq);
1589bdb12e0dSWillem de Bruijn 
1590074c3582SJacob Keller 	/* timestamp packet in software */
1591074c3582SJacob Keller 	skb_tx_timestamp(skb);
1592074c3582SJacob Keller 
159303f191baSMichael S. Tsirkin 	/* Try to transmit */
1594b7dfde95SLinus Torvalds 	err = xmit_skb(sq, skb);
159599ffc696SRusty Russell 
15969ed4cb07SRusty Russell 	/* This should not happen! */
1597681daee2SJason Wang 	if (unlikely(err)) {
159858eba97dSRusty Russell 		dev->stats.tx_fifo_errors++;
15992e57b79cSRick Jones 		if (net_ratelimit())
160058eba97dSRusty Russell 			dev_warn(&dev->dev,
16017934b481SYuval Shaia 				 "Unexpected TXQ (%d) queue failure: %d\n",
16027934b481SYuval Shaia 				 qnum, err);
160358eba97dSRusty Russell 		dev->stats.tx_dropped++;
160485e94525SEric W. Biederman 		dev_kfree_skb_any(skb);
160558eba97dSRusty Russell 		return NETDEV_TX_OK;
1606296f96fcSRusty Russell 	}
160703f191baSMichael S. Tsirkin 
160848925e37SRusty Russell 	/* Don't wait up for transmitted skbs to be freed. */
1609b92f1e67SWillem de Bruijn 	if (!use_napi) {
161048925e37SRusty Russell 		skb_orphan(skb);
1611895b5c9fSFlorian Westphal 		nf_reset_ct(skb);
1612b92f1e67SWillem de Bruijn 	}
161348925e37SRusty Russell 
161460302ff6SMichael S. Tsirkin 	/* If running out of space, stop queue to avoid getting packets that we
161560302ff6SMichael S. Tsirkin 	 * are then unable to transmit.
161660302ff6SMichael S. Tsirkin 	 * An alternative would be to force queuing layer to requeue the skb by
161760302ff6SMichael S. Tsirkin 	 * returning NETDEV_TX_BUSY. However, NETDEV_TX_BUSY should not be
161860302ff6SMichael S. Tsirkin 	 * returned in a normal path of operation: it means that driver is not
161960302ff6SMichael S. Tsirkin 	 * maintaining the TX queue stop/start state properly, and causes
162060302ff6SMichael S. Tsirkin 	 * the stack to do a non-trivial amount of useless work.
162160302ff6SMichael S. Tsirkin 	 * Since most packets only take 1 or 2 ring slots, stopping the queue
162260302ff6SMichael S. Tsirkin 	 * early means 16 slots are typically wasted.
1623d631b94eSstephen hemminger 	 */
1624b7dfde95SLinus Torvalds 	if (sq->vq->num_free < 2+MAX_SKB_FRAGS) {
1625986a4f4dSJason Wang 		netif_stop_subqueue(dev, qnum);
1626b92f1e67SWillem de Bruijn 		if (!use_napi &&
1627b92f1e67SWillem de Bruijn 		    unlikely(!virtqueue_enable_cb_delayed(sq->vq))) {
162848925e37SRusty Russell 			/* More just got used, free them then recheck. */
1629df133f3fSMichael S. Tsirkin 			free_old_xmit_skbs(sq, false);
1630b7dfde95SLinus Torvalds 			if (sq->vq->num_free >= 2+MAX_SKB_FRAGS) {
1631986a4f4dSJason Wang 				netif_start_subqueue(dev, qnum);
1632e9d7417bSJason Wang 				virtqueue_disable_cb(sq->vq);
163348925e37SRusty Russell 			}
163448925e37SRusty Russell 		}
163548925e37SRusty Russell 	}
163648925e37SRusty Russell 
1637461f03dcSToshiaki Makita 	if (kick || netif_xmit_stopped(txq)) {
1638461f03dcSToshiaki Makita 		if (virtqueue_kick_prepare(sq->vq) && virtqueue_notify(sq->vq)) {
1639461f03dcSToshiaki Makita 			u64_stats_update_begin(&sq->stats.syncp);
1640461f03dcSToshiaki Makita 			sq->stats.kicks++;
1641461f03dcSToshiaki Makita 			u64_stats_update_end(&sq->stats.syncp);
1642461f03dcSToshiaki Makita 		}
1643461f03dcSToshiaki Makita 	}
16440b725a2cSDavid S. Miller 
16450b725a2cSDavid S. Miller 	return NETDEV_TX_OK;
1646c223a078SDavid S. Miller }
1647c223a078SDavid S. Miller 
164840cbfc37SAmos Kong /*
164940cbfc37SAmos Kong  * Send command via the control virtqueue and check status.  Commands
165040cbfc37SAmos Kong  * supported by the hypervisor, as indicated by feature bits, should
1651788a8b6dSstephen hemminger  * never fail unless improperly formatted.
165240cbfc37SAmos Kong  */
165340cbfc37SAmos Kong static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
1654d24bae32Sstephen hemminger 				 struct scatterlist *out)
165540cbfc37SAmos Kong {
1656f7bc9594SRusty Russell 	struct scatterlist *sgs[4], hdr, stat;
1657d24bae32Sstephen hemminger 	unsigned out_num = 0, tmp;
165840cbfc37SAmos Kong 
165940cbfc37SAmos Kong 	/* Caller should know better */
1660f7bc9594SRusty Russell 	BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ));
166140cbfc37SAmos Kong 
166212e57169SMichael S. Tsirkin 	vi->ctrl->status = ~0;
166312e57169SMichael S. Tsirkin 	vi->ctrl->hdr.class = class;
166412e57169SMichael S. Tsirkin 	vi->ctrl->hdr.cmd = cmd;
1665f7bc9594SRusty Russell 	/* Add header */
166612e57169SMichael S. Tsirkin 	sg_init_one(&hdr, &vi->ctrl->hdr, sizeof(vi->ctrl->hdr));
1667f7bc9594SRusty Russell 	sgs[out_num++] = &hdr;
166840cbfc37SAmos Kong 
1669f7bc9594SRusty Russell 	if (out)
1670f7bc9594SRusty Russell 		sgs[out_num++] = out;
167140cbfc37SAmos Kong 
1672f7bc9594SRusty Russell 	/* Add return status. */
167312e57169SMichael S. Tsirkin 	sg_init_one(&stat, &vi->ctrl->status, sizeof(vi->ctrl->status));
1674d24bae32Sstephen hemminger 	sgs[out_num] = &stat;
167540cbfc37SAmos Kong 
1676d24bae32Sstephen hemminger 	BUG_ON(out_num + 1 > ARRAY_SIZE(sgs));
1677a7c58146SRusty Russell 	virtqueue_add_sgs(vi->cvq, sgs, out_num, 1, vi, GFP_ATOMIC);
167840cbfc37SAmos Kong 
167967975901SHeinz Graalfs 	if (unlikely(!virtqueue_kick(vi->cvq)))
168012e57169SMichael S. Tsirkin 		return vi->ctrl->status == VIRTIO_NET_OK;
168140cbfc37SAmos Kong 
168240cbfc37SAmos Kong 	/* Spin for a response, the kick causes an ioport write, trapping
168340cbfc37SAmos Kong 	 * into the hypervisor, so the request should be handled immediately.
168440cbfc37SAmos Kong 	 */
1685047b9b94SHeinz Graalfs 	while (!virtqueue_get_buf(vi->cvq, &tmp) &&
1686047b9b94SHeinz Graalfs 	       !virtqueue_is_broken(vi->cvq))
168740cbfc37SAmos Kong 		cpu_relax();
168840cbfc37SAmos Kong 
168912e57169SMichael S. Tsirkin 	return vi->ctrl->status == VIRTIO_NET_OK;
169040cbfc37SAmos Kong }
169140cbfc37SAmos Kong 
16929c46f6d4SAlex Williamson static int virtnet_set_mac_address(struct net_device *dev, void *p)
16939c46f6d4SAlex Williamson {
16949c46f6d4SAlex Williamson 	struct virtnet_info *vi = netdev_priv(dev);
16959c46f6d4SAlex Williamson 	struct virtio_device *vdev = vi->vdev;
1696f2f2c8b4SJiri Pirko 	int ret;
1697e37e2ff3SAndy Lutomirski 	struct sockaddr *addr;
16987e58d5aeSAmos Kong 	struct scatterlist sg;
16999c46f6d4SAlex Williamson 
1700ba5e4426SSridhar Samudrala 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
1701ba5e4426SSridhar Samudrala 		return -EOPNOTSUPP;
1702ba5e4426SSridhar Samudrala 
1703801822d1SShyam Saini 	addr = kmemdup(p, sizeof(*addr), GFP_KERNEL);
1704e37e2ff3SAndy Lutomirski 	if (!addr)
1705e37e2ff3SAndy Lutomirski 		return -ENOMEM;
1706e37e2ff3SAndy Lutomirski 
1707e37e2ff3SAndy Lutomirski 	ret = eth_prepare_mac_addr_change(dev, addr);
1708f2f2c8b4SJiri Pirko 	if (ret)
1709e37e2ff3SAndy Lutomirski 		goto out;
17109c46f6d4SAlex Williamson 
17117e58d5aeSAmos Kong 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR)) {
17127e58d5aeSAmos Kong 		sg_init_one(&sg, addr->sa_data, dev->addr_len);
17137e58d5aeSAmos Kong 		if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1714d24bae32Sstephen hemminger 					  VIRTIO_NET_CTRL_MAC_ADDR_SET, &sg)) {
17157e58d5aeSAmos Kong 			dev_warn(&vdev->dev,
17167e58d5aeSAmos Kong 				 "Failed to set mac address by vq command.\n");
1717e37e2ff3SAndy Lutomirski 			ret = -EINVAL;
1718e37e2ff3SAndy Lutomirski 			goto out;
17197e58d5aeSAmos Kong 		}
17207e93a02fSMichael S. Tsirkin 	} else if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC) &&
17217e93a02fSMichael S. Tsirkin 		   !virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
1722855e0c52SRusty Russell 		unsigned int i;
1723855e0c52SRusty Russell 
1724855e0c52SRusty Russell 		/* Naturally, this has an atomicity problem. */
1725855e0c52SRusty Russell 		for (i = 0; i < dev->addr_len; i++)
1726855e0c52SRusty Russell 			virtio_cwrite8(vdev,
1727855e0c52SRusty Russell 				       offsetof(struct virtio_net_config, mac) +
1728855e0c52SRusty Russell 				       i, addr->sa_data[i]);
17297e58d5aeSAmos Kong 	}
17307e58d5aeSAmos Kong 
17317e58d5aeSAmos Kong 	eth_commit_mac_addr_change(dev, p);
1732e37e2ff3SAndy Lutomirski 	ret = 0;
17339c46f6d4SAlex Williamson 
1734e37e2ff3SAndy Lutomirski out:
1735e37e2ff3SAndy Lutomirski 	kfree(addr);
1736e37e2ff3SAndy Lutomirski 	return ret;
17379c46f6d4SAlex Williamson }
17389c46f6d4SAlex Williamson 
1739bc1f4470Sstephen hemminger static void virtnet_stats(struct net_device *dev,
17403fa2a1dfSstephen hemminger 			  struct rtnl_link_stats64 *tot)
17413fa2a1dfSstephen hemminger {
17423fa2a1dfSstephen hemminger 	struct virtnet_info *vi = netdev_priv(dev);
17433fa2a1dfSstephen hemminger 	unsigned int start;
1744d7dfc5cfSToshiaki Makita 	int i;
17453fa2a1dfSstephen hemminger 
1746d7dfc5cfSToshiaki Makita 	for (i = 0; i < vi->max_queue_pairs; i++) {
17472c4a2f7dSToshiaki Makita 		u64 tpackets, tbytes, rpackets, rbytes, rdrops;
1748d7dfc5cfSToshiaki Makita 		struct receive_queue *rq = &vi->rq[i];
1749d7dfc5cfSToshiaki Makita 		struct send_queue *sq = &vi->sq[i];
17503fa2a1dfSstephen hemminger 
17513fa2a1dfSstephen hemminger 		do {
1752d7dfc5cfSToshiaki Makita 			start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
1753d7dfc5cfSToshiaki Makita 			tpackets = sq->stats.packets;
1754d7dfc5cfSToshiaki Makita 			tbytes   = sq->stats.bytes;
1755d7dfc5cfSToshiaki Makita 		} while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
175683a27052SEric Dumazet 
175783a27052SEric Dumazet 		do {
1758d7dfc5cfSToshiaki Makita 			start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
1759d46eeeafSJason Wang 			rpackets = rq->stats.packets;
1760d46eeeafSJason Wang 			rbytes   = rq->stats.bytes;
1761d46eeeafSJason Wang 			rdrops   = rq->stats.drops;
1762d7dfc5cfSToshiaki Makita 		} while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
17633fa2a1dfSstephen hemminger 
17643fa2a1dfSstephen hemminger 		tot->rx_packets += rpackets;
17653fa2a1dfSstephen hemminger 		tot->tx_packets += tpackets;
17663fa2a1dfSstephen hemminger 		tot->rx_bytes   += rbytes;
17673fa2a1dfSstephen hemminger 		tot->tx_bytes   += tbytes;
17682c4a2f7dSToshiaki Makita 		tot->rx_dropped += rdrops;
17693fa2a1dfSstephen hemminger 	}
17703fa2a1dfSstephen hemminger 
17713fa2a1dfSstephen hemminger 	tot->tx_dropped = dev->stats.tx_dropped;
1772021ac8d3SRick Jones 	tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
17733fa2a1dfSstephen hemminger 	tot->rx_length_errors = dev->stats.rx_length_errors;
17743fa2a1dfSstephen hemminger 	tot->rx_frame_errors = dev->stats.rx_frame_errors;
17753fa2a1dfSstephen hemminger }
17763fa2a1dfSstephen hemminger 
1777586d17c5SJason Wang static void virtnet_ack_link_announce(struct virtnet_info *vi)
1778586d17c5SJason Wang {
1779586d17c5SJason Wang 	rtnl_lock();
1780586d17c5SJason Wang 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_ANNOUNCE,
1781d24bae32Sstephen hemminger 				  VIRTIO_NET_CTRL_ANNOUNCE_ACK, NULL))
1782586d17c5SJason Wang 		dev_warn(&vi->dev->dev, "Failed to ack link announce.\n");
1783586d17c5SJason Wang 	rtnl_unlock();
1784586d17c5SJason Wang }
1785586d17c5SJason Wang 
178647315329SJohn Fastabend static int _virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
1787986a4f4dSJason Wang {
1788986a4f4dSJason Wang 	struct scatterlist sg;
1789986a4f4dSJason Wang 	struct net_device *dev = vi->dev;
1790986a4f4dSJason Wang 
1791986a4f4dSJason Wang 	if (!vi->has_cvq || !virtio_has_feature(vi->vdev, VIRTIO_NET_F_MQ))
1792986a4f4dSJason Wang 		return 0;
1793986a4f4dSJason Wang 
179412e57169SMichael S. Tsirkin 	vi->ctrl->mq.virtqueue_pairs = cpu_to_virtio16(vi->vdev, queue_pairs);
179512e57169SMichael S. Tsirkin 	sg_init_one(&sg, &vi->ctrl->mq, sizeof(vi->ctrl->mq));
1796986a4f4dSJason Wang 
1797986a4f4dSJason Wang 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MQ,
1798d24bae32Sstephen hemminger 				  VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET, &sg)) {
1799986a4f4dSJason Wang 		dev_warn(&dev->dev, "Fail to set num of queue pairs to %d\n",
1800986a4f4dSJason Wang 			 queue_pairs);
1801986a4f4dSJason Wang 		return -EINVAL;
180255257d72SSasha Levin 	} else {
1803986a4f4dSJason Wang 		vi->curr_queue_pairs = queue_pairs;
180435ed159bSJason Wang 		/* virtnet_open() will refill when device is going to up. */
180535ed159bSJason Wang 		if (dev->flags & IFF_UP)
18069b9cd802SJason Wang 			schedule_delayed_work(&vi->refill, 0);
180755257d72SSasha Levin 	}
1808986a4f4dSJason Wang 
1809986a4f4dSJason Wang 	return 0;
1810986a4f4dSJason Wang }
1811986a4f4dSJason Wang 
181247315329SJohn Fastabend static int virtnet_set_queues(struct virtnet_info *vi, u16 queue_pairs)
181347315329SJohn Fastabend {
181447315329SJohn Fastabend 	int err;
181547315329SJohn Fastabend 
181647315329SJohn Fastabend 	rtnl_lock();
181747315329SJohn Fastabend 	err = _virtnet_set_queues(vi, queue_pairs);
181847315329SJohn Fastabend 	rtnl_unlock();
181947315329SJohn Fastabend 	return err;
182047315329SJohn Fastabend }
182147315329SJohn Fastabend 
1822296f96fcSRusty Russell static int virtnet_close(struct net_device *dev)
1823296f96fcSRusty Russell {
1824296f96fcSRusty Russell 	struct virtnet_info *vi = netdev_priv(dev);
1825986a4f4dSJason Wang 	int i;
1826296f96fcSRusty Russell 
1827b2baed69SRusty Russell 	/* Make sure refill_work doesn't re-enable napi! */
1828b2baed69SRusty Russell 	cancel_delayed_work_sync(&vi->refill);
1829986a4f4dSJason Wang 
1830b92f1e67SWillem de Bruijn 	for (i = 0; i < vi->max_queue_pairs; i++) {
1831754b8a21SJesper Dangaard Brouer 		xdp_rxq_info_unreg(&vi->rq[i].xdp_rxq);
1832986a4f4dSJason Wang 		napi_disable(&vi->rq[i].napi);
183378a57b48SWillem de Bruijn 		virtnet_napi_tx_disable(&vi->sq[i].napi);
1834b92f1e67SWillem de Bruijn 	}
1835296f96fcSRusty Russell 
1836296f96fcSRusty Russell 	return 0;
1837296f96fcSRusty Russell }
1838296f96fcSRusty Russell 
18392af7698eSAlex Williamson static void virtnet_set_rx_mode(struct net_device *dev)
18402af7698eSAlex Williamson {
18412af7698eSAlex Williamson 	struct virtnet_info *vi = netdev_priv(dev);
1842f565a7c2SAlex Williamson 	struct scatterlist sg[2];
1843f565a7c2SAlex Williamson 	struct virtio_net_ctrl_mac *mac_data;
1844ccffad25SJiri Pirko 	struct netdev_hw_addr *ha;
184532e7bfc4SJiri Pirko 	int uc_count;
18464cd24eafSJiri Pirko 	int mc_count;
1847f565a7c2SAlex Williamson 	void *buf;
1848f565a7c2SAlex Williamson 	int i;
18492af7698eSAlex Williamson 
1850788a8b6dSstephen hemminger 	/* We can't dynamically set ndo_set_rx_mode, so return gracefully */
18512af7698eSAlex Williamson 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
18522af7698eSAlex Williamson 		return;
18532af7698eSAlex Williamson 
185412e57169SMichael S. Tsirkin 	vi->ctrl->promisc = ((dev->flags & IFF_PROMISC) != 0);
185512e57169SMichael S. Tsirkin 	vi->ctrl->allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
18562af7698eSAlex Williamson 
185712e57169SMichael S. Tsirkin 	sg_init_one(sg, &vi->ctrl->promisc, sizeof(vi->ctrl->promisc));
18582af7698eSAlex Williamson 
18592af7698eSAlex Williamson 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1860d24bae32Sstephen hemminger 				  VIRTIO_NET_CTRL_RX_PROMISC, sg))
18612af7698eSAlex Williamson 		dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
186212e57169SMichael S. Tsirkin 			 vi->ctrl->promisc ? "en" : "dis");
18632af7698eSAlex Williamson 
186412e57169SMichael S. Tsirkin 	sg_init_one(sg, &vi->ctrl->allmulti, sizeof(vi->ctrl->allmulti));
18652af7698eSAlex Williamson 
18662af7698eSAlex Williamson 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
1867d24bae32Sstephen hemminger 				  VIRTIO_NET_CTRL_RX_ALLMULTI, sg))
18682af7698eSAlex Williamson 		dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
186912e57169SMichael S. Tsirkin 			 vi->ctrl->allmulti ? "en" : "dis");
1870f565a7c2SAlex Williamson 
187132e7bfc4SJiri Pirko 	uc_count = netdev_uc_count(dev);
18724cd24eafSJiri Pirko 	mc_count = netdev_mc_count(dev);
1873f565a7c2SAlex Williamson 	/* MAC filter - use one buffer for both lists */
18744cd24eafSJiri Pirko 	buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
1875f565a7c2SAlex Williamson 		      (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
18764cd24eafSJiri Pirko 	mac_data = buf;
1877e68ed8f0SJoe Perches 	if (!buf)
1878f565a7c2SAlex Williamson 		return;
1879f565a7c2SAlex Williamson 
188023e258e1SAlex Williamson 	sg_init_table(sg, 2);
188123e258e1SAlex Williamson 
1882f565a7c2SAlex Williamson 	/* Store the unicast list and count in the front of the buffer */
1883fdd819b2SMichael S. Tsirkin 	mac_data->entries = cpu_to_virtio32(vi->vdev, uc_count);
1884ccffad25SJiri Pirko 	i = 0;
188532e7bfc4SJiri Pirko 	netdev_for_each_uc_addr(ha, dev)
1886ccffad25SJiri Pirko 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1887f565a7c2SAlex Williamson 
1888f565a7c2SAlex Williamson 	sg_set_buf(&sg[0], mac_data,
188932e7bfc4SJiri Pirko 		   sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
1890f565a7c2SAlex Williamson 
1891f565a7c2SAlex Williamson 	/* multicast list and count fill the end */
189232e7bfc4SJiri Pirko 	mac_data = (void *)&mac_data->macs[uc_count][0];
1893f565a7c2SAlex Williamson 
1894fdd819b2SMichael S. Tsirkin 	mac_data->entries = cpu_to_virtio32(vi->vdev, mc_count);
1895567ec874SJiri Pirko 	i = 0;
189622bedad3SJiri Pirko 	netdev_for_each_mc_addr(ha, dev)
189722bedad3SJiri Pirko 		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
1898f565a7c2SAlex Williamson 
1899f565a7c2SAlex Williamson 	sg_set_buf(&sg[1], mac_data,
19004cd24eafSJiri Pirko 		   sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
1901f565a7c2SAlex Williamson 
1902f565a7c2SAlex Williamson 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
1903d24bae32Sstephen hemminger 				  VIRTIO_NET_CTRL_MAC_TABLE_SET, sg))
190499e872aeSThomas Huth 		dev_warn(&dev->dev, "Failed to set MAC filter table.\n");
1905f565a7c2SAlex Williamson 
1906f565a7c2SAlex Williamson 	kfree(buf);
19072af7698eSAlex Williamson }
19082af7698eSAlex Williamson 
190980d5c368SPatrick McHardy static int virtnet_vlan_rx_add_vid(struct net_device *dev,
191080d5c368SPatrick McHardy 				   __be16 proto, u16 vid)
19110bde9569SAlex Williamson {
19120bde9569SAlex Williamson 	struct virtnet_info *vi = netdev_priv(dev);
19130bde9569SAlex Williamson 	struct scatterlist sg;
19140bde9569SAlex Williamson 
1915d7fad4c8SMichael S. Tsirkin 	vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
191612e57169SMichael S. Tsirkin 	sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
19170bde9569SAlex Williamson 
19180bde9569SAlex Williamson 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1919d24bae32Sstephen hemminger 				  VIRTIO_NET_CTRL_VLAN_ADD, &sg))
19200bde9569SAlex Williamson 		dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
19218e586137SJiri Pirko 	return 0;
19220bde9569SAlex Williamson }
19230bde9569SAlex Williamson 
192480d5c368SPatrick McHardy static int virtnet_vlan_rx_kill_vid(struct net_device *dev,
192580d5c368SPatrick McHardy 				    __be16 proto, u16 vid)
19260bde9569SAlex Williamson {
19270bde9569SAlex Williamson 	struct virtnet_info *vi = netdev_priv(dev);
19280bde9569SAlex Williamson 	struct scatterlist sg;
19290bde9569SAlex Williamson 
1930d7fad4c8SMichael S. Tsirkin 	vi->ctrl->vid = cpu_to_virtio16(vi->vdev, vid);
193112e57169SMichael S. Tsirkin 	sg_init_one(&sg, &vi->ctrl->vid, sizeof(vi->ctrl->vid));
19320bde9569SAlex Williamson 
19330bde9569SAlex Williamson 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
1934d24bae32Sstephen hemminger 				  VIRTIO_NET_CTRL_VLAN_DEL, &sg))
19350bde9569SAlex Williamson 		dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
19368e586137SJiri Pirko 	return 0;
19370bde9569SAlex Williamson }
19380bde9569SAlex Williamson 
1939310974faSPeter Xu static void virtnet_clean_affinity(struct virtnet_info *vi)
1940986a4f4dSJason Wang {
1941986a4f4dSJason Wang 	int i;
19428898c21cSWanlong Gao 
19438898c21cSWanlong Gao 	if (vi->affinity_hint_set) {
19448898c21cSWanlong Gao 		for (i = 0; i < vi->max_queue_pairs; i++) {
194519e226e8SCaleb Raitto 			virtqueue_set_affinity(vi->rq[i].vq, NULL);
194619e226e8SCaleb Raitto 			virtqueue_set_affinity(vi->sq[i].vq, NULL);
19478898c21cSWanlong Gao 		}
19488898c21cSWanlong Gao 
19498898c21cSWanlong Gao 		vi->affinity_hint_set = false;
19508898c21cSWanlong Gao 	}
19518898c21cSWanlong Gao }
19528898c21cSWanlong Gao 
19538898c21cSWanlong Gao static void virtnet_set_affinity(struct virtnet_info *vi)
1954986a4f4dSJason Wang {
19552ca653d6SCaleb Raitto 	cpumask_var_t mask;
19562ca653d6SCaleb Raitto 	int stragglers;
19572ca653d6SCaleb Raitto 	int group_size;
19582ca653d6SCaleb Raitto 	int i, j, cpu;
19592ca653d6SCaleb Raitto 	int num_cpu;
19602ca653d6SCaleb Raitto 	int stride;
1961986a4f4dSJason Wang 
19622ca653d6SCaleb Raitto 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
1963310974faSPeter Xu 		virtnet_clean_affinity(vi);
1964986a4f4dSJason Wang 		return;
1965986a4f4dSJason Wang 	}
1966986a4f4dSJason Wang 
19672ca653d6SCaleb Raitto 	num_cpu = num_online_cpus();
19682ca653d6SCaleb Raitto 	stride = max_t(int, num_cpu / vi->curr_queue_pairs, 1);
19692ca653d6SCaleb Raitto 	stragglers = num_cpu >= vi->curr_queue_pairs ?
19702ca653d6SCaleb Raitto 			num_cpu % vi->curr_queue_pairs :
19712ca653d6SCaleb Raitto 			0;
19722ca653d6SCaleb Raitto 	cpu = cpumask_next(-1, cpu_online_mask);
19734d99f660SAndrei Vagin 
19742ca653d6SCaleb Raitto 	for (i = 0; i < vi->curr_queue_pairs; i++) {
19752ca653d6SCaleb Raitto 		group_size = stride + (i < stragglers ? 1 : 0);
19762ca653d6SCaleb Raitto 
19772ca653d6SCaleb Raitto 		for (j = 0; j < group_size; j++) {
19782ca653d6SCaleb Raitto 			cpumask_set_cpu(cpu, mask);
19792ca653d6SCaleb Raitto 			cpu = cpumask_next_wrap(cpu, cpu_online_mask,
19802ca653d6SCaleb Raitto 						nr_cpu_ids, false);
19812ca653d6SCaleb Raitto 		}
19822ca653d6SCaleb Raitto 		virtqueue_set_affinity(vi->rq[i].vq, mask);
19832ca653d6SCaleb Raitto 		virtqueue_set_affinity(vi->sq[i].vq, mask);
19842ca653d6SCaleb Raitto 		__netif_set_xps_queue(vi->dev, cpumask_bits(mask), i, false);
19852ca653d6SCaleb Raitto 		cpumask_clear(mask);
1986986a4f4dSJason Wang 	}
1987986a4f4dSJason Wang 
1988986a4f4dSJason Wang 	vi->affinity_hint_set = true;
19892ca653d6SCaleb Raitto 	free_cpumask_var(mask);
199047be2479SWanlong Gao }
1991986a4f4dSJason Wang 
19928017c279SSebastian Andrzej Siewior static int virtnet_cpu_online(unsigned int cpu, struct hlist_node *node)
19938de4b2f3SWanlong Gao {
19948017c279SSebastian Andrzej Siewior 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
19958017c279SSebastian Andrzej Siewior 						   node);
19968de4b2f3SWanlong Gao 	virtnet_set_affinity(vi);
19978017c279SSebastian Andrzej Siewior 	return 0;
19988de4b2f3SWanlong Gao }
19993ab098dfSJason Wang 
20008017c279SSebastian Andrzej Siewior static int virtnet_cpu_dead(unsigned int cpu, struct hlist_node *node)
20018017c279SSebastian Andrzej Siewior {
20028017c279SSebastian Andrzej Siewior 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
20038017c279SSebastian Andrzej Siewior 						   node_dead);
20048017c279SSebastian Andrzej Siewior 	virtnet_set_affinity(vi);
20058017c279SSebastian Andrzej Siewior 	return 0;
20068017c279SSebastian Andrzej Siewior }
20078017c279SSebastian Andrzej Siewior 
20088017c279SSebastian Andrzej Siewior static int virtnet_cpu_down_prep(unsigned int cpu, struct hlist_node *node)
20098017c279SSebastian Andrzej Siewior {
20108017c279SSebastian Andrzej Siewior 	struct virtnet_info *vi = hlist_entry_safe(node, struct virtnet_info,
20118017c279SSebastian Andrzej Siewior 						   node);
20128017c279SSebastian Andrzej Siewior 
2013310974faSPeter Xu 	virtnet_clean_affinity(vi);
20148017c279SSebastian Andrzej Siewior 	return 0;
20158017c279SSebastian Andrzej Siewior }
20168017c279SSebastian Andrzej Siewior 
20178017c279SSebastian Andrzej Siewior static enum cpuhp_state virtionet_online;
20188017c279SSebastian Andrzej Siewior 
20198017c279SSebastian Andrzej Siewior static int virtnet_cpu_notif_add(struct virtnet_info *vi)
20208017c279SSebastian Andrzej Siewior {
20218017c279SSebastian Andrzej Siewior 	int ret;
20228017c279SSebastian Andrzej Siewior 
20238017c279SSebastian Andrzej Siewior 	ret = cpuhp_state_add_instance_nocalls(virtionet_online, &vi->node);
20248017c279SSebastian Andrzej Siewior 	if (ret)
20258017c279SSebastian Andrzej Siewior 		return ret;
20268017c279SSebastian Andrzej Siewior 	ret = cpuhp_state_add_instance_nocalls(CPUHP_VIRT_NET_DEAD,
20278017c279SSebastian Andrzej Siewior 					       &vi->node_dead);
20288017c279SSebastian Andrzej Siewior 	if (!ret)
20298017c279SSebastian Andrzej Siewior 		return ret;
20308017c279SSebastian Andrzej Siewior 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
20318017c279SSebastian Andrzej Siewior 	return ret;
20328017c279SSebastian Andrzej Siewior }
20338017c279SSebastian Andrzej Siewior 
20348017c279SSebastian Andrzej Siewior static void virtnet_cpu_notif_remove(struct virtnet_info *vi)
20358017c279SSebastian Andrzej Siewior {
20368017c279SSebastian Andrzej Siewior 	cpuhp_state_remove_instance_nocalls(virtionet_online, &vi->node);
20378017c279SSebastian Andrzej Siewior 	cpuhp_state_remove_instance_nocalls(CPUHP_VIRT_NET_DEAD,
20388017c279SSebastian Andrzej Siewior 					    &vi->node_dead);
2039a9ea3fc6SHerbert Xu }
2040a9ea3fc6SHerbert Xu 
20418f9f4668SRick Jones static void virtnet_get_ringparam(struct net_device *dev,
20428f9f4668SRick Jones 				struct ethtool_ringparam *ring)
20438f9f4668SRick Jones {
20448f9f4668SRick Jones 	struct virtnet_info *vi = netdev_priv(dev);
20458f9f4668SRick Jones 
2046986a4f4dSJason Wang 	ring->rx_max_pending = virtqueue_get_vring_size(vi->rq[0].vq);
2047986a4f4dSJason Wang 	ring->tx_max_pending = virtqueue_get_vring_size(vi->sq[0].vq);
20488f9f4668SRick Jones 	ring->rx_pending = ring->rx_max_pending;
20498f9f4668SRick Jones 	ring->tx_pending = ring->tx_max_pending;
20508f9f4668SRick Jones }
20518f9f4668SRick Jones 
205266846048SRick Jones 
205366846048SRick Jones static void virtnet_get_drvinfo(struct net_device *dev,
205466846048SRick Jones 				struct ethtool_drvinfo *info)
205566846048SRick Jones {
205666846048SRick Jones 	struct virtnet_info *vi = netdev_priv(dev);
205766846048SRick Jones 	struct virtio_device *vdev = vi->vdev;
205866846048SRick Jones 
205966846048SRick Jones 	strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
206066846048SRick Jones 	strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
206166846048SRick Jones 	strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
206266846048SRick Jones 
206366846048SRick Jones }
206466846048SRick Jones 
2065d73bcd2cSJason Wang /* TODO: Eliminate OOO packets during switching */
2066d73bcd2cSJason Wang static int virtnet_set_channels(struct net_device *dev,
2067d73bcd2cSJason Wang 				struct ethtool_channels *channels)
2068d73bcd2cSJason Wang {
2069d73bcd2cSJason Wang 	struct virtnet_info *vi = netdev_priv(dev);
2070d73bcd2cSJason Wang 	u16 queue_pairs = channels->combined_count;
2071d73bcd2cSJason Wang 	int err;
2072d73bcd2cSJason Wang 
2073d73bcd2cSJason Wang 	/* We don't support separate rx/tx channels.
2074d73bcd2cSJason Wang 	 * We don't allow setting 'other' channels.
2075d73bcd2cSJason Wang 	 */
2076d73bcd2cSJason Wang 	if (channels->rx_count || channels->tx_count || channels->other_count)
2077d73bcd2cSJason Wang 		return -EINVAL;
2078d73bcd2cSJason Wang 
2079c18e9cd6SAmos Kong 	if (queue_pairs > vi->max_queue_pairs || queue_pairs == 0)
2080d73bcd2cSJason Wang 		return -EINVAL;
2081d73bcd2cSJason Wang 
2082f600b690SJohn Fastabend 	/* For now we don't support modifying channels while XDP is loaded
2083f600b690SJohn Fastabend 	 * also when XDP is loaded all RX queues have XDP programs so we only
2084f600b690SJohn Fastabend 	 * need to check a single RX queue.
2085f600b690SJohn Fastabend 	 */
2086f600b690SJohn Fastabend 	if (vi->rq[0].xdp_prog)
2087f600b690SJohn Fastabend 		return -EINVAL;
2088f600b690SJohn Fastabend 
208947be2479SWanlong Gao 	get_online_cpus();
209047315329SJohn Fastabend 	err = _virtnet_set_queues(vi, queue_pairs);
2091d73bcd2cSJason Wang 	if (!err) {
2092d73bcd2cSJason Wang 		netif_set_real_num_tx_queues(dev, queue_pairs);
2093d73bcd2cSJason Wang 		netif_set_real_num_rx_queues(dev, queue_pairs);
2094d73bcd2cSJason Wang 
20958898c21cSWanlong Gao 		virtnet_set_affinity(vi);
2096d73bcd2cSJason Wang 	}
209747be2479SWanlong Gao 	put_online_cpus();
2098d73bcd2cSJason Wang 
2099d73bcd2cSJason Wang 	return err;
2100d73bcd2cSJason Wang }
2101d73bcd2cSJason Wang 
2102d7dfc5cfSToshiaki Makita static void virtnet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
2103d7dfc5cfSToshiaki Makita {
2104d7dfc5cfSToshiaki Makita 	struct virtnet_info *vi = netdev_priv(dev);
2105d7dfc5cfSToshiaki Makita 	char *p = (char *)data;
2106d7dfc5cfSToshiaki Makita 	unsigned int i, j;
2107d7dfc5cfSToshiaki Makita 
2108d7dfc5cfSToshiaki Makita 	switch (stringset) {
2109d7dfc5cfSToshiaki Makita 	case ETH_SS_STATS:
2110d7dfc5cfSToshiaki Makita 		for (i = 0; i < vi->curr_queue_pairs; i++) {
2111d7dfc5cfSToshiaki Makita 			for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2112d7dfc5cfSToshiaki Makita 				snprintf(p, ETH_GSTRING_LEN, "rx_queue_%u_%s",
2113d7dfc5cfSToshiaki Makita 					 i, virtnet_rq_stats_desc[j].desc);
2114d7dfc5cfSToshiaki Makita 				p += ETH_GSTRING_LEN;
2115d7dfc5cfSToshiaki Makita 			}
2116d7dfc5cfSToshiaki Makita 		}
2117d7dfc5cfSToshiaki Makita 
2118d7dfc5cfSToshiaki Makita 		for (i = 0; i < vi->curr_queue_pairs; i++) {
2119d7dfc5cfSToshiaki Makita 			for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2120d7dfc5cfSToshiaki Makita 				snprintf(p, ETH_GSTRING_LEN, "tx_queue_%u_%s",
2121d7dfc5cfSToshiaki Makita 					 i, virtnet_sq_stats_desc[j].desc);
2122d7dfc5cfSToshiaki Makita 				p += ETH_GSTRING_LEN;
2123d7dfc5cfSToshiaki Makita 			}
2124d7dfc5cfSToshiaki Makita 		}
2125d7dfc5cfSToshiaki Makita 		break;
2126d7dfc5cfSToshiaki Makita 	}
2127d7dfc5cfSToshiaki Makita }
2128d7dfc5cfSToshiaki Makita 
2129d7dfc5cfSToshiaki Makita static int virtnet_get_sset_count(struct net_device *dev, int sset)
2130d7dfc5cfSToshiaki Makita {
2131d7dfc5cfSToshiaki Makita 	struct virtnet_info *vi = netdev_priv(dev);
2132d7dfc5cfSToshiaki Makita 
2133d7dfc5cfSToshiaki Makita 	switch (sset) {
2134d7dfc5cfSToshiaki Makita 	case ETH_SS_STATS:
2135d7dfc5cfSToshiaki Makita 		return vi->curr_queue_pairs * (VIRTNET_RQ_STATS_LEN +
2136d7dfc5cfSToshiaki Makita 					       VIRTNET_SQ_STATS_LEN);
2137d7dfc5cfSToshiaki Makita 	default:
2138d7dfc5cfSToshiaki Makita 		return -EOPNOTSUPP;
2139d7dfc5cfSToshiaki Makita 	}
2140d7dfc5cfSToshiaki Makita }
2141d7dfc5cfSToshiaki Makita 
2142d7dfc5cfSToshiaki Makita static void virtnet_get_ethtool_stats(struct net_device *dev,
2143d7dfc5cfSToshiaki Makita 				      struct ethtool_stats *stats, u64 *data)
2144d7dfc5cfSToshiaki Makita {
2145d7dfc5cfSToshiaki Makita 	struct virtnet_info *vi = netdev_priv(dev);
2146d7dfc5cfSToshiaki Makita 	unsigned int idx = 0, start, i, j;
2147d7dfc5cfSToshiaki Makita 	const u8 *stats_base;
2148d7dfc5cfSToshiaki Makita 	size_t offset;
2149d7dfc5cfSToshiaki Makita 
2150d7dfc5cfSToshiaki Makita 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2151d7dfc5cfSToshiaki Makita 		struct receive_queue *rq = &vi->rq[i];
2152d7dfc5cfSToshiaki Makita 
2153d46eeeafSJason Wang 		stats_base = (u8 *)&rq->stats;
2154d7dfc5cfSToshiaki Makita 		do {
2155d7dfc5cfSToshiaki Makita 			start = u64_stats_fetch_begin_irq(&rq->stats.syncp);
2156d7dfc5cfSToshiaki Makita 			for (j = 0; j < VIRTNET_RQ_STATS_LEN; j++) {
2157d7dfc5cfSToshiaki Makita 				offset = virtnet_rq_stats_desc[j].offset;
2158d7dfc5cfSToshiaki Makita 				data[idx + j] = *(u64 *)(stats_base + offset);
2159d7dfc5cfSToshiaki Makita 			}
2160d7dfc5cfSToshiaki Makita 		} while (u64_stats_fetch_retry_irq(&rq->stats.syncp, start));
2161d7dfc5cfSToshiaki Makita 		idx += VIRTNET_RQ_STATS_LEN;
2162d7dfc5cfSToshiaki Makita 	}
2163d7dfc5cfSToshiaki Makita 
2164d7dfc5cfSToshiaki Makita 	for (i = 0; i < vi->curr_queue_pairs; i++) {
2165d7dfc5cfSToshiaki Makita 		struct send_queue *sq = &vi->sq[i];
2166d7dfc5cfSToshiaki Makita 
2167d7dfc5cfSToshiaki Makita 		stats_base = (u8 *)&sq->stats;
2168d7dfc5cfSToshiaki Makita 		do {
2169d7dfc5cfSToshiaki Makita 			start = u64_stats_fetch_begin_irq(&sq->stats.syncp);
2170d7dfc5cfSToshiaki Makita 			for (j = 0; j < VIRTNET_SQ_STATS_LEN; j++) {
2171d7dfc5cfSToshiaki Makita 				offset = virtnet_sq_stats_desc[j].offset;
2172d7dfc5cfSToshiaki Makita 				data[idx + j] = *(u64 *)(stats_base + offset);
2173d7dfc5cfSToshiaki Makita 			}
2174d7dfc5cfSToshiaki Makita 		} while (u64_stats_fetch_retry_irq(&sq->stats.syncp, start));
2175d7dfc5cfSToshiaki Makita 		idx += VIRTNET_SQ_STATS_LEN;
2176d7dfc5cfSToshiaki Makita 	}
2177d7dfc5cfSToshiaki Makita }
2178d7dfc5cfSToshiaki Makita 
2179d73bcd2cSJason Wang static void virtnet_get_channels(struct net_device *dev,
2180d73bcd2cSJason Wang 				 struct ethtool_channels *channels)
2181d73bcd2cSJason Wang {
2182d73bcd2cSJason Wang 	struct virtnet_info *vi = netdev_priv(dev);
2183d73bcd2cSJason Wang 
2184d73bcd2cSJason Wang 	channels->combined_count = vi->curr_queue_pairs;
2185d73bcd2cSJason Wang 	channels->max_combined = vi->max_queue_pairs;
2186d73bcd2cSJason Wang 	channels->max_other = 0;
2187d73bcd2cSJason Wang 	channels->rx_count = 0;
2188d73bcd2cSJason Wang 	channels->tx_count = 0;
2189d73bcd2cSJason Wang 	channels->other_count = 0;
2190d73bcd2cSJason Wang }
2191d73bcd2cSJason Wang 
2192ebb6b4b1SPhilippe Reynes static int virtnet_set_link_ksettings(struct net_device *dev,
2193ebb6b4b1SPhilippe Reynes 				      const struct ethtool_link_ksettings *cmd)
219416032be5SNikolay Aleksandrov {
219516032be5SNikolay Aleksandrov 	struct virtnet_info *vi = netdev_priv(dev);
219616032be5SNikolay Aleksandrov 
21979aedc6e2SCris Forno 	return ethtool_virtdev_set_link_ksettings(dev, cmd,
21989aedc6e2SCris Forno 						  &vi->speed, &vi->duplex);
219916032be5SNikolay Aleksandrov }
220016032be5SNikolay Aleksandrov 
2201ebb6b4b1SPhilippe Reynes static int virtnet_get_link_ksettings(struct net_device *dev,
2202ebb6b4b1SPhilippe Reynes 				      struct ethtool_link_ksettings *cmd)
220316032be5SNikolay Aleksandrov {
220416032be5SNikolay Aleksandrov 	struct virtnet_info *vi = netdev_priv(dev);
220516032be5SNikolay Aleksandrov 
2206ebb6b4b1SPhilippe Reynes 	cmd->base.speed = vi->speed;
2207ebb6b4b1SPhilippe Reynes 	cmd->base.duplex = vi->duplex;
2208ebb6b4b1SPhilippe Reynes 	cmd->base.port = PORT_OTHER;
220916032be5SNikolay Aleksandrov 
221016032be5SNikolay Aleksandrov 	return 0;
221116032be5SNikolay Aleksandrov }
221216032be5SNikolay Aleksandrov 
22130c465be1SJason Wang static int virtnet_set_coalesce(struct net_device *dev,
22140c465be1SJason Wang 				struct ethtool_coalesce *ec)
22150c465be1SJason Wang {
22160c465be1SJason Wang 	struct virtnet_info *vi = netdev_priv(dev);
22170c465be1SJason Wang 	int i, napi_weight;
22180c465be1SJason Wang 
2219a51e5206SJakub Kicinski 	if (ec->tx_max_coalesced_frames > 1 ||
2220a51e5206SJakub Kicinski 	    ec->rx_max_coalesced_frames != 1)
22210c465be1SJason Wang 		return -EINVAL;
22220c465be1SJason Wang 
22230c465be1SJason Wang 	napi_weight = ec->tx_max_coalesced_frames ? NAPI_POLL_WEIGHT : 0;
22240c465be1SJason Wang 	if (napi_weight ^ vi->sq[0].napi.weight) {
22250c465be1SJason Wang 		if (dev->flags & IFF_UP)
22260c465be1SJason Wang 			return -EBUSY;
22270c465be1SJason Wang 		for (i = 0; i < vi->max_queue_pairs; i++)
22280c465be1SJason Wang 			vi->sq[i].napi.weight = napi_weight;
22290c465be1SJason Wang 	}
22300c465be1SJason Wang 
22310c465be1SJason Wang 	return 0;
22320c465be1SJason Wang }
22330c465be1SJason Wang 
22340c465be1SJason Wang static int virtnet_get_coalesce(struct net_device *dev,
22350c465be1SJason Wang 				struct ethtool_coalesce *ec)
22360c465be1SJason Wang {
22370c465be1SJason Wang 	struct ethtool_coalesce ec_default = {
22380c465be1SJason Wang 		.cmd = ETHTOOL_GCOALESCE,
22390c465be1SJason Wang 		.rx_max_coalesced_frames = 1,
22400c465be1SJason Wang 	};
22410c465be1SJason Wang 	struct virtnet_info *vi = netdev_priv(dev);
22420c465be1SJason Wang 
22430c465be1SJason Wang 	memcpy(ec, &ec_default, sizeof(ec_default));
22440c465be1SJason Wang 
22450c465be1SJason Wang 	if (vi->sq[0].napi.weight)
22460c465be1SJason Wang 		ec->tx_max_coalesced_frames = 1;
22470c465be1SJason Wang 
22480c465be1SJason Wang 	return 0;
22490c465be1SJason Wang }
22500c465be1SJason Wang 
225116032be5SNikolay Aleksandrov static void virtnet_init_settings(struct net_device *dev)
225216032be5SNikolay Aleksandrov {
225316032be5SNikolay Aleksandrov 	struct virtnet_info *vi = netdev_priv(dev);
225416032be5SNikolay Aleksandrov 
225516032be5SNikolay Aleksandrov 	vi->speed = SPEED_UNKNOWN;
225616032be5SNikolay Aleksandrov 	vi->duplex = DUPLEX_UNKNOWN;
225716032be5SNikolay Aleksandrov }
225816032be5SNikolay Aleksandrov 
2259faa9b39fSJason Baron static void virtnet_update_settings(struct virtnet_info *vi)
2260faa9b39fSJason Baron {
2261faa9b39fSJason Baron 	u32 speed;
2262faa9b39fSJason Baron 	u8 duplex;
2263faa9b39fSJason Baron 
2264faa9b39fSJason Baron 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_SPEED_DUPLEX))
2265faa9b39fSJason Baron 		return;
2266faa9b39fSJason Baron 
226764ffa39dSMichael S. Tsirkin 	virtio_cread_le(vi->vdev, struct virtio_net_config, speed, &speed);
226864ffa39dSMichael S. Tsirkin 
2269faa9b39fSJason Baron 	if (ethtool_validate_speed(speed))
2270faa9b39fSJason Baron 		vi->speed = speed;
227164ffa39dSMichael S. Tsirkin 
227264ffa39dSMichael S. Tsirkin 	virtio_cread_le(vi->vdev, struct virtio_net_config, duplex, &duplex);
227364ffa39dSMichael S. Tsirkin 
2274faa9b39fSJason Baron 	if (ethtool_validate_duplex(duplex))
2275faa9b39fSJason Baron 		vi->duplex = duplex;
2276faa9b39fSJason Baron }
2277faa9b39fSJason Baron 
22780fc0b732SStephen Hemminger static const struct ethtool_ops virtnet_ethtool_ops = {
2279a51e5206SJakub Kicinski 	.supported_coalesce_params = ETHTOOL_COALESCE_MAX_FRAMES,
228066846048SRick Jones 	.get_drvinfo = virtnet_get_drvinfo,
22819f4d26d0SMark McLoughlin 	.get_link = ethtool_op_get_link,
22828f9f4668SRick Jones 	.get_ringparam = virtnet_get_ringparam,
2283d7dfc5cfSToshiaki Makita 	.get_strings = virtnet_get_strings,
2284d7dfc5cfSToshiaki Makita 	.get_sset_count = virtnet_get_sset_count,
2285d7dfc5cfSToshiaki Makita 	.get_ethtool_stats = virtnet_get_ethtool_stats,
2286d73bcd2cSJason Wang 	.set_channels = virtnet_set_channels,
2287d73bcd2cSJason Wang 	.get_channels = virtnet_get_channels,
2288074c3582SJacob Keller 	.get_ts_info = ethtool_op_get_ts_info,
2289ebb6b4b1SPhilippe Reynes 	.get_link_ksettings = virtnet_get_link_ksettings,
2290ebb6b4b1SPhilippe Reynes 	.set_link_ksettings = virtnet_set_link_ksettings,
22910c465be1SJason Wang 	.set_coalesce = virtnet_set_coalesce,
22920c465be1SJason Wang 	.get_coalesce = virtnet_get_coalesce,
2293a9ea3fc6SHerbert Xu };
2294a9ea3fc6SHerbert Xu 
22959fe7bfceSJohn Fastabend static void virtnet_freeze_down(struct virtio_device *vdev)
22969fe7bfceSJohn Fastabend {
22979fe7bfceSJohn Fastabend 	struct virtnet_info *vi = vdev->priv;
22989fe7bfceSJohn Fastabend 	int i;
22999fe7bfceSJohn Fastabend 
23009fe7bfceSJohn Fastabend 	/* Make sure no work handler is accessing the device */
23019fe7bfceSJohn Fastabend 	flush_work(&vi->config_work);
23029fe7bfceSJohn Fastabend 
230305c998b7SAke Koomsin 	netif_tx_lock_bh(vi->dev);
23049fe7bfceSJohn Fastabend 	netif_device_detach(vi->dev);
230505c998b7SAke Koomsin 	netif_tx_unlock_bh(vi->dev);
23069fe7bfceSJohn Fastabend 	cancel_delayed_work_sync(&vi->refill);
23079fe7bfceSJohn Fastabend 
23089fe7bfceSJohn Fastabend 	if (netif_running(vi->dev)) {
2309b92f1e67SWillem de Bruijn 		for (i = 0; i < vi->max_queue_pairs; i++) {
23109fe7bfceSJohn Fastabend 			napi_disable(&vi->rq[i].napi);
231178a57b48SWillem de Bruijn 			virtnet_napi_tx_disable(&vi->sq[i].napi);
2312b92f1e67SWillem de Bruijn 		}
23139fe7bfceSJohn Fastabend 	}
23149fe7bfceSJohn Fastabend }
23159fe7bfceSJohn Fastabend 
23169fe7bfceSJohn Fastabend static int init_vqs(struct virtnet_info *vi);
23179fe7bfceSJohn Fastabend 
23189fe7bfceSJohn Fastabend static int virtnet_restore_up(struct virtio_device *vdev)
23199fe7bfceSJohn Fastabend {
23209fe7bfceSJohn Fastabend 	struct virtnet_info *vi = vdev->priv;
23219fe7bfceSJohn Fastabend 	int err, i;
23229fe7bfceSJohn Fastabend 
23239fe7bfceSJohn Fastabend 	err = init_vqs(vi);
23249fe7bfceSJohn Fastabend 	if (err)
23259fe7bfceSJohn Fastabend 		return err;
23269fe7bfceSJohn Fastabend 
23279fe7bfceSJohn Fastabend 	virtio_device_ready(vdev);
23289fe7bfceSJohn Fastabend 
23299fe7bfceSJohn Fastabend 	if (netif_running(vi->dev)) {
23309fe7bfceSJohn Fastabend 		for (i = 0; i < vi->curr_queue_pairs; i++)
23319fe7bfceSJohn Fastabend 			if (!try_fill_recv(vi, &vi->rq[i], GFP_KERNEL))
23329fe7bfceSJohn Fastabend 				schedule_delayed_work(&vi->refill, 0);
23339fe7bfceSJohn Fastabend 
2334b92f1e67SWillem de Bruijn 		for (i = 0; i < vi->max_queue_pairs; i++) {
2335e4e8452aSWillem de Bruijn 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2336b92f1e67SWillem de Bruijn 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2337b92f1e67SWillem de Bruijn 					       &vi->sq[i].napi);
2338b92f1e67SWillem de Bruijn 		}
23399fe7bfceSJohn Fastabend 	}
23409fe7bfceSJohn Fastabend 
234105c998b7SAke Koomsin 	netif_tx_lock_bh(vi->dev);
23429fe7bfceSJohn Fastabend 	netif_device_attach(vi->dev);
234305c998b7SAke Koomsin 	netif_tx_unlock_bh(vi->dev);
23449fe7bfceSJohn Fastabend 	return err;
23459fe7bfceSJohn Fastabend }
23469fe7bfceSJohn Fastabend 
23473f93522fSJason Wang static int virtnet_set_guest_offloads(struct virtnet_info *vi, u64 offloads)
23483f93522fSJason Wang {
23493f93522fSJason Wang 	struct scatterlist sg;
235012e57169SMichael S. Tsirkin 	vi->ctrl->offloads = cpu_to_virtio64(vi->vdev, offloads);
23513f93522fSJason Wang 
235212e57169SMichael S. Tsirkin 	sg_init_one(&sg, &vi->ctrl->offloads, sizeof(vi->ctrl->offloads));
23533f93522fSJason Wang 
23543f93522fSJason Wang 	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_GUEST_OFFLOADS,
23553f93522fSJason Wang 				  VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET, &sg)) {
23563f93522fSJason Wang 		dev_warn(&vi->dev->dev, "Fail to set guest offload.\n");
23573f93522fSJason Wang 		return -EINVAL;
23583f93522fSJason Wang 	}
23593f93522fSJason Wang 
23603f93522fSJason Wang 	return 0;
23613f93522fSJason Wang }
23623f93522fSJason Wang 
23633f93522fSJason Wang static int virtnet_clear_guest_offloads(struct virtnet_info *vi)
23643f93522fSJason Wang {
23653f93522fSJason Wang 	u64 offloads = 0;
23663f93522fSJason Wang 
23673f93522fSJason Wang 	if (!vi->guest_offloads)
23683f93522fSJason Wang 		return 0;
23693f93522fSJason Wang 
23703f93522fSJason Wang 	return virtnet_set_guest_offloads(vi, offloads);
23713f93522fSJason Wang }
23723f93522fSJason Wang 
23733f93522fSJason Wang static int virtnet_restore_guest_offloads(struct virtnet_info *vi)
23743f93522fSJason Wang {
23753f93522fSJason Wang 	u64 offloads = vi->guest_offloads;
23763f93522fSJason Wang 
23773f93522fSJason Wang 	if (!vi->guest_offloads)
23783f93522fSJason Wang 		return 0;
23793f93522fSJason Wang 
23803f93522fSJason Wang 	return virtnet_set_guest_offloads(vi, offloads);
23813f93522fSJason Wang }
23823f93522fSJason Wang 
23839861ce03SJakub Kicinski static int virtnet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
23849861ce03SJakub Kicinski 			   struct netlink_ext_ack *extack)
2385f600b690SJohn Fastabend {
2386f600b690SJohn Fastabend 	unsigned long int max_sz = PAGE_SIZE - sizeof(struct padded_vnet_hdr);
2387f600b690SJohn Fastabend 	struct virtnet_info *vi = netdev_priv(dev);
2388f600b690SJohn Fastabend 	struct bpf_prog *old_prog;
2389017b29c3SJason Wang 	u16 xdp_qp = 0, curr_qp;
2390672aafd5SJohn Fastabend 	int i, err;
2391f600b690SJohn Fastabend 
23923f93522fSJason Wang 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)
23933f93522fSJason Wang 	    && (virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO4) ||
239492502fe8SJason Wang 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_TSO6) ||
239592502fe8SJason Wang 	        virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_ECN) ||
239618ba58e1SJason Wang 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_UFO) ||
239718ba58e1SJason Wang 		virtio_has_feature(vi->vdev, VIRTIO_NET_F_GUEST_CSUM))) {
239818ba58e1SJason Wang 		NL_SET_ERR_MSG_MOD(extack, "Can't set XDP while host is implementing LRO/CSUM, disable LRO/CSUM first");
2399f600b690SJohn Fastabend 		return -EOPNOTSUPP;
2400f600b690SJohn Fastabend 	}
2401f600b690SJohn Fastabend 
2402f600b690SJohn Fastabend 	if (vi->mergeable_rx_bufs && !vi->any_header_sg) {
24034d463c4dSDaniel Borkmann 		NL_SET_ERR_MSG_MOD(extack, "XDP expects header/data in single page, any_header_sg required");
2404f600b690SJohn Fastabend 		return -EINVAL;
2405f600b690SJohn Fastabend 	}
2406f600b690SJohn Fastabend 
2407f600b690SJohn Fastabend 	if (dev->mtu > max_sz) {
24084d463c4dSDaniel Borkmann 		NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
2409f600b690SJohn Fastabend 		netdev_warn(dev, "XDP requires MTU less than %lu\n", max_sz);
2410f600b690SJohn Fastabend 		return -EINVAL;
2411f600b690SJohn Fastabend 	}
2412f600b690SJohn Fastabend 
2413672aafd5SJohn Fastabend 	curr_qp = vi->curr_queue_pairs - vi->xdp_queue_pairs;
2414672aafd5SJohn Fastabend 	if (prog)
2415672aafd5SJohn Fastabend 		xdp_qp = nr_cpu_ids;
2416672aafd5SJohn Fastabend 
2417672aafd5SJohn Fastabend 	/* XDP requires extra queues for XDP_TX */
2418672aafd5SJohn Fastabend 	if (curr_qp + xdp_qp > vi->max_queue_pairs) {
24194d463c4dSDaniel Borkmann 		NL_SET_ERR_MSG_MOD(extack, "Too few free TX rings available");
2420672aafd5SJohn Fastabend 		netdev_warn(dev, "request %i queues but max is %i\n",
2421672aafd5SJohn Fastabend 			    curr_qp + xdp_qp, vi->max_queue_pairs);
2422672aafd5SJohn Fastabend 		return -ENOMEM;
2423672aafd5SJohn Fastabend 	}
2424672aafd5SJohn Fastabend 
242503aa6d34SToshiaki Makita 	old_prog = rtnl_dereference(vi->rq[0].xdp_prog);
242603aa6d34SToshiaki Makita 	if (!prog && !old_prog)
242703aa6d34SToshiaki Makita 		return 0;
242803aa6d34SToshiaki Makita 
242985192dbfSAndrii Nakryiko 	if (prog)
243085192dbfSAndrii Nakryiko 		bpf_prog_add(prog, vi->max_queue_pairs - 1);
24312de2f7f4SJohn Fastabend 
24324941d472SJason Wang 	/* Make sure NAPI is not using any XDP TX queues for RX. */
2433534da5e8SToshiaki Makita 	if (netif_running(dev)) {
2434534da5e8SToshiaki Makita 		for (i = 0; i < vi->max_queue_pairs; i++) {
24354941d472SJason Wang 			napi_disable(&vi->rq[i].napi);
2436534da5e8SToshiaki Makita 			virtnet_napi_tx_disable(&vi->sq[i].napi);
2437534da5e8SToshiaki Makita 		}
2438534da5e8SToshiaki Makita 	}
24392de2f7f4SJohn Fastabend 
244003aa6d34SToshiaki Makita 	if (!prog) {
244103aa6d34SToshiaki Makita 		for (i = 0; i < vi->max_queue_pairs; i++) {
244203aa6d34SToshiaki Makita 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
244303aa6d34SToshiaki Makita 			if (i == 0)
244403aa6d34SToshiaki Makita 				virtnet_restore_guest_offloads(vi);
244503aa6d34SToshiaki Makita 		}
244603aa6d34SToshiaki Makita 		synchronize_net();
244703aa6d34SToshiaki Makita 	}
244803aa6d34SToshiaki Makita 
24494941d472SJason Wang 	err = _virtnet_set_queues(vi, curr_qp + xdp_qp);
24504941d472SJason Wang 	if (err)
24514941d472SJason Wang 		goto err;
2452188313c1SToshiaki Makita 	netif_set_real_num_rx_queues(dev, curr_qp + xdp_qp);
24534941d472SJason Wang 	vi->xdp_queue_pairs = xdp_qp;
2454f600b690SJohn Fastabend 
245503aa6d34SToshiaki Makita 	if (prog) {
2456f600b690SJohn Fastabend 		for (i = 0; i < vi->max_queue_pairs; i++) {
2457f600b690SJohn Fastabend 			rcu_assign_pointer(vi->rq[i].xdp_prog, prog);
245803aa6d34SToshiaki Makita 			if (i == 0 && !old_prog)
24593f93522fSJason Wang 				virtnet_clear_guest_offloads(vi);
24603f93522fSJason Wang 		}
246103aa6d34SToshiaki Makita 	}
246203aa6d34SToshiaki Makita 
246303aa6d34SToshiaki Makita 	for (i = 0; i < vi->max_queue_pairs; i++) {
2464f600b690SJohn Fastabend 		if (old_prog)
2465f600b690SJohn Fastabend 			bpf_prog_put(old_prog);
2466534da5e8SToshiaki Makita 		if (netif_running(dev)) {
24674941d472SJason Wang 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2468534da5e8SToshiaki Makita 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2469534da5e8SToshiaki Makita 					       &vi->sq[i].napi);
2470534da5e8SToshiaki Makita 		}
2471f600b690SJohn Fastabend 	}
2472f600b690SJohn Fastabend 
2473f600b690SJohn Fastabend 	return 0;
24742de2f7f4SJohn Fastabend 
24754941d472SJason Wang err:
247603aa6d34SToshiaki Makita 	if (!prog) {
247703aa6d34SToshiaki Makita 		virtnet_clear_guest_offloads(vi);
24784941d472SJason Wang 		for (i = 0; i < vi->max_queue_pairs; i++)
247903aa6d34SToshiaki Makita 			rcu_assign_pointer(vi->rq[i].xdp_prog, old_prog);
248003aa6d34SToshiaki Makita 	}
248103aa6d34SToshiaki Makita 
24828be4d9a4SToshiaki Makita 	if (netif_running(dev)) {
2483534da5e8SToshiaki Makita 		for (i = 0; i < vi->max_queue_pairs; i++) {
24844941d472SJason Wang 			virtnet_napi_enable(vi->rq[i].vq, &vi->rq[i].napi);
2485534da5e8SToshiaki Makita 			virtnet_napi_tx_enable(vi, vi->sq[i].vq,
2486534da5e8SToshiaki Makita 					       &vi->sq[i].napi);
2487534da5e8SToshiaki Makita 		}
24888be4d9a4SToshiaki Makita 	}
24892de2f7f4SJohn Fastabend 	if (prog)
24902de2f7f4SJohn Fastabend 		bpf_prog_sub(prog, vi->max_queue_pairs - 1);
24912de2f7f4SJohn Fastabend 	return err;
2492f600b690SJohn Fastabend }
2493f600b690SJohn Fastabend 
2494f4e63525SJakub Kicinski static int virtnet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
2495f600b690SJohn Fastabend {
2496f600b690SJohn Fastabend 	switch (xdp->command) {
2497f600b690SJohn Fastabend 	case XDP_SETUP_PROG:
24989861ce03SJakub Kicinski 		return virtnet_xdp_set(dev, xdp->prog, xdp->extack);
2499f600b690SJohn Fastabend 	default:
2500f600b690SJohn Fastabend 		return -EINVAL;
2501f600b690SJohn Fastabend 	}
2502f600b690SJohn Fastabend }
2503f600b690SJohn Fastabend 
2504ba5e4426SSridhar Samudrala static int virtnet_get_phys_port_name(struct net_device *dev, char *buf,
2505ba5e4426SSridhar Samudrala 				      size_t len)
2506ba5e4426SSridhar Samudrala {
2507ba5e4426SSridhar Samudrala 	struct virtnet_info *vi = netdev_priv(dev);
2508ba5e4426SSridhar Samudrala 	int ret;
2509ba5e4426SSridhar Samudrala 
2510ba5e4426SSridhar Samudrala 	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STANDBY))
2511ba5e4426SSridhar Samudrala 		return -EOPNOTSUPP;
2512ba5e4426SSridhar Samudrala 
2513ba5e4426SSridhar Samudrala 	ret = snprintf(buf, len, "sby");
2514ba5e4426SSridhar Samudrala 	if (ret >= len)
2515ba5e4426SSridhar Samudrala 		return -EOPNOTSUPP;
2516ba5e4426SSridhar Samudrala 
2517ba5e4426SSridhar Samudrala 	return 0;
2518ba5e4426SSridhar Samudrala }
2519ba5e4426SSridhar Samudrala 
2520a02e8964SWillem de Bruijn static int virtnet_set_features(struct net_device *dev,
2521a02e8964SWillem de Bruijn 				netdev_features_t features)
2522a02e8964SWillem de Bruijn {
2523a02e8964SWillem de Bruijn 	struct virtnet_info *vi = netdev_priv(dev);
2524a02e8964SWillem de Bruijn 	u64 offloads;
2525a02e8964SWillem de Bruijn 	int err;
2526a02e8964SWillem de Bruijn 
2527a02e8964SWillem de Bruijn 	if ((dev->features ^ features) & NETIF_F_LRO) {
2528a02e8964SWillem de Bruijn 		if (vi->xdp_queue_pairs)
2529a02e8964SWillem de Bruijn 			return -EBUSY;
2530a02e8964SWillem de Bruijn 
2531a02e8964SWillem de Bruijn 		if (features & NETIF_F_LRO)
2532a02e8964SWillem de Bruijn 			offloads = vi->guest_offloads_capable;
2533a02e8964SWillem de Bruijn 		else
2534a02e8964SWillem de Bruijn 			offloads = 0;
2535a02e8964SWillem de Bruijn 
2536a02e8964SWillem de Bruijn 		err = virtnet_set_guest_offloads(vi, offloads);
2537a02e8964SWillem de Bruijn 		if (err)
2538a02e8964SWillem de Bruijn 			return err;
2539a02e8964SWillem de Bruijn 		vi->guest_offloads = offloads;
2540a02e8964SWillem de Bruijn 	}
2541a02e8964SWillem de Bruijn 
2542a02e8964SWillem de Bruijn 	return 0;
2543a02e8964SWillem de Bruijn }
2544a02e8964SWillem de Bruijn 
254576288b4eSStephen Hemminger static const struct net_device_ops virtnet_netdev = {
254676288b4eSStephen Hemminger 	.ndo_open            = virtnet_open,
254776288b4eSStephen Hemminger 	.ndo_stop   	     = virtnet_close,
254876288b4eSStephen Hemminger 	.ndo_start_xmit      = start_xmit,
254976288b4eSStephen Hemminger 	.ndo_validate_addr   = eth_validate_addr,
25509c46f6d4SAlex Williamson 	.ndo_set_mac_address = virtnet_set_mac_address,
25512af7698eSAlex Williamson 	.ndo_set_rx_mode     = virtnet_set_rx_mode,
25523fa2a1dfSstephen hemminger 	.ndo_get_stats64     = virtnet_stats,
25531824a989SAlex Williamson 	.ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
25541824a989SAlex Williamson 	.ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
2555f4e63525SJakub Kicinski 	.ndo_bpf		= virtnet_xdp,
2556186b3c99SJason Wang 	.ndo_xdp_xmit		= virtnet_xdp_xmit,
25572836b4f2SVlad Yasevich 	.ndo_features_check	= passthru_features_check,
2558ba5e4426SSridhar Samudrala 	.ndo_get_phys_port_name	= virtnet_get_phys_port_name,
2559a02e8964SWillem de Bruijn 	.ndo_set_features	= virtnet_set_features,
256076288b4eSStephen Hemminger };
256176288b4eSStephen Hemminger 
2562586d17c5SJason Wang static void virtnet_config_changed_work(struct work_struct *work)
25639f4d26d0SMark McLoughlin {
2564586d17c5SJason Wang 	struct virtnet_info *vi =
2565586d17c5SJason Wang 		container_of(work, struct virtnet_info, config_work);
25669f4d26d0SMark McLoughlin 	u16 v;
25679f4d26d0SMark McLoughlin 
2568855e0c52SRusty Russell 	if (virtio_cread_feature(vi->vdev, VIRTIO_NET_F_STATUS,
2569855e0c52SRusty Russell 				 struct virtio_net_config, status, &v) < 0)
2570507613bfSMichael S. Tsirkin 		return;
2571586d17c5SJason Wang 
2572586d17c5SJason Wang 	if (v & VIRTIO_NET_S_ANNOUNCE) {
2573ee89bab1SAmerigo Wang 		netdev_notify_peers(vi->dev);
2574586d17c5SJason Wang 		virtnet_ack_link_announce(vi);
2575586d17c5SJason Wang 	}
25769f4d26d0SMark McLoughlin 
25779f4d26d0SMark McLoughlin 	/* Ignore unknown (future) status bits */
25789f4d26d0SMark McLoughlin 	v &= VIRTIO_NET_S_LINK_UP;
25799f4d26d0SMark McLoughlin 
25809f4d26d0SMark McLoughlin 	if (vi->status == v)
2581507613bfSMichael S. Tsirkin 		return;
25829f4d26d0SMark McLoughlin 
25839f4d26d0SMark McLoughlin 	vi->status = v;
25849f4d26d0SMark McLoughlin 
25859f4d26d0SMark McLoughlin 	if (vi->status & VIRTIO_NET_S_LINK_UP) {
2586faa9b39fSJason Baron 		virtnet_update_settings(vi);
25879f4d26d0SMark McLoughlin 		netif_carrier_on(vi->dev);
2588986a4f4dSJason Wang 		netif_tx_wake_all_queues(vi->dev);
25899f4d26d0SMark McLoughlin 	} else {
25909f4d26d0SMark McLoughlin 		netif_carrier_off(vi->dev);
2591986a4f4dSJason Wang 		netif_tx_stop_all_queues(vi->dev);
25929f4d26d0SMark McLoughlin 	}
25939f4d26d0SMark McLoughlin }
25949f4d26d0SMark McLoughlin 
25959f4d26d0SMark McLoughlin static void virtnet_config_changed(struct virtio_device *vdev)
25969f4d26d0SMark McLoughlin {
25979f4d26d0SMark McLoughlin 	struct virtnet_info *vi = vdev->priv;
25989f4d26d0SMark McLoughlin 
25993b07e9caSTejun Heo 	schedule_work(&vi->config_work);
26009f4d26d0SMark McLoughlin }
26019f4d26d0SMark McLoughlin 
2602986a4f4dSJason Wang static void virtnet_free_queues(struct virtnet_info *vi)
2603986a4f4dSJason Wang {
2604d4fb84eeSAndrey Vagin 	int i;
2605d4fb84eeSAndrey Vagin 
2606ab3971b1SJason Wang 	for (i = 0; i < vi->max_queue_pairs; i++) {
2607ab3971b1SJason Wang 		napi_hash_del(&vi->rq[i].napi);
2608d4fb84eeSAndrey Vagin 		netif_napi_del(&vi->rq[i].napi);
2609b92f1e67SWillem de Bruijn 		netif_napi_del(&vi->sq[i].napi);
2610ab3971b1SJason Wang 	}
2611d4fb84eeSAndrey Vagin 
2612963abe5cSEric Dumazet 	/* We called napi_hash_del() before netif_napi_del(),
2613963abe5cSEric Dumazet 	 * we need to respect an RCU grace period before freeing vi->rq
2614963abe5cSEric Dumazet 	 */
2615963abe5cSEric Dumazet 	synchronize_net();
2616963abe5cSEric Dumazet 
2617986a4f4dSJason Wang 	kfree(vi->rq);
2618986a4f4dSJason Wang 	kfree(vi->sq);
261912e57169SMichael S. Tsirkin 	kfree(vi->ctrl);
2620986a4f4dSJason Wang }
2621986a4f4dSJason Wang 
262247315329SJohn Fastabend static void _free_receive_bufs(struct virtnet_info *vi)
2623986a4f4dSJason Wang {
2624f600b690SJohn Fastabend 	struct bpf_prog *old_prog;
2625986a4f4dSJason Wang 	int i;
2626986a4f4dSJason Wang 
2627986a4f4dSJason Wang 	for (i = 0; i < vi->max_queue_pairs; i++) {
2628986a4f4dSJason Wang 		while (vi->rq[i].pages)
2629986a4f4dSJason Wang 			__free_pages(get_a_page(&vi->rq[i], GFP_KERNEL), 0);
2630f600b690SJohn Fastabend 
2631f600b690SJohn Fastabend 		old_prog = rtnl_dereference(vi->rq[i].xdp_prog);
2632f600b690SJohn Fastabend 		RCU_INIT_POINTER(vi->rq[i].xdp_prog, NULL);
2633f600b690SJohn Fastabend 		if (old_prog)
2634f600b690SJohn Fastabend 			bpf_prog_put(old_prog);
2635986a4f4dSJason Wang 	}
263647315329SJohn Fastabend }
263747315329SJohn Fastabend 
263847315329SJohn Fastabend static void free_receive_bufs(struct virtnet_info *vi)
263947315329SJohn Fastabend {
264047315329SJohn Fastabend 	rtnl_lock();
264147315329SJohn Fastabend 	_free_receive_bufs(vi);
2642f600b690SJohn Fastabend 	rtnl_unlock();
2643986a4f4dSJason Wang }
2644986a4f4dSJason Wang 
2645fb51879dSMichael Dalton static void free_receive_page_frags(struct virtnet_info *vi)
2646fb51879dSMichael Dalton {
2647fb51879dSMichael Dalton 	int i;
2648fb51879dSMichael Dalton 	for (i = 0; i < vi->max_queue_pairs; i++)
2649fb51879dSMichael Dalton 		if (vi->rq[i].alloc_frag.page)
2650fb51879dSMichael Dalton 			put_page(vi->rq[i].alloc_frag.page);
2651fb51879dSMichael Dalton }
2652fb51879dSMichael Dalton 
2653986a4f4dSJason Wang static void free_unused_bufs(struct virtnet_info *vi)
2654986a4f4dSJason Wang {
2655986a4f4dSJason Wang 	void *buf;
2656986a4f4dSJason Wang 	int i;
2657986a4f4dSJason Wang 
2658986a4f4dSJason Wang 	for (i = 0; i < vi->max_queue_pairs; i++) {
2659986a4f4dSJason Wang 		struct virtqueue *vq = vi->sq[i].vq;
266056434a01SJohn Fastabend 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
26615050471dSToshiaki Makita 			if (!is_xdp_frame(buf))
2662986a4f4dSJason Wang 				dev_kfree_skb(buf);
266356434a01SJohn Fastabend 			else
26645050471dSToshiaki Makita 				xdp_return_frame(ptr_to_xdp(buf));
266556434a01SJohn Fastabend 		}
2666986a4f4dSJason Wang 	}
2667986a4f4dSJason Wang 
2668986a4f4dSJason Wang 	for (i = 0; i < vi->max_queue_pairs; i++) {
2669986a4f4dSJason Wang 		struct virtqueue *vq = vi->rq[i].vq;
2670986a4f4dSJason Wang 
2671986a4f4dSJason Wang 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL) {
2672ab7db917SMichael Dalton 			if (vi->mergeable_rx_bufs) {
2673680557cfSMichael S. Tsirkin 				put_page(virt_to_head_page(buf));
2674ab7db917SMichael Dalton 			} else if (vi->big_packets) {
2675fa9fac17SAndrey Vagin 				give_pages(&vi->rq[i], buf);
2676ab7db917SMichael Dalton 			} else {
2677f6b10209SJason Wang 				put_page(virt_to_head_page(buf));
2678986a4f4dSJason Wang 			}
2679986a4f4dSJason Wang 		}
2680986a4f4dSJason Wang 	}
2681ab7db917SMichael Dalton }
2682986a4f4dSJason Wang 
2683e9d7417bSJason Wang static void virtnet_del_vqs(struct virtnet_info *vi)
2684e9d7417bSJason Wang {
2685e9d7417bSJason Wang 	struct virtio_device *vdev = vi->vdev;
2686e9d7417bSJason Wang 
2687310974faSPeter Xu 	virtnet_clean_affinity(vi);
2688986a4f4dSJason Wang 
2689e9d7417bSJason Wang 	vdev->config->del_vqs(vdev);
2690986a4f4dSJason Wang 
2691986a4f4dSJason Wang 	virtnet_free_queues(vi);
2692986a4f4dSJason Wang }
2693986a4f4dSJason Wang 
2694d85b758fSMichael S. Tsirkin /* How large should a single buffer be so a queue full of these can fit at
2695d85b758fSMichael S. Tsirkin  * least one full packet?
2696d85b758fSMichael S. Tsirkin  * Logic below assumes the mergeable buffer header is used.
2697d85b758fSMichael S. Tsirkin  */
2698d85b758fSMichael S. Tsirkin static unsigned int mergeable_min_buf_len(struct virtnet_info *vi, struct virtqueue *vq)
2699d85b758fSMichael S. Tsirkin {
2700d85b758fSMichael S. Tsirkin 	const unsigned int hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
2701d85b758fSMichael S. Tsirkin 	unsigned int rq_size = virtqueue_get_vring_size(vq);
2702d85b758fSMichael S. Tsirkin 	unsigned int packet_len = vi->big_packets ? IP_MAX_MTU : vi->dev->max_mtu;
2703d85b758fSMichael S. Tsirkin 	unsigned int buf_len = hdr_len + ETH_HLEN + VLAN_HLEN + packet_len;
2704d85b758fSMichael S. Tsirkin 	unsigned int min_buf_len = DIV_ROUND_UP(buf_len, rq_size);
2705d85b758fSMichael S. Tsirkin 
2706f0c3192cSMichael S. Tsirkin 	return max(max(min_buf_len, hdr_len) - hdr_len,
2707f0c3192cSMichael S. Tsirkin 		   (unsigned int)GOOD_PACKET_LEN);
2708d85b758fSMichael S. Tsirkin }
2709d85b758fSMichael S. Tsirkin 
2710986a4f4dSJason Wang static int virtnet_find_vqs(struct virtnet_info *vi)
2711986a4f4dSJason Wang {
2712986a4f4dSJason Wang 	vq_callback_t **callbacks;
2713986a4f4dSJason Wang 	struct virtqueue **vqs;
2714986a4f4dSJason Wang 	int ret = -ENOMEM;
2715986a4f4dSJason Wang 	int i, total_vqs;
2716986a4f4dSJason Wang 	const char **names;
2717d45b897bSMichael S. Tsirkin 	bool *ctx;
2718986a4f4dSJason Wang 
2719986a4f4dSJason Wang 	/* We expect 1 RX virtqueue followed by 1 TX virtqueue, followed by
2720986a4f4dSJason Wang 	 * possible N-1 RX/TX queue pairs used in multiqueue mode, followed by
2721986a4f4dSJason Wang 	 * possible control vq.
2722986a4f4dSJason Wang 	 */
2723986a4f4dSJason Wang 	total_vqs = vi->max_queue_pairs * 2 +
2724986a4f4dSJason Wang 		    virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ);
2725986a4f4dSJason Wang 
2726986a4f4dSJason Wang 	/* Allocate space for find_vqs parameters */
27276396bb22SKees Cook 	vqs = kcalloc(total_vqs, sizeof(*vqs), GFP_KERNEL);
2728986a4f4dSJason Wang 	if (!vqs)
2729986a4f4dSJason Wang 		goto err_vq;
27306da2ec56SKees Cook 	callbacks = kmalloc_array(total_vqs, sizeof(*callbacks), GFP_KERNEL);
2731986a4f4dSJason Wang 	if (!callbacks)
2732986a4f4dSJason Wang 		goto err_callback;
27336da2ec56SKees Cook 	names = kmalloc_array(total_vqs, sizeof(*names), GFP_KERNEL);
2734986a4f4dSJason Wang 	if (!names)
2735986a4f4dSJason Wang 		goto err_names;
2736192f68cfSJason Wang 	if (!vi->big_packets || vi->mergeable_rx_bufs) {
27376396bb22SKees Cook 		ctx = kcalloc(total_vqs, sizeof(*ctx), GFP_KERNEL);
2738d45b897bSMichael S. Tsirkin 		if (!ctx)
2739d45b897bSMichael S. Tsirkin 			goto err_ctx;
2740d45b897bSMichael S. Tsirkin 	} else {
2741d45b897bSMichael S. Tsirkin 		ctx = NULL;
2742d45b897bSMichael S. Tsirkin 	}
2743986a4f4dSJason Wang 
2744986a4f4dSJason Wang 	/* Parameters for control virtqueue, if any */
2745986a4f4dSJason Wang 	if (vi->has_cvq) {
2746986a4f4dSJason Wang 		callbacks[total_vqs - 1] = NULL;
2747986a4f4dSJason Wang 		names[total_vqs - 1] = "control";
2748986a4f4dSJason Wang 	}
2749986a4f4dSJason Wang 
2750986a4f4dSJason Wang 	/* Allocate/initialize parameters for send/receive virtqueues */
2751986a4f4dSJason Wang 	for (i = 0; i < vi->max_queue_pairs; i++) {
2752986a4f4dSJason Wang 		callbacks[rxq2vq(i)] = skb_recv_done;
2753986a4f4dSJason Wang 		callbacks[txq2vq(i)] = skb_xmit_done;
2754986a4f4dSJason Wang 		sprintf(vi->rq[i].name, "input.%d", i);
2755986a4f4dSJason Wang 		sprintf(vi->sq[i].name, "output.%d", i);
2756986a4f4dSJason Wang 		names[rxq2vq(i)] = vi->rq[i].name;
2757986a4f4dSJason Wang 		names[txq2vq(i)] = vi->sq[i].name;
2758d45b897bSMichael S. Tsirkin 		if (ctx)
2759d45b897bSMichael S. Tsirkin 			ctx[rxq2vq(i)] = true;
2760986a4f4dSJason Wang 	}
2761986a4f4dSJason Wang 
2762986a4f4dSJason Wang 	ret = vi->vdev->config->find_vqs(vi->vdev, total_vqs, vqs, callbacks,
2763d45b897bSMichael S. Tsirkin 					 names, ctx, NULL);
2764986a4f4dSJason Wang 	if (ret)
2765986a4f4dSJason Wang 		goto err_find;
2766986a4f4dSJason Wang 
2767986a4f4dSJason Wang 	if (vi->has_cvq) {
2768986a4f4dSJason Wang 		vi->cvq = vqs[total_vqs - 1];
2769986a4f4dSJason Wang 		if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
2770f646968fSPatrick McHardy 			vi->dev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
2771986a4f4dSJason Wang 	}
2772986a4f4dSJason Wang 
2773986a4f4dSJason Wang 	for (i = 0; i < vi->max_queue_pairs; i++) {
2774986a4f4dSJason Wang 		vi->rq[i].vq = vqs[rxq2vq(i)];
2775d85b758fSMichael S. Tsirkin 		vi->rq[i].min_buf_len = mergeable_min_buf_len(vi, vi->rq[i].vq);
2776986a4f4dSJason Wang 		vi->sq[i].vq = vqs[txq2vq(i)];
2777986a4f4dSJason Wang 	}
2778986a4f4dSJason Wang 
27792fa3c8a8STonghao Zhang 	/* run here: ret == 0. */
2780986a4f4dSJason Wang 
2781986a4f4dSJason Wang 
2782986a4f4dSJason Wang err_find:
2783d45b897bSMichael S. Tsirkin 	kfree(ctx);
2784d45b897bSMichael S. Tsirkin err_ctx:
2785986a4f4dSJason Wang 	kfree(names);
2786986a4f4dSJason Wang err_names:
2787986a4f4dSJason Wang 	kfree(callbacks);
2788986a4f4dSJason Wang err_callback:
2789986a4f4dSJason Wang 	kfree(vqs);
2790986a4f4dSJason Wang err_vq:
2791986a4f4dSJason Wang 	return ret;
2792986a4f4dSJason Wang }
2793986a4f4dSJason Wang 
2794986a4f4dSJason Wang static int virtnet_alloc_queues(struct virtnet_info *vi)
2795986a4f4dSJason Wang {
2796986a4f4dSJason Wang 	int i;
2797986a4f4dSJason Wang 
279812e57169SMichael S. Tsirkin 	vi->ctrl = kzalloc(sizeof(*vi->ctrl), GFP_KERNEL);
279912e57169SMichael S. Tsirkin 	if (!vi->ctrl)
280012e57169SMichael S. Tsirkin 		goto err_ctrl;
28016396bb22SKees Cook 	vi->sq = kcalloc(vi->max_queue_pairs, sizeof(*vi->sq), GFP_KERNEL);
2802986a4f4dSJason Wang 	if (!vi->sq)
2803986a4f4dSJason Wang 		goto err_sq;
28046396bb22SKees Cook 	vi->rq = kcalloc(vi->max_queue_pairs, sizeof(*vi->rq), GFP_KERNEL);
2805008d4278SAmerigo Wang 	if (!vi->rq)
2806986a4f4dSJason Wang 		goto err_rq;
2807986a4f4dSJason Wang 
2808986a4f4dSJason Wang 	INIT_DELAYED_WORK(&vi->refill, refill_work);
2809986a4f4dSJason Wang 	for (i = 0; i < vi->max_queue_pairs; i++) {
2810986a4f4dSJason Wang 		vi->rq[i].pages = NULL;
2811986a4f4dSJason Wang 		netif_napi_add(vi->dev, &vi->rq[i].napi, virtnet_poll,
2812986a4f4dSJason Wang 			       napi_weight);
28131d11e732SWillem de Bruijn 		netif_tx_napi_add(vi->dev, &vi->sq[i].napi, virtnet_poll_tx,
2814b92f1e67SWillem de Bruijn 				  napi_tx ? napi_weight : 0);
2815986a4f4dSJason Wang 
2816986a4f4dSJason Wang 		sg_init_table(vi->rq[i].sg, ARRAY_SIZE(vi->rq[i].sg));
28175377d758SJohannes Berg 		ewma_pkt_len_init(&vi->rq[i].mrg_avg_pkt_len);
2818986a4f4dSJason Wang 		sg_init_table(vi->sq[i].sg, ARRAY_SIZE(vi->sq[i].sg));
2819d7dfc5cfSToshiaki Makita 
2820d7dfc5cfSToshiaki Makita 		u64_stats_init(&vi->rq[i].stats.syncp);
2821d7dfc5cfSToshiaki Makita 		u64_stats_init(&vi->sq[i].stats.syncp);
2822986a4f4dSJason Wang 	}
2823986a4f4dSJason Wang 
2824986a4f4dSJason Wang 	return 0;
2825986a4f4dSJason Wang 
2826986a4f4dSJason Wang err_rq:
2827986a4f4dSJason Wang 	kfree(vi->sq);
2828986a4f4dSJason Wang err_sq:
282912e57169SMichael S. Tsirkin 	kfree(vi->ctrl);
283012e57169SMichael S. Tsirkin err_ctrl:
2831986a4f4dSJason Wang 	return -ENOMEM;
2832e9d7417bSJason Wang }
2833e9d7417bSJason Wang 
28343f9c10b0SAmit Shah static int init_vqs(struct virtnet_info *vi)
28353f9c10b0SAmit Shah {
2836986a4f4dSJason Wang 	int ret;
28373f9c10b0SAmit Shah 
2838986a4f4dSJason Wang 	/* Allocate send & receive queues */
2839986a4f4dSJason Wang 	ret = virtnet_alloc_queues(vi);
2840986a4f4dSJason Wang 	if (ret)
2841986a4f4dSJason Wang 		goto err;
28423f9c10b0SAmit Shah 
2843986a4f4dSJason Wang 	ret = virtnet_find_vqs(vi);
2844986a4f4dSJason Wang 	if (ret)
2845986a4f4dSJason Wang 		goto err_free;
28463f9c10b0SAmit Shah 
284747be2479SWanlong Gao 	get_online_cpus();
28488898c21cSWanlong Gao 	virtnet_set_affinity(vi);
284947be2479SWanlong Gao 	put_online_cpus();
285047be2479SWanlong Gao 
28513f9c10b0SAmit Shah 	return 0;
2852986a4f4dSJason Wang 
2853986a4f4dSJason Wang err_free:
2854986a4f4dSJason Wang 	virtnet_free_queues(vi);
2855986a4f4dSJason Wang err:
2856986a4f4dSJason Wang 	return ret;
28573f9c10b0SAmit Shah }
28583f9c10b0SAmit Shah 
2859fbf28d78SMichael Dalton #ifdef CONFIG_SYSFS
2860fbf28d78SMichael Dalton static ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
2861718ad681Sstephen hemminger 		char *buf)
2862fbf28d78SMichael Dalton {
2863fbf28d78SMichael Dalton 	struct virtnet_info *vi = netdev_priv(queue->dev);
2864fbf28d78SMichael Dalton 	unsigned int queue_index = get_netdev_rx_queue_index(queue);
28653cc81a9aSJason Wang 	unsigned int headroom = virtnet_get_headroom(vi);
28663cc81a9aSJason Wang 	unsigned int tailroom = headroom ? sizeof(struct skb_shared_info) : 0;
28675377d758SJohannes Berg 	struct ewma_pkt_len *avg;
2868fbf28d78SMichael Dalton 
2869fbf28d78SMichael Dalton 	BUG_ON(queue_index >= vi->max_queue_pairs);
2870fbf28d78SMichael Dalton 	avg = &vi->rq[queue_index].mrg_avg_pkt_len;
2871d85b758fSMichael S. Tsirkin 	return sprintf(buf, "%u\n",
28723cc81a9aSJason Wang 		       get_mergeable_buf_len(&vi->rq[queue_index], avg,
28733cc81a9aSJason Wang 				       SKB_DATA_ALIGN(headroom + tailroom)));
2874fbf28d78SMichael Dalton }
2875fbf28d78SMichael Dalton 
2876fbf28d78SMichael Dalton static struct rx_queue_attribute mergeable_rx_buffer_size_attribute =
2877fbf28d78SMichael Dalton 	__ATTR_RO(mergeable_rx_buffer_size);
2878fbf28d78SMichael Dalton 
2879fbf28d78SMichael Dalton static struct attribute *virtio_net_mrg_rx_attrs[] = {
2880fbf28d78SMichael Dalton 	&mergeable_rx_buffer_size_attribute.attr,
2881fbf28d78SMichael Dalton 	NULL
2882fbf28d78SMichael Dalton };
2883fbf28d78SMichael Dalton 
2884fbf28d78SMichael Dalton static const struct attribute_group virtio_net_mrg_rx_group = {
2885fbf28d78SMichael Dalton 	.name = "virtio_net",
2886fbf28d78SMichael Dalton 	.attrs = virtio_net_mrg_rx_attrs
2887fbf28d78SMichael Dalton };
2888fbf28d78SMichael Dalton #endif
2889fbf28d78SMichael Dalton 
2890892d6eb1SJason Wang static bool virtnet_fail_on_feature(struct virtio_device *vdev,
2891892d6eb1SJason Wang 				    unsigned int fbit,
2892892d6eb1SJason Wang 				    const char *fname, const char *dname)
2893892d6eb1SJason Wang {
2894892d6eb1SJason Wang 	if (!virtio_has_feature(vdev, fbit))
2895892d6eb1SJason Wang 		return false;
2896892d6eb1SJason Wang 
2897892d6eb1SJason Wang 	dev_err(&vdev->dev, "device advertises feature %s but not %s",
2898892d6eb1SJason Wang 		fname, dname);
2899892d6eb1SJason Wang 
2900892d6eb1SJason Wang 	return true;
2901892d6eb1SJason Wang }
2902892d6eb1SJason Wang 
2903892d6eb1SJason Wang #define VIRTNET_FAIL_ON(vdev, fbit, dbit)			\
2904892d6eb1SJason Wang 	virtnet_fail_on_feature(vdev, fbit, #fbit, dbit)
2905892d6eb1SJason Wang 
2906892d6eb1SJason Wang static bool virtnet_validate_features(struct virtio_device *vdev)
2907892d6eb1SJason Wang {
2908892d6eb1SJason Wang 	if (!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) &&
2909892d6eb1SJason Wang 	    (VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_RX,
2910892d6eb1SJason Wang 			     "VIRTIO_NET_F_CTRL_VQ") ||
2911892d6eb1SJason Wang 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_VLAN,
2912892d6eb1SJason Wang 			     "VIRTIO_NET_F_CTRL_VQ") ||
2913892d6eb1SJason Wang 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE,
2914892d6eb1SJason Wang 			     "VIRTIO_NET_F_CTRL_VQ") ||
2915892d6eb1SJason Wang 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_MQ, "VIRTIO_NET_F_CTRL_VQ") ||
2916892d6eb1SJason Wang 	     VIRTNET_FAIL_ON(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR,
2917892d6eb1SJason Wang 			     "VIRTIO_NET_F_CTRL_VQ"))) {
2918892d6eb1SJason Wang 		return false;
2919892d6eb1SJason Wang 	}
2920892d6eb1SJason Wang 
2921892d6eb1SJason Wang 	return true;
2922892d6eb1SJason Wang }
2923892d6eb1SJason Wang 
2924d0c2c997SJarod Wilson #define MIN_MTU ETH_MIN_MTU
2925d0c2c997SJarod Wilson #define MAX_MTU ETH_MAX_MTU
2926d0c2c997SJarod Wilson 
2927fe36cbe0SMichael S. Tsirkin static int virtnet_validate(struct virtio_device *vdev)
2928296f96fcSRusty Russell {
29296ba42248SMichael S. Tsirkin 	if (!vdev->config->get) {
29306ba42248SMichael S. Tsirkin 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
29316ba42248SMichael S. Tsirkin 			__func__);
29326ba42248SMichael S. Tsirkin 		return -EINVAL;
29336ba42248SMichael S. Tsirkin 	}
29346ba42248SMichael S. Tsirkin 
2935892d6eb1SJason Wang 	if (!virtnet_validate_features(vdev))
2936892d6eb1SJason Wang 		return -EINVAL;
2937892d6eb1SJason Wang 
2938fe36cbe0SMichael S. Tsirkin 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
2939fe36cbe0SMichael S. Tsirkin 		int mtu = virtio_cread16(vdev,
2940fe36cbe0SMichael S. Tsirkin 					 offsetof(struct virtio_net_config,
2941fe36cbe0SMichael S. Tsirkin 						  mtu));
2942fe36cbe0SMichael S. Tsirkin 		if (mtu < MIN_MTU)
2943fe36cbe0SMichael S. Tsirkin 			__virtio_clear_bit(vdev, VIRTIO_NET_F_MTU);
2944fe36cbe0SMichael S. Tsirkin 	}
2945fe36cbe0SMichael S. Tsirkin 
2946fe36cbe0SMichael S. Tsirkin 	return 0;
2947fe36cbe0SMichael S. Tsirkin }
2948fe36cbe0SMichael S. Tsirkin 
2949fe36cbe0SMichael S. Tsirkin static int virtnet_probe(struct virtio_device *vdev)
2950fe36cbe0SMichael S. Tsirkin {
2951d7dfc5cfSToshiaki Makita 	int i, err = -ENOMEM;
2952fe36cbe0SMichael S. Tsirkin 	struct net_device *dev;
2953fe36cbe0SMichael S. Tsirkin 	struct virtnet_info *vi;
2954fe36cbe0SMichael S. Tsirkin 	u16 max_queue_pairs;
2955fe36cbe0SMichael S. Tsirkin 	int mtu;
2956fe36cbe0SMichael S. Tsirkin 
2957986a4f4dSJason Wang 	/* Find if host supports multiqueue virtio_net device */
2958855e0c52SRusty Russell 	err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
2959855e0c52SRusty Russell 				   struct virtio_net_config,
2960855e0c52SRusty Russell 				   max_virtqueue_pairs, &max_queue_pairs);
2961986a4f4dSJason Wang 
2962986a4f4dSJason Wang 	/* We need at least 2 queue's */
2963986a4f4dSJason Wang 	if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
2964986a4f4dSJason Wang 	    max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
2965986a4f4dSJason Wang 	    !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
2966986a4f4dSJason Wang 		max_queue_pairs = 1;
2967296f96fcSRusty Russell 
2968296f96fcSRusty Russell 	/* Allocate ourselves a network device with room for our info */
2969986a4f4dSJason Wang 	dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
2970296f96fcSRusty Russell 	if (!dev)
2971296f96fcSRusty Russell 		return -ENOMEM;
2972296f96fcSRusty Russell 
2973296f96fcSRusty Russell 	/* Set up network device as normal. */
2974f2f2c8b4SJiri Pirko 	dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
297576288b4eSStephen Hemminger 	dev->netdev_ops = &virtnet_netdev;
2976296f96fcSRusty Russell 	dev->features = NETIF_F_HIGHDMA;
29773fa2a1dfSstephen hemminger 
29787ad24ea4SWilfried Klaebe 	dev->ethtool_ops = &virtnet_ethtool_ops;
2979296f96fcSRusty Russell 	SET_NETDEV_DEV(dev, &vdev->dev);
2980296f96fcSRusty Russell 
2981296f96fcSRusty Russell 	/* Do we support "hardware" checksums? */
298298e778c9SMichał Mirosław 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
2983296f96fcSRusty Russell 		/* This opens up the world of extra features. */
298448900cb6SJason Wang 		dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG;
298598e778c9SMichał Mirosław 		if (csum)
298648900cb6SJason Wang 			dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG;
298798e778c9SMichał Mirosław 
298898e778c9SMichał Mirosław 		if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
2989e078de03SDavid S. Miller 			dev->hw_features |= NETIF_F_TSO
299034a48579SRusty Russell 				| NETIF_F_TSO_ECN | NETIF_F_TSO6;
299134a48579SRusty Russell 		}
29925539ae96SRusty Russell 		/* Individual feature bits: what can host handle? */
299398e778c9SMichał Mirosław 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
299498e778c9SMichał Mirosław 			dev->hw_features |= NETIF_F_TSO;
299598e778c9SMichał Mirosław 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
299698e778c9SMichał Mirosław 			dev->hw_features |= NETIF_F_TSO6;
299798e778c9SMichał Mirosław 		if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
299898e778c9SMichał Mirosław 			dev->hw_features |= NETIF_F_TSO_ECN;
299998e778c9SMichał Mirosław 
300041f2f127SJason Wang 		dev->features |= NETIF_F_GSO_ROBUST;
300141f2f127SJason Wang 
300298e778c9SMichał Mirosław 		if (gso)
3003e078de03SDavid S. Miller 			dev->features |= dev->hw_features & NETIF_F_ALL_TSO;
300498e778c9SMichał Mirosław 		/* (!csum && gso) case will be fixed by register_netdev() */
3005296f96fcSRusty Russell 	}
30064f49129bSThomas Huth 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
30074f49129bSThomas Huth 		dev->features |= NETIF_F_RXCSUM;
3008a02e8964SWillem de Bruijn 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
3009a02e8964SWillem de Bruijn 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6))
3010a02e8964SWillem de Bruijn 		dev->features |= NETIF_F_LRO;
3011a02e8964SWillem de Bruijn 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS))
3012a02e8964SWillem de Bruijn 		dev->hw_features |= NETIF_F_LRO;
3013296f96fcSRusty Russell 
30144fda8302SJason Wang 	dev->vlan_features = dev->features;
30154fda8302SJason Wang 
3016d0c2c997SJarod Wilson 	/* MTU range: 68 - 65535 */
3017d0c2c997SJarod Wilson 	dev->min_mtu = MIN_MTU;
3018d0c2c997SJarod Wilson 	dev->max_mtu = MAX_MTU;
3019d0c2c997SJarod Wilson 
3020296f96fcSRusty Russell 	/* Configuration may specify what MAC to use.  Otherwise random. */
3021855e0c52SRusty Russell 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
3022855e0c52SRusty Russell 		virtio_cread_bytes(vdev,
3023a586d4f6SRusty Russell 				   offsetof(struct virtio_net_config, mac),
3024855e0c52SRusty Russell 				   dev->dev_addr, dev->addr_len);
3025855e0c52SRusty Russell 	else
3026f2cedb63SDanny Kukawka 		eth_hw_addr_random(dev);
3027296f96fcSRusty Russell 
3028296f96fcSRusty Russell 	/* Set up our device-specific information */
3029296f96fcSRusty Russell 	vi = netdev_priv(dev);
3030296f96fcSRusty Russell 	vi->dev = dev;
3031296f96fcSRusty Russell 	vi->vdev = vdev;
3032d9d5dcc8SChristian Borntraeger 	vdev->priv = vi;
3033827da44cSJohn Stultz 
3034586d17c5SJason Wang 	INIT_WORK(&vi->config_work, virtnet_config_changed_work);
3035296f96fcSRusty Russell 
303697402b96SHerbert Xu 	/* If we can receive ANY GSO packets, we must allocate large ones. */
30378e95a202SJoe Perches 	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
30388e95a202SJoe Perches 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
3039e3e3c423SVlad Yasevich 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
3040e3e3c423SVlad Yasevich 	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
304197402b96SHerbert Xu 		vi->big_packets = true;
304297402b96SHerbert Xu 
30433f2c31d9SMark McLoughlin 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
30443f2c31d9SMark McLoughlin 		vi->mergeable_rx_bufs = true;
30453f2c31d9SMark McLoughlin 
3046d04302b3SMichael S. Tsirkin 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
3047d04302b3SMichael S. Tsirkin 	    virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3048012873d0SMichael S. Tsirkin 		vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
3049012873d0SMichael S. Tsirkin 	else
3050012873d0SMichael S. Tsirkin 		vi->hdr_len = sizeof(struct virtio_net_hdr);
3051012873d0SMichael S. Tsirkin 
305275993300SMichael S. Tsirkin 	if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
305375993300SMichael S. Tsirkin 	    virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
3054e7428e95SMichael S. Tsirkin 		vi->any_header_sg = true;
3055e7428e95SMichael S. Tsirkin 
3056986a4f4dSJason Wang 	if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
3057986a4f4dSJason Wang 		vi->has_cvq = true;
3058986a4f4dSJason Wang 
305914de9d11SAaron Conole 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MTU)) {
306014de9d11SAaron Conole 		mtu = virtio_cread16(vdev,
306114de9d11SAaron Conole 				     offsetof(struct virtio_net_config,
306214de9d11SAaron Conole 					      mtu));
306393a205eeSAaron Conole 		if (mtu < dev->min_mtu) {
3064fe36cbe0SMichael S. Tsirkin 			/* Should never trigger: MTU was previously validated
3065fe36cbe0SMichael S. Tsirkin 			 * in virtnet_validate.
3066fe36cbe0SMichael S. Tsirkin 			 */
30677934b481SYuval Shaia 			dev_err(&vdev->dev,
30687934b481SYuval Shaia 				"device MTU appears to have changed it is now %d < %d",
30697934b481SYuval Shaia 				mtu, dev->min_mtu);
3070d7dfc5cfSToshiaki Makita 			goto free;
3071fe36cbe0SMichael S. Tsirkin 		}
3072fe36cbe0SMichael S. Tsirkin 
3073d0c2c997SJarod Wilson 		dev->mtu = mtu;
307493a205eeSAaron Conole 		dev->max_mtu = mtu;
30752e123b44SMichael S. Tsirkin 
30762e123b44SMichael S. Tsirkin 		/* TODO: size buffers correctly in this case. */
30772e123b44SMichael S. Tsirkin 		if (dev->mtu > ETH_DATA_LEN)
30782e123b44SMichael S. Tsirkin 			vi->big_packets = true;
307914de9d11SAaron Conole 	}
308014de9d11SAaron Conole 
3081012873d0SMichael S. Tsirkin 	if (vi->any_header_sg)
3082012873d0SMichael S. Tsirkin 		dev->needed_headroom = vi->hdr_len;
30836ebbc1a6SZhangjie \(HZ\) 
308444900010SJason Wang 	/* Enable multiqueue by default */
308544900010SJason Wang 	if (num_online_cpus() >= max_queue_pairs)
308644900010SJason Wang 		vi->curr_queue_pairs = max_queue_pairs;
308744900010SJason Wang 	else
308844900010SJason Wang 		vi->curr_queue_pairs = num_online_cpus();
3089986a4f4dSJason Wang 	vi->max_queue_pairs = max_queue_pairs;
3090986a4f4dSJason Wang 
3091986a4f4dSJason Wang 	/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
30923f9c10b0SAmit Shah 	err = init_vqs(vi);
3093d2a7dddaSMichael S. Tsirkin 	if (err)
3094d7dfc5cfSToshiaki Makita 		goto free;
3095d2a7dddaSMichael S. Tsirkin 
3096fbf28d78SMichael Dalton #ifdef CONFIG_SYSFS
3097fbf28d78SMichael Dalton 	if (vi->mergeable_rx_bufs)
3098fbf28d78SMichael Dalton 		dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
3099fbf28d78SMichael Dalton #endif
31000f13b66bSZhi Yong Wu 	netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
31010f13b66bSZhi Yong Wu 	netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
3102986a4f4dSJason Wang 
310316032be5SNikolay Aleksandrov 	virtnet_init_settings(dev);
310416032be5SNikolay Aleksandrov 
3105ba5e4426SSridhar Samudrala 	if (virtio_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
3106ba5e4426SSridhar Samudrala 		vi->failover = net_failover_create(vi->dev);
31074b8e6ac4SWei Yongjun 		if (IS_ERR(vi->failover)) {
31084b8e6ac4SWei Yongjun 			err = PTR_ERR(vi->failover);
3109ba5e4426SSridhar Samudrala 			goto free_vqs;
3110ba5e4426SSridhar Samudrala 		}
31114b8e6ac4SWei Yongjun 	}
3112ba5e4426SSridhar Samudrala 
3113296f96fcSRusty Russell 	err = register_netdev(dev);
3114296f96fcSRusty Russell 	if (err) {
3115296f96fcSRusty Russell 		pr_debug("virtio_net: registering device failed\n");
3116ba5e4426SSridhar Samudrala 		goto free_failover;
3117296f96fcSRusty Russell 	}
3118b3369c1fSRusty Russell 
31194baf1e33SMichael S. Tsirkin 	virtio_device_ready(vdev);
31204baf1e33SMichael S. Tsirkin 
31218017c279SSebastian Andrzej Siewior 	err = virtnet_cpu_notif_add(vi);
31228de4b2f3SWanlong Gao 	if (err) {
31238de4b2f3SWanlong Gao 		pr_debug("virtio_net: registering cpu notifier failed\n");
3124f00e35e2Swangyunjian 		goto free_unregister_netdev;
31258de4b2f3SWanlong Gao 	}
31268de4b2f3SWanlong Gao 
3127a220871bSJason Wang 	virtnet_set_queues(vi, vi->curr_queue_pairs);
312844900010SJason Wang 
3129167c25e4SJason Wang 	/* Assume link up if device can't report link status,
3130167c25e4SJason Wang 	   otherwise get link status from config. */
3131167c25e4SJason Wang 	netif_carrier_off(dev);
3132bda7fab5SJay Vosburgh 	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
31333b07e9caSTejun Heo 		schedule_work(&vi->config_work);
3134167c25e4SJason Wang 	} else {
3135167c25e4SJason Wang 		vi->status = VIRTIO_NET_S_LINK_UP;
3136faa9b39fSJason Baron 		virtnet_update_settings(vi);
31374783256eSPantelis Koukousoulas 		netif_carrier_on(dev);
3138167c25e4SJason Wang 	}
31399f4d26d0SMark McLoughlin 
31403f93522fSJason Wang 	for (i = 0; i < ARRAY_SIZE(guest_offloads); i++)
31413f93522fSJason Wang 		if (virtio_has_feature(vi->vdev, guest_offloads[i]))
31423f93522fSJason Wang 			set_bit(guest_offloads[i], &vi->guest_offloads);
3143a02e8964SWillem de Bruijn 	vi->guest_offloads_capable = vi->guest_offloads;
31443f93522fSJason Wang 
3145986a4f4dSJason Wang 	pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
3146986a4f4dSJason Wang 		 dev->name, max_queue_pairs);
3147986a4f4dSJason Wang 
3148296f96fcSRusty Russell 	return 0;
3149296f96fcSRusty Russell 
3150f00e35e2Swangyunjian free_unregister_netdev:
315102465555SMichael S. Tsirkin 	vi->vdev->config->reset(vdev);
315202465555SMichael S. Tsirkin 
3153b3369c1fSRusty Russell 	unregister_netdev(dev);
3154ba5e4426SSridhar Samudrala free_failover:
3155ba5e4426SSridhar Samudrala 	net_failover_destroy(vi->failover);
3156d2a7dddaSMichael S. Tsirkin free_vqs:
3157986a4f4dSJason Wang 	cancel_delayed_work_sync(&vi->refill);
3158fb51879dSMichael Dalton 	free_receive_page_frags(vi);
3159e9d7417bSJason Wang 	virtnet_del_vqs(vi);
3160296f96fcSRusty Russell free:
3161296f96fcSRusty Russell 	free_netdev(dev);
3162296f96fcSRusty Russell 	return err;
3163296f96fcSRusty Russell }
3164296f96fcSRusty Russell 
316504486ed0SAmit Shah static void remove_vq_common(struct virtnet_info *vi)
3166296f96fcSRusty Russell {
316704486ed0SAmit Shah 	vi->vdev->config->reset(vi->vdev);
3168830a8a97SShirley Ma 
3169830a8a97SShirley Ma 	/* Free unused buffers in both send and recv, if any. */
31709ab86bbcSShirley Ma 	free_unused_bufs(vi);
3171fb6813f4SRusty Russell 
3172986a4f4dSJason Wang 	free_receive_bufs(vi);
3173d2a7dddaSMichael S. Tsirkin 
3174fb51879dSMichael Dalton 	free_receive_page_frags(vi);
3175fb51879dSMichael Dalton 
3176986a4f4dSJason Wang 	virtnet_del_vqs(vi);
317704486ed0SAmit Shah }
317804486ed0SAmit Shah 
31798cc085d6SBill Pemberton static void virtnet_remove(struct virtio_device *vdev)
318004486ed0SAmit Shah {
318104486ed0SAmit Shah 	struct virtnet_info *vi = vdev->priv;
318204486ed0SAmit Shah 
31838017c279SSebastian Andrzej Siewior 	virtnet_cpu_notif_remove(vi);
31848de4b2f3SWanlong Gao 
3185102a2786SMichael S. Tsirkin 	/* Make sure no work handler is accessing the device. */
3186102a2786SMichael S. Tsirkin 	flush_work(&vi->config_work);
3187586d17c5SJason Wang 
318804486ed0SAmit Shah 	unregister_netdev(vi->dev);
318904486ed0SAmit Shah 
3190ba5e4426SSridhar Samudrala 	net_failover_destroy(vi->failover);
3191ba5e4426SSridhar Samudrala 
319204486ed0SAmit Shah 	remove_vq_common(vi);
3193fb6813f4SRusty Russell 
319474b2553fSRusty Russell 	free_netdev(vi->dev);
3195296f96fcSRusty Russell }
3196296f96fcSRusty Russell 
319767a75194SArnd Bergmann static __maybe_unused int virtnet_freeze(struct virtio_device *vdev)
31980741bcb5SAmit Shah {
31990741bcb5SAmit Shah 	struct virtnet_info *vi = vdev->priv;
32000741bcb5SAmit Shah 
32018017c279SSebastian Andrzej Siewior 	virtnet_cpu_notif_remove(vi);
32029fe7bfceSJohn Fastabend 	virtnet_freeze_down(vdev);
32030741bcb5SAmit Shah 	remove_vq_common(vi);
32040741bcb5SAmit Shah 
32050741bcb5SAmit Shah 	return 0;
32060741bcb5SAmit Shah }
32070741bcb5SAmit Shah 
320867a75194SArnd Bergmann static __maybe_unused int virtnet_restore(struct virtio_device *vdev)
32090741bcb5SAmit Shah {
32100741bcb5SAmit Shah 	struct virtnet_info *vi = vdev->priv;
32119fe7bfceSJohn Fastabend 	int err;
32120741bcb5SAmit Shah 
32139fe7bfceSJohn Fastabend 	err = virtnet_restore_up(vdev);
32140741bcb5SAmit Shah 	if (err)
32150741bcb5SAmit Shah 		return err;
3216986a4f4dSJason Wang 	virtnet_set_queues(vi, vi->curr_queue_pairs);
3217986a4f4dSJason Wang 
32188017c279SSebastian Andrzej Siewior 	err = virtnet_cpu_notif_add(vi);
3219ec9debbdSJason Wang 	if (err)
3220ec9debbdSJason Wang 		return err;
3221ec9debbdSJason Wang 
32220741bcb5SAmit Shah 	return 0;
32230741bcb5SAmit Shah }
32240741bcb5SAmit Shah 
3225296f96fcSRusty Russell static struct virtio_device_id id_table[] = {
3226296f96fcSRusty Russell 	{ VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
3227296f96fcSRusty Russell 	{ 0 },
3228296f96fcSRusty Russell };
3229296f96fcSRusty Russell 
3230f3358507SMichael S. Tsirkin #define VIRTNET_FEATURES \
3231f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM, \
3232f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_MAC, \
3233f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6, \
3234f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6, \
3235f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO, \
3236f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ, \
3237f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN, \
3238f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_GUEST_ANNOUNCE, VIRTIO_NET_F_MQ, \
3239f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_CTRL_MAC_ADDR, \
3240faa9b39fSJason Baron 	VIRTIO_NET_F_MTU, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, \
32419805069dSSridhar Samudrala 	VIRTIO_NET_F_SPEED_DUPLEX, VIRTIO_NET_F_STANDBY
3242f3358507SMichael S. Tsirkin 
3243c45a6816SRusty Russell static unsigned int features[] = {
3244f3358507SMichael S. Tsirkin 	VIRTNET_FEATURES,
3245f3358507SMichael S. Tsirkin };
3246f3358507SMichael S. Tsirkin 
3247f3358507SMichael S. Tsirkin static unsigned int features_legacy[] = {
3248f3358507SMichael S. Tsirkin 	VIRTNET_FEATURES,
3249f3358507SMichael S. Tsirkin 	VIRTIO_NET_F_GSO,
3250e7428e95SMichael S. Tsirkin 	VIRTIO_F_ANY_LAYOUT,
3251c45a6816SRusty Russell };
3252c45a6816SRusty Russell 
325322402529SUwe Kleine-König static struct virtio_driver virtio_net_driver = {
3254c45a6816SRusty Russell 	.feature_table = features,
3255c45a6816SRusty Russell 	.feature_table_size = ARRAY_SIZE(features),
3256f3358507SMichael S. Tsirkin 	.feature_table_legacy = features_legacy,
3257f3358507SMichael S. Tsirkin 	.feature_table_size_legacy = ARRAY_SIZE(features_legacy),
3258296f96fcSRusty Russell 	.driver.name =	KBUILD_MODNAME,
3259296f96fcSRusty Russell 	.driver.owner =	THIS_MODULE,
3260296f96fcSRusty Russell 	.id_table =	id_table,
3261fe36cbe0SMichael S. Tsirkin 	.validate =	virtnet_validate,
3262296f96fcSRusty Russell 	.probe =	virtnet_probe,
32638cc085d6SBill Pemberton 	.remove =	virtnet_remove,
32649f4d26d0SMark McLoughlin 	.config_changed = virtnet_config_changed,
326589107000SAaron Lu #ifdef CONFIG_PM_SLEEP
32660741bcb5SAmit Shah 	.freeze =	virtnet_freeze,
32670741bcb5SAmit Shah 	.restore =	virtnet_restore,
32680741bcb5SAmit Shah #endif
3269296f96fcSRusty Russell };
3270296f96fcSRusty Russell 
32718017c279SSebastian Andrzej Siewior static __init int virtio_net_driver_init(void)
32728017c279SSebastian Andrzej Siewior {
32738017c279SSebastian Andrzej Siewior 	int ret;
32748017c279SSebastian Andrzej Siewior 
327573c1b41eSThomas Gleixner 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "virtio/net:online",
32768017c279SSebastian Andrzej Siewior 				      virtnet_cpu_online,
32778017c279SSebastian Andrzej Siewior 				      virtnet_cpu_down_prep);
32788017c279SSebastian Andrzej Siewior 	if (ret < 0)
32798017c279SSebastian Andrzej Siewior 		goto out;
32808017c279SSebastian Andrzej Siewior 	virtionet_online = ret;
328173c1b41eSThomas Gleixner 	ret = cpuhp_setup_state_multi(CPUHP_VIRT_NET_DEAD, "virtio/net:dead",
32828017c279SSebastian Andrzej Siewior 				      NULL, virtnet_cpu_dead);
32838017c279SSebastian Andrzej Siewior 	if (ret)
32848017c279SSebastian Andrzej Siewior 		goto err_dead;
32858017c279SSebastian Andrzej Siewior 
32868017c279SSebastian Andrzej Siewior         ret = register_virtio_driver(&virtio_net_driver);
32878017c279SSebastian Andrzej Siewior 	if (ret)
32888017c279SSebastian Andrzej Siewior 		goto err_virtio;
32898017c279SSebastian Andrzej Siewior 	return 0;
32908017c279SSebastian Andrzej Siewior err_virtio:
32918017c279SSebastian Andrzej Siewior 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
32928017c279SSebastian Andrzej Siewior err_dead:
32938017c279SSebastian Andrzej Siewior 	cpuhp_remove_multi_state(virtionet_online);
32948017c279SSebastian Andrzej Siewior out:
32958017c279SSebastian Andrzej Siewior 	return ret;
32968017c279SSebastian Andrzej Siewior }
32978017c279SSebastian Andrzej Siewior module_init(virtio_net_driver_init);
32988017c279SSebastian Andrzej Siewior 
32998017c279SSebastian Andrzej Siewior static __exit void virtio_net_driver_exit(void)
33008017c279SSebastian Andrzej Siewior {
3301cfa0ebc9SAndrew Jones 	unregister_virtio_driver(&virtio_net_driver);
33028017c279SSebastian Andrzej Siewior 	cpuhp_remove_multi_state(CPUHP_VIRT_NET_DEAD);
33038017c279SSebastian Andrzej Siewior 	cpuhp_remove_multi_state(virtionet_online);
33048017c279SSebastian Andrzej Siewior }
33058017c279SSebastian Andrzej Siewior module_exit(virtio_net_driver_exit);
3306296f96fcSRusty Russell 
3307296f96fcSRusty Russell MODULE_DEVICE_TABLE(virtio, id_table);
3308296f96fcSRusty Russell MODULE_DESCRIPTION("Virtio network driver");
3309296f96fcSRusty Russell MODULE_LICENSE("GPL");
3310