xref: /linux/drivers/net/xen-netfront.c (revision 2a31b5378c6db9c4a8d399e5d10d32cd4b732bef)
1 /*
2  * Virtual network driver for conversing with remote driver backends.
3  *
4  * Copyright (c) 2002-2005, K A Fraser
5  * Copyright (c) 2005, XenSource Ltd
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License version 2
9  * as published by the Free Software Foundation; or, when distributed
10  * separately from the Linux kernel or incorporated into other
11  * software packages, subject to the following license:
12  *
13  * Permission is hereby granted, free of charge, to any person obtaining a copy
14  * of this source file (the "Software"), to deal in the Software without
15  * restriction, including without limitation the rights to use, copy, modify,
16  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
17  * and to permit persons to whom the Software is furnished to do so, subject to
18  * the following conditions:
19  *
20  * The above copyright notice and this permission notice shall be included in
21  * all copies or substantial portions of the Software.
22  *
23  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
29  * IN THE SOFTWARE.
30  */
31 
32 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
33 
34 #include <linux/module.h>
35 #include <linux/kernel.h>
36 #include <linux/netdevice.h>
37 #include <linux/etherdevice.h>
38 #include <linux/skbuff.h>
39 #include <linux/ethtool.h>
40 #include <linux/if_ether.h>
41 #include <net/tcp.h>
42 #include <linux/udp.h>
43 #include <linux/moduleparam.h>
44 #include <linux/mm.h>
45 #include <linux/slab.h>
46 #include <net/ip.h>
47 #include <linux/bpf.h>
48 #include <net/page_pool/types.h>
49 #include <linux/bpf_trace.h>
50 
51 #include <xen/xen.h>
52 #include <xen/xenbus.h>
53 #include <xen/events.h>
54 #include <xen/page.h>
55 #include <xen/platform_pci.h>
56 #include <xen/grant_table.h>
57 
58 #include <xen/interface/io/netif.h>
59 #include <xen/interface/memory.h>
60 #include <xen/interface/grant_table.h>
61 
62 /* Module parameters */
63 #define MAX_QUEUES_DEFAULT 8
64 static unsigned int xennet_max_queues;
65 module_param_named(max_queues, xennet_max_queues, uint, 0644);
66 MODULE_PARM_DESC(max_queues,
67 		 "Maximum number of queues per virtual interface");
68 
69 static bool __read_mostly xennet_trusted = true;
70 module_param_named(trusted, xennet_trusted, bool, 0644);
71 MODULE_PARM_DESC(trusted, "Is the backend trusted");
72 
73 #define XENNET_TIMEOUT  (5 * HZ)
74 
75 static const struct ethtool_ops xennet_ethtool_ops;
76 
77 struct netfront_cb {
78 	int pull_to;
79 };
80 
81 #define NETFRONT_SKB_CB(skb)	((struct netfront_cb *)((skb)->cb))
82 
83 #define RX_COPY_THRESHOLD 256
84 
85 #define NET_TX_RING_SIZE __CONST_RING_SIZE(xen_netif_tx, XEN_PAGE_SIZE)
86 #define NET_RX_RING_SIZE __CONST_RING_SIZE(xen_netif_rx, XEN_PAGE_SIZE)
87 
88 /* Minimum number of Rx slots (includes slot for GSO metadata). */
89 #define NET_RX_SLOTS_MIN (XEN_NETIF_NR_SLOTS_MIN + 1)
90 
91 /* Queue name is interface name with "-qNNN" appended */
92 #define QUEUE_NAME_SIZE (IFNAMSIZ + 6)
93 
94 /* IRQ name is queue name with "-tx" or "-rx" appended */
95 #define IRQ_NAME_SIZE (QUEUE_NAME_SIZE + 3)
96 
97 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
98 
99 struct netfront_stats {
100 	u64_stats_t		packets;
101 	u64_stats_t		bytes;
102 	struct u64_stats_sync	syncp;
103 };
104 
105 struct netfront_info;
106 
107 struct netfront_queue {
108 	unsigned int id; /* Queue ID, 0-based */
109 	char name[QUEUE_NAME_SIZE]; /* DEVNAME-qN */
110 	struct netfront_info *info;
111 
112 	struct bpf_prog __rcu *xdp_prog;
113 
114 	struct napi_struct napi;
115 
116 	/* Split event channels support, tx_* == rx_* when using
117 	 * single event channel.
118 	 */
119 	unsigned int tx_evtchn, rx_evtchn;
120 	unsigned int tx_irq, rx_irq;
121 	/* Only used when split event channels support is enabled */
122 	char tx_irq_name[IRQ_NAME_SIZE]; /* DEVNAME-qN-tx */
123 	char rx_irq_name[IRQ_NAME_SIZE]; /* DEVNAME-qN-rx */
124 
125 	spinlock_t   tx_lock;
126 	struct xen_netif_tx_front_ring tx;
127 	int tx_ring_ref;
128 
129 	/*
130 	 * {tx,rx}_skbs store outstanding skbuffs. Free tx_skb entries
131 	 * are linked from tx_skb_freelist through tx_link.
132 	 */
133 	struct sk_buff *tx_skbs[NET_TX_RING_SIZE];
134 	unsigned short tx_link[NET_TX_RING_SIZE];
135 #define TX_LINK_NONE 0xffff
136 #define TX_PENDING   0xfffe
137 	grant_ref_t gref_tx_head;
138 	grant_ref_t grant_tx_ref[NET_TX_RING_SIZE];
139 	struct page *grant_tx_page[NET_TX_RING_SIZE];
140 	unsigned tx_skb_freelist;
141 	unsigned int tx_pend_queue;
142 
143 	spinlock_t   rx_lock ____cacheline_aligned_in_smp;
144 	struct xen_netif_rx_front_ring rx;
145 	int rx_ring_ref;
146 
147 	struct timer_list rx_refill_timer;
148 
149 	struct sk_buff *rx_skbs[NET_RX_RING_SIZE];
150 	grant_ref_t gref_rx_head;
151 	grant_ref_t grant_rx_ref[NET_RX_RING_SIZE];
152 
153 	unsigned int rx_rsp_unconsumed;
154 	spinlock_t rx_cons_lock;
155 
156 	struct page_pool *page_pool;
157 	struct xdp_rxq_info xdp_rxq;
158 };
159 
160 struct netfront_info {
161 	struct list_head list;
162 	struct net_device *netdev;
163 
164 	struct xenbus_device *xbdev;
165 
166 	/* Multi-queue support */
167 	struct netfront_queue *queues;
168 
169 	/* Statistics */
170 	struct netfront_stats __percpu *rx_stats;
171 	struct netfront_stats __percpu *tx_stats;
172 
173 	/* XDP state */
174 	bool netback_has_xdp_headroom;
175 	bool netfront_xdp_enabled;
176 
177 	/* Is device behaving sane? */
178 	bool broken;
179 
180 	/* Should skbs be bounced into a zeroed buffer? */
181 	bool bounce;
182 
183 	atomic_t rx_gso_checksum_fixup;
184 };
185 
186 struct netfront_rx_info {
187 	struct xen_netif_rx_response rx;
188 	struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX - 1];
189 };
190 
191 /*
192  * Access macros for acquiring freeing slots in tx_skbs[].
193  */
194 
195 static void add_id_to_list(unsigned *head, unsigned short *list,
196 			   unsigned short id)
197 {
198 	list[id] = *head;
199 	*head = id;
200 }
201 
202 static unsigned short get_id_from_list(unsigned *head, unsigned short *list)
203 {
204 	unsigned int id = *head;
205 
206 	if (id != TX_LINK_NONE) {
207 		*head = list[id];
208 		list[id] = TX_LINK_NONE;
209 	}
210 	return id;
211 }
212 
213 static int xennet_rxidx(RING_IDX idx)
214 {
215 	return idx & (NET_RX_RING_SIZE - 1);
216 }
217 
218 static struct sk_buff *xennet_get_rx_skb(struct netfront_queue *queue,
219 					 RING_IDX ri)
220 {
221 	int i = xennet_rxidx(ri);
222 	struct sk_buff *skb = queue->rx_skbs[i];
223 	queue->rx_skbs[i] = NULL;
224 	return skb;
225 }
226 
227 static grant_ref_t xennet_get_rx_ref(struct netfront_queue *queue,
228 					    RING_IDX ri)
229 {
230 	int i = xennet_rxidx(ri);
231 	grant_ref_t ref = queue->grant_rx_ref[i];
232 	queue->grant_rx_ref[i] = INVALID_GRANT_REF;
233 	return ref;
234 }
235 
236 #ifdef CONFIG_SYSFS
237 static const struct attribute_group xennet_dev_group;
238 #endif
239 
240 static bool xennet_can_sg(struct net_device *dev)
241 {
242 	return dev->features & NETIF_F_SG;
243 }
244 
245 
246 static void rx_refill_timeout(struct timer_list *t)
247 {
248 	struct netfront_queue *queue = timer_container_of(queue, t,
249 							  rx_refill_timer);
250 	napi_schedule(&queue->napi);
251 }
252 
253 static int netfront_tx_slot_available(struct netfront_queue *queue)
254 {
255 	return (queue->tx.req_prod_pvt - queue->tx.rsp_cons) <
256 		(NET_TX_RING_SIZE - XEN_NETIF_NR_SLOTS_MIN - 1);
257 }
258 
259 static void xennet_maybe_wake_tx(struct netfront_queue *queue)
260 {
261 	struct net_device *dev = queue->info->netdev;
262 	struct netdev_queue *dev_queue = netdev_get_tx_queue(dev, queue->id);
263 
264 	if (unlikely(netif_tx_queue_stopped(dev_queue)) &&
265 	    netfront_tx_slot_available(queue) &&
266 	    likely(netif_running(dev)))
267 		netif_tx_wake_queue(netdev_get_tx_queue(dev, queue->id));
268 }
269 
270 
271 static struct sk_buff *xennet_alloc_one_rx_buffer(struct netfront_queue *queue)
272 {
273 	struct sk_buff *skb;
274 	struct page *page;
275 
276 	skb = __netdev_alloc_skb(queue->info->netdev,
277 				 RX_COPY_THRESHOLD + NET_IP_ALIGN,
278 				 GFP_ATOMIC | __GFP_NOWARN);
279 	if (unlikely(!skb))
280 		return NULL;
281 
282 	page = page_pool_alloc_pages(queue->page_pool,
283 				     GFP_ATOMIC | __GFP_NOWARN | __GFP_ZERO);
284 	if (unlikely(!page)) {
285 		kfree_skb(skb);
286 		return NULL;
287 	}
288 	skb_add_rx_frag(skb, 0, page, 0, 0, PAGE_SIZE);
289 	skb_mark_for_recycle(skb);
290 
291 	/* Align ip header to a 16 bytes boundary */
292 	skb_reserve(skb, NET_IP_ALIGN);
293 	skb->dev = queue->info->netdev;
294 
295 	return skb;
296 }
297 
298 
299 static void xennet_alloc_rx_buffers(struct netfront_queue *queue)
300 {
301 	RING_IDX req_prod = queue->rx.req_prod_pvt;
302 	int notify;
303 	int err = 0;
304 
305 	if (unlikely(!netif_carrier_ok(queue->info->netdev)))
306 		return;
307 
308 	for (req_prod = queue->rx.req_prod_pvt;
309 	     req_prod - queue->rx.rsp_cons < NET_RX_RING_SIZE;
310 	     req_prod++) {
311 		struct sk_buff *skb;
312 		unsigned short id;
313 		grant_ref_t ref;
314 		struct page *page;
315 		struct xen_netif_rx_request *req;
316 
317 		skb = xennet_alloc_one_rx_buffer(queue);
318 		if (!skb) {
319 			err = -ENOMEM;
320 			break;
321 		}
322 
323 		id = xennet_rxidx(req_prod);
324 
325 		BUG_ON(queue->rx_skbs[id]);
326 		queue->rx_skbs[id] = skb;
327 
328 		ref = gnttab_claim_grant_reference(&queue->gref_rx_head);
329 		WARN_ON_ONCE(IS_ERR_VALUE((unsigned long)(int)ref));
330 		queue->grant_rx_ref[id] = ref;
331 
332 		page = skb_frag_page(&skb_shinfo(skb)->frags[0]);
333 
334 		req = RING_GET_REQUEST(&queue->rx, req_prod);
335 		gnttab_page_grant_foreign_access_ref_one(ref,
336 							 queue->info->xbdev->otherend_id,
337 							 page,
338 							 0);
339 		req->id = id;
340 		req->gref = ref;
341 	}
342 
343 	queue->rx.req_prod_pvt = req_prod;
344 
345 	/* Try again later if there are not enough requests or skb allocation
346 	 * failed.
347 	 * Enough requests is quantified as the sum of newly created slots and
348 	 * the unconsumed slots at the backend.
349 	 */
350 	if (req_prod - queue->rx.rsp_cons < NET_RX_SLOTS_MIN ||
351 	    unlikely(err)) {
352 		mod_timer(&queue->rx_refill_timer, jiffies + (HZ/10));
353 		return;
354 	}
355 
356 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&queue->rx, notify);
357 	if (notify)
358 		notify_remote_via_irq(queue->rx_irq);
359 }
360 
361 static int xennet_open(struct net_device *dev)
362 {
363 	struct netfront_info *np = netdev_priv(dev);
364 	unsigned int num_queues = dev->real_num_tx_queues;
365 	unsigned int i = 0;
366 	struct netfront_queue *queue = NULL;
367 
368 	if (!np->queues || np->broken)
369 		return -ENODEV;
370 
371 	for (i = 0; i < num_queues; ++i) {
372 		queue = &np->queues[i];
373 		napi_enable(&queue->napi);
374 
375 		spin_lock_bh(&queue->rx_lock);
376 		if (netif_carrier_ok(dev)) {
377 			xennet_alloc_rx_buffers(queue);
378 			queue->rx.sring->rsp_event = queue->rx.rsp_cons + 1;
379 			if (RING_HAS_UNCONSUMED_RESPONSES(&queue->rx))
380 				napi_schedule(&queue->napi);
381 		}
382 		spin_unlock_bh(&queue->rx_lock);
383 	}
384 
385 	netif_tx_start_all_queues(dev);
386 
387 	return 0;
388 }
389 
390 static bool xennet_tx_buf_gc(struct netfront_queue *queue)
391 {
392 	RING_IDX cons, prod;
393 	unsigned short id;
394 	struct sk_buff *skb;
395 	bool more_to_do;
396 	bool work_done = false;
397 	const struct device *dev = &queue->info->netdev->dev;
398 
399 	BUG_ON(!netif_carrier_ok(queue->info->netdev));
400 
401 	do {
402 		prod = queue->tx.sring->rsp_prod;
403 		if (RING_RESPONSE_PROD_OVERFLOW(&queue->tx, prod)) {
404 			dev_alert(dev, "Illegal number of responses %u\n",
405 				  prod - queue->tx.rsp_cons);
406 			goto err;
407 		}
408 		rmb(); /* Ensure we see responses up to 'rp'. */
409 
410 		for (cons = queue->tx.rsp_cons; cons != prod; cons++) {
411 			struct xen_netif_tx_response txrsp;
412 
413 			work_done = true;
414 
415 			RING_COPY_RESPONSE(&queue->tx, cons, &txrsp);
416 			if (txrsp.status == XEN_NETIF_RSP_NULL)
417 				continue;
418 
419 			id = txrsp.id;
420 			if (id >= RING_SIZE(&queue->tx)) {
421 				dev_alert(dev,
422 					  "Response has incorrect id (%u)\n",
423 					  id);
424 				goto err;
425 			}
426 			if (queue->tx_link[id] != TX_PENDING) {
427 				dev_alert(dev,
428 					  "Response for inactive request\n");
429 				goto err;
430 			}
431 
432 			queue->tx_link[id] = TX_LINK_NONE;
433 			skb = queue->tx_skbs[id];
434 			queue->tx_skbs[id] = NULL;
435 			if (unlikely(!gnttab_end_foreign_access_ref(
436 				queue->grant_tx_ref[id]))) {
437 				dev_alert(dev,
438 					  "Grant still in use by backend domain\n");
439 				goto err;
440 			}
441 			gnttab_release_grant_reference(
442 				&queue->gref_tx_head, queue->grant_tx_ref[id]);
443 			queue->grant_tx_ref[id] = INVALID_GRANT_REF;
444 			queue->grant_tx_page[id] = NULL;
445 			add_id_to_list(&queue->tx_skb_freelist, queue->tx_link, id);
446 			dev_kfree_skb_irq(skb);
447 		}
448 
449 		queue->tx.rsp_cons = prod;
450 
451 		RING_FINAL_CHECK_FOR_RESPONSES(&queue->tx, more_to_do);
452 	} while (more_to_do);
453 
454 	xennet_maybe_wake_tx(queue);
455 
456 	return work_done;
457 
458  err:
459 	queue->info->broken = true;
460 	dev_alert(dev, "Disabled for further use\n");
461 
462 	return work_done;
463 }
464 
465 struct xennet_gnttab_make_txreq {
466 	struct netfront_queue *queue;
467 	struct sk_buff *skb;
468 	struct page *page;
469 	struct xen_netif_tx_request *tx;      /* Last request on ring page */
470 	struct xen_netif_tx_request tx_local; /* Last request local copy*/
471 	unsigned int size;
472 };
473 
474 static void xennet_tx_setup_grant(unsigned long gfn, unsigned int offset,
475 				  unsigned int len, void *data)
476 {
477 	struct xennet_gnttab_make_txreq *info = data;
478 	unsigned int id;
479 	struct xen_netif_tx_request *tx;
480 	grant_ref_t ref;
481 	/* convenient aliases */
482 	struct page *page = info->page;
483 	struct netfront_queue *queue = info->queue;
484 	struct sk_buff *skb = info->skb;
485 
486 	id = get_id_from_list(&queue->tx_skb_freelist, queue->tx_link);
487 	tx = RING_GET_REQUEST(&queue->tx, queue->tx.req_prod_pvt++);
488 	ref = gnttab_claim_grant_reference(&queue->gref_tx_head);
489 	WARN_ON_ONCE(IS_ERR_VALUE((unsigned long)(int)ref));
490 
491 	gnttab_grant_foreign_access_ref(ref, queue->info->xbdev->otherend_id,
492 					gfn, GNTMAP_readonly);
493 
494 	queue->tx_skbs[id] = skb;
495 	queue->grant_tx_page[id] = page;
496 	queue->grant_tx_ref[id] = ref;
497 
498 	info->tx_local.id = id;
499 	info->tx_local.gref = ref;
500 	info->tx_local.offset = offset;
501 	info->tx_local.size = len;
502 	info->tx_local.flags = 0;
503 
504 	*tx = info->tx_local;
505 
506 	/*
507 	 * Put the request in the pending queue, it will be set to be pending
508 	 * when the producer index is about to be raised.
509 	 */
510 	add_id_to_list(&queue->tx_pend_queue, queue->tx_link, id);
511 
512 	info->tx = tx;
513 	info->size += info->tx_local.size;
514 }
515 
516 static struct xen_netif_tx_request *xennet_make_first_txreq(
517 	struct xennet_gnttab_make_txreq *info,
518 	unsigned int offset, unsigned int len)
519 {
520 	info->size = 0;
521 
522 	gnttab_for_one_grant(info->page, offset, len, xennet_tx_setup_grant, info);
523 
524 	return info->tx;
525 }
526 
527 static void xennet_make_one_txreq(unsigned long gfn, unsigned int offset,
528 				  unsigned int len, void *data)
529 {
530 	struct xennet_gnttab_make_txreq *info = data;
531 
532 	info->tx->flags |= XEN_NETTXF_more_data;
533 	skb_get(info->skb);
534 	xennet_tx_setup_grant(gfn, offset, len, data);
535 }
536 
537 static void xennet_make_txreqs(
538 	struct xennet_gnttab_make_txreq *info,
539 	struct page *page,
540 	unsigned int offset, unsigned int len)
541 {
542 	/* Skip unused frames from start of page */
543 	page += offset >> PAGE_SHIFT;
544 	offset &= ~PAGE_MASK;
545 
546 	while (len) {
547 		info->page = page;
548 		info->size = 0;
549 
550 		gnttab_foreach_grant_in_range(page, offset, len,
551 					      xennet_make_one_txreq,
552 					      info);
553 
554 		page++;
555 		offset = 0;
556 		len -= info->size;
557 	}
558 }
559 
560 /*
561  * Count how many ring slots are required to send this skb. Each frag
562  * might be a compound page.
563  */
564 static int xennet_count_skb_slots(struct sk_buff *skb)
565 {
566 	int i, frags = skb_shinfo(skb)->nr_frags;
567 	int slots;
568 
569 	slots = gnttab_count_grant(offset_in_page(skb->data),
570 				   skb_headlen(skb));
571 
572 	for (i = 0; i < frags; i++) {
573 		skb_frag_t *frag = skb_shinfo(skb)->frags + i;
574 		unsigned long size = skb_frag_size(frag);
575 		unsigned long offset = skb_frag_off(frag);
576 
577 		/* Skip unused frames from start of page */
578 		offset &= ~PAGE_MASK;
579 
580 		slots += gnttab_count_grant(offset, size);
581 	}
582 
583 	return slots;
584 }
585 
586 static u16 xennet_select_queue(struct net_device *dev, struct sk_buff *skb,
587 			       struct net_device *sb_dev)
588 {
589 	unsigned int num_queues = dev->real_num_tx_queues;
590 	u32 hash;
591 	u16 queue_idx;
592 
593 	/* First, check if there is only one queue */
594 	if (num_queues == 1) {
595 		queue_idx = 0;
596 	} else {
597 		hash = skb_get_hash(skb);
598 		queue_idx = hash % num_queues;
599 	}
600 
601 	return queue_idx;
602 }
603 
604 static void xennet_mark_tx_pending(struct netfront_queue *queue)
605 {
606 	unsigned int i;
607 
608 	while ((i = get_id_from_list(&queue->tx_pend_queue, queue->tx_link)) !=
609 	       TX_LINK_NONE)
610 		queue->tx_link[i] = TX_PENDING;
611 }
612 
613 static int xennet_xdp_xmit_one(struct net_device *dev,
614 			       struct netfront_queue *queue,
615 			       struct xdp_frame *xdpf)
616 {
617 	struct netfront_info *np = netdev_priv(dev);
618 	struct netfront_stats *tx_stats = this_cpu_ptr(np->tx_stats);
619 	struct xennet_gnttab_make_txreq info = {
620 		.queue = queue,
621 		.skb = NULL,
622 		.page = virt_to_page(xdpf->data),
623 	};
624 	int notify;
625 
626 	xennet_make_first_txreq(&info,
627 				offset_in_page(xdpf->data),
628 				xdpf->len);
629 
630 	xennet_mark_tx_pending(queue);
631 
632 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&queue->tx, notify);
633 	if (notify)
634 		notify_remote_via_irq(queue->tx_irq);
635 
636 	u64_stats_update_begin(&tx_stats->syncp);
637 	u64_stats_add(&tx_stats->bytes, xdpf->len);
638 	u64_stats_inc(&tx_stats->packets);
639 	u64_stats_update_end(&tx_stats->syncp);
640 
641 	return 0;
642 }
643 
644 static int xennet_xdp_xmit(struct net_device *dev, int n,
645 			   struct xdp_frame **frames, u32 flags)
646 {
647 	unsigned int num_queues = dev->real_num_tx_queues;
648 	struct netfront_info *np = netdev_priv(dev);
649 	struct netfront_queue *queue = NULL;
650 	unsigned long irq_flags;
651 	int nxmit = 0;
652 	int i;
653 
654 	if (unlikely(np->broken))
655 		return -ENODEV;
656 	if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
657 		return -EINVAL;
658 
659 	queue = &np->queues[smp_processor_id() % num_queues];
660 
661 	spin_lock_irqsave(&queue->tx_lock, irq_flags);
662 	for (i = 0; i < n; i++) {
663 		struct xdp_frame *xdpf = frames[i];
664 
665 		if (!xdpf)
666 			continue;
667 		if (xennet_xdp_xmit_one(dev, queue, xdpf))
668 			break;
669 		nxmit++;
670 	}
671 	spin_unlock_irqrestore(&queue->tx_lock, irq_flags);
672 
673 	return nxmit;
674 }
675 
676 static struct sk_buff *bounce_skb(const struct sk_buff *skb)
677 {
678 	unsigned int headerlen = skb_headroom(skb);
679 	/* Align size to allocate full pages and avoid contiguous data leaks */
680 	unsigned int size = ALIGN(skb_end_offset(skb) + skb->data_len,
681 				  XEN_PAGE_SIZE);
682 	struct sk_buff *n = alloc_skb(size, GFP_ATOMIC | __GFP_ZERO);
683 
684 	if (!n)
685 		return NULL;
686 
687 	if (!IS_ALIGNED((uintptr_t)n->head, XEN_PAGE_SIZE)) {
688 		WARN_ONCE(1, "misaligned skb allocated\n");
689 		kfree_skb(n);
690 		return NULL;
691 	}
692 
693 	/* Set the data pointer */
694 	skb_reserve(n, headerlen);
695 	/* Set the tail pointer and length */
696 	skb_put(n, skb->len);
697 
698 	BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
699 
700 	skb_copy_header(n, skb);
701 	return n;
702 }
703 
704 #define MAX_XEN_SKB_FRAGS (65536 / XEN_PAGE_SIZE + 1)
705 
706 static netdev_tx_t xennet_start_xmit(struct sk_buff *skb, struct net_device *dev)
707 {
708 	struct netfront_info *np = netdev_priv(dev);
709 	struct netfront_stats *tx_stats = this_cpu_ptr(np->tx_stats);
710 	struct xen_netif_tx_request *first_tx;
711 	unsigned int i;
712 	int notify;
713 	int slots;
714 	struct page *page;
715 	unsigned int offset;
716 	unsigned int len;
717 	unsigned long flags;
718 	struct netfront_queue *queue = NULL;
719 	struct xennet_gnttab_make_txreq info = { };
720 	unsigned int num_queues = dev->real_num_tx_queues;
721 	u16 queue_index;
722 	struct sk_buff *nskb;
723 
724 	/* Drop the packet if no queues are set up */
725 	if (num_queues < 1)
726 		goto drop;
727 	if (unlikely(np->broken))
728 		goto drop;
729 	/* Determine which queue to transmit this SKB on */
730 	queue_index = skb_get_queue_mapping(skb);
731 	queue = &np->queues[queue_index];
732 
733 	/* If skb->len is too big for wire format, drop skb and alert
734 	 * user about misconfiguration.
735 	 */
736 	if (unlikely(skb->len > XEN_NETIF_MAX_TX_SIZE)) {
737 		net_alert_ratelimited(
738 			"xennet: skb->len = %u, too big for wire format\n",
739 			skb->len);
740 		goto drop;
741 	}
742 
743 	slots = xennet_count_skb_slots(skb);
744 	if (unlikely(slots > MAX_XEN_SKB_FRAGS + 1)) {
745 		net_dbg_ratelimited("xennet: skb rides the rocket: %d slots, %d bytes\n",
746 				    slots, skb->len);
747 		if (skb_linearize(skb))
748 			goto drop;
749 	}
750 
751 	page = virt_to_page(skb->data);
752 	offset = offset_in_page(skb->data);
753 
754 	/* The first req should be at least ETH_HLEN size or the packet will be
755 	 * dropped by netback.
756 	 *
757 	 * If the backend is not trusted bounce all data to zeroed pages to
758 	 * avoid exposing contiguous data on the granted page not belonging to
759 	 * the skb.
760 	 */
761 	if (np->bounce || unlikely(PAGE_SIZE - offset < ETH_HLEN)) {
762 		nskb = bounce_skb(skb);
763 		if (!nskb)
764 			goto drop;
765 		dev_consume_skb_any(skb);
766 		skb = nskb;
767 		page = virt_to_page(skb->data);
768 		offset = offset_in_page(skb->data);
769 	}
770 
771 	len = skb_headlen(skb);
772 
773 	spin_lock_irqsave(&queue->tx_lock, flags);
774 
775 	if (unlikely(!netif_carrier_ok(dev) ||
776 		     (slots > 1 && !xennet_can_sg(dev)) ||
777 		     netif_needs_gso(skb, netif_skb_features(skb)))) {
778 		spin_unlock_irqrestore(&queue->tx_lock, flags);
779 		goto drop;
780 	}
781 
782 	/* First request for the linear area. */
783 	info.queue = queue;
784 	info.skb = skb;
785 	info.page = page;
786 	first_tx = xennet_make_first_txreq(&info, offset, len);
787 	offset += info.tx_local.size;
788 	if (offset == PAGE_SIZE) {
789 		page++;
790 		offset = 0;
791 	}
792 	len -= info.tx_local.size;
793 
794 	if (skb->ip_summed == CHECKSUM_PARTIAL)
795 		/* local packet? */
796 		first_tx->flags |= XEN_NETTXF_csum_blank |
797 				   XEN_NETTXF_data_validated;
798 	else if (skb->ip_summed == CHECKSUM_UNNECESSARY)
799 		/* remote but checksummed. */
800 		first_tx->flags |= XEN_NETTXF_data_validated;
801 
802 	/* Optional extra info after the first request. */
803 	if (skb_shinfo(skb)->gso_size) {
804 		struct xen_netif_extra_info *gso;
805 
806 		gso = (struct xen_netif_extra_info *)
807 			RING_GET_REQUEST(&queue->tx, queue->tx.req_prod_pvt++);
808 
809 		first_tx->flags |= XEN_NETTXF_extra_info;
810 
811 		gso->u.gso.size = skb_shinfo(skb)->gso_size;
812 		gso->u.gso.type = (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) ?
813 			XEN_NETIF_GSO_TYPE_TCPV6 :
814 			XEN_NETIF_GSO_TYPE_TCPV4;
815 		gso->u.gso.pad = 0;
816 		gso->u.gso.features = 0;
817 
818 		gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
819 		gso->flags = 0;
820 	}
821 
822 	/* Requests for the rest of the linear area. */
823 	xennet_make_txreqs(&info, page, offset, len);
824 
825 	/* Requests for all the frags. */
826 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
827 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
828 		xennet_make_txreqs(&info, skb_frag_page(frag),
829 					skb_frag_off(frag),
830 					skb_frag_size(frag));
831 	}
832 
833 	/* First request has the packet length. */
834 	first_tx->size = skb->len;
835 
836 	/* timestamp packet in software */
837 	skb_tx_timestamp(skb);
838 
839 	xennet_mark_tx_pending(queue);
840 
841 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&queue->tx, notify);
842 	if (notify)
843 		notify_remote_via_irq(queue->tx_irq);
844 
845 	u64_stats_update_begin(&tx_stats->syncp);
846 	u64_stats_add(&tx_stats->bytes, skb->len);
847 	u64_stats_inc(&tx_stats->packets);
848 	u64_stats_update_end(&tx_stats->syncp);
849 
850 	if (!netfront_tx_slot_available(queue))
851 		netif_tx_stop_queue(netdev_get_tx_queue(dev, queue->id));
852 
853 	spin_unlock_irqrestore(&queue->tx_lock, flags);
854 
855 	return NETDEV_TX_OK;
856 
857  drop:
858 	dev->stats.tx_dropped++;
859 	dev_kfree_skb_any(skb);
860 	return NETDEV_TX_OK;
861 }
862 
863 static int xennet_close(struct net_device *dev)
864 {
865 	struct netfront_info *np = netdev_priv(dev);
866 	unsigned int num_queues = np->queues ? dev->real_num_tx_queues : 0;
867 	unsigned int i;
868 	struct netfront_queue *queue;
869 	netif_tx_stop_all_queues(np->netdev);
870 	for (i = 0; i < num_queues; ++i) {
871 		queue = &np->queues[i];
872 		napi_disable(&queue->napi);
873 	}
874 	return 0;
875 }
876 
877 static void xennet_destroy_queues(struct netfront_info *info)
878 {
879 	unsigned int i;
880 
881 	if (!info->queues)
882 		return;
883 
884 	for (i = 0; i < info->netdev->real_num_tx_queues; i++) {
885 		struct netfront_queue *queue = &info->queues[i];
886 
887 		if (netif_running(info->netdev))
888 			napi_disable(&queue->napi);
889 		netif_napi_del(&queue->napi);
890 	}
891 
892 	kfree(info->queues);
893 	info->queues = NULL;
894 }
895 
896 static void xennet_uninit(struct net_device *dev)
897 {
898 	struct netfront_info *np = netdev_priv(dev);
899 	xennet_destroy_queues(np);
900 }
901 
902 static void xennet_set_rx_rsp_cons(struct netfront_queue *queue, RING_IDX val)
903 {
904 	unsigned long flags;
905 
906 	spin_lock_irqsave(&queue->rx_cons_lock, flags);
907 	queue->rx.rsp_cons = val;
908 	queue->rx_rsp_unconsumed = XEN_RING_NR_UNCONSUMED_RESPONSES(&queue->rx);
909 	spin_unlock_irqrestore(&queue->rx_cons_lock, flags);
910 }
911 
912 static void xennet_move_rx_slot(struct netfront_queue *queue, struct sk_buff *skb,
913 				grant_ref_t ref)
914 {
915 	int new = xennet_rxidx(queue->rx.req_prod_pvt);
916 
917 	BUG_ON(queue->rx_skbs[new]);
918 	queue->rx_skbs[new] = skb;
919 	queue->grant_rx_ref[new] = ref;
920 	RING_GET_REQUEST(&queue->rx, queue->rx.req_prod_pvt)->id = new;
921 	RING_GET_REQUEST(&queue->rx, queue->rx.req_prod_pvt)->gref = ref;
922 	queue->rx.req_prod_pvt++;
923 }
924 
925 static int xennet_get_extras(struct netfront_queue *queue,
926 			     struct xen_netif_extra_info *extras,
927 			     RING_IDX rp)
928 
929 {
930 	struct xen_netif_extra_info extra;
931 	struct device *dev = &queue->info->netdev->dev;
932 	RING_IDX cons = queue->rx.rsp_cons;
933 	int err = 0;
934 
935 	do {
936 		struct sk_buff *skb;
937 		grant_ref_t ref;
938 
939 		if (unlikely(cons + 1 == rp)) {
940 			if (net_ratelimit())
941 				dev_warn(dev, "Missing extra info\n");
942 			err = -EBADR;
943 			break;
944 		}
945 
946 		RING_COPY_RESPONSE(&queue->rx, ++cons, &extra);
947 
948 		if (unlikely(!extra.type ||
949 			     extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
950 			if (net_ratelimit())
951 				dev_warn(dev, "Invalid extra type: %d\n",
952 					 extra.type);
953 			err = -EINVAL;
954 		} else {
955 			extras[extra.type - 1] = extra;
956 		}
957 
958 		skb = xennet_get_rx_skb(queue, cons);
959 		ref = xennet_get_rx_ref(queue, cons);
960 		xennet_move_rx_slot(queue, skb, ref);
961 	} while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE);
962 
963 	xennet_set_rx_rsp_cons(queue, cons);
964 	return err;
965 }
966 
967 static u32 xennet_run_xdp(struct netfront_queue *queue, struct page *pdata,
968 		   struct xen_netif_rx_response *rx, struct bpf_prog *prog,
969 		   struct xdp_buff *xdp, bool *need_xdp_flush)
970 {
971 	struct xdp_frame *xdpf;
972 	u32 len = rx->status;
973 	u32 act;
974 	int err;
975 
976 	xdp_init_buff(xdp, XEN_PAGE_SIZE - XDP_PACKET_HEADROOM,
977 		      &queue->xdp_rxq);
978 	xdp_prepare_buff(xdp, page_address(pdata), XDP_PACKET_HEADROOM,
979 			 len, false);
980 
981 	act = bpf_prog_run_xdp(prog, xdp);
982 	switch (act) {
983 	case XDP_TX:
984 		xdpf = xdp_convert_buff_to_frame(xdp);
985 		if (unlikely(!xdpf)) {
986 			trace_xdp_exception(queue->info->netdev, prog, act);
987 			break;
988 		}
989 		get_page(pdata);
990 		err = xennet_xdp_xmit(queue->info->netdev, 1, &xdpf, 0);
991 		if (unlikely(err <= 0)) {
992 			if (err < 0)
993 				trace_xdp_exception(queue->info->netdev, prog, act);
994 			xdp_return_frame_rx_napi(xdpf);
995 		}
996 		break;
997 	case XDP_REDIRECT:
998 		get_page(pdata);
999 		err = xdp_do_redirect(queue->info->netdev, xdp, prog);
1000 		*need_xdp_flush = true;
1001 		if (unlikely(err)) {
1002 			trace_xdp_exception(queue->info->netdev, prog, act);
1003 			xdp_return_buff(xdp);
1004 		}
1005 		break;
1006 	case XDP_PASS:
1007 	case XDP_DROP:
1008 		break;
1009 
1010 	case XDP_ABORTED:
1011 		trace_xdp_exception(queue->info->netdev, prog, act);
1012 		break;
1013 
1014 	default:
1015 		bpf_warn_invalid_xdp_action(queue->info->netdev, prog, act);
1016 	}
1017 
1018 	return act;
1019 }
1020 
1021 static int xennet_get_responses(struct netfront_queue *queue,
1022 				struct netfront_rx_info *rinfo, RING_IDX rp,
1023 				struct sk_buff_head *list,
1024 				bool *need_xdp_flush)
1025 {
1026 	struct xen_netif_rx_response *rx = &rinfo->rx, rx_local;
1027 	int max = XEN_NETIF_NR_SLOTS_MIN + (rx->status <= RX_COPY_THRESHOLD);
1028 	RING_IDX cons = queue->rx.rsp_cons;
1029 	struct sk_buff *skb = xennet_get_rx_skb(queue, cons);
1030 	struct xen_netif_extra_info *extras = rinfo->extras;
1031 	grant_ref_t ref = xennet_get_rx_ref(queue, cons);
1032 	struct device *dev = &queue->info->netdev->dev;
1033 	struct bpf_prog *xdp_prog;
1034 	struct xdp_buff xdp;
1035 	int slots = 1;
1036 	int err = 0;
1037 	u32 verdict;
1038 
1039 	if (rx->flags & XEN_NETRXF_extra_info) {
1040 		err = xennet_get_extras(queue, extras, rp);
1041 		if (!err) {
1042 			if (extras[XEN_NETIF_EXTRA_TYPE_XDP - 1].type) {
1043 				struct xen_netif_extra_info *xdp;
1044 
1045 				xdp = &extras[XEN_NETIF_EXTRA_TYPE_XDP - 1];
1046 				rx->offset = xdp->u.xdp.headroom;
1047 			}
1048 		}
1049 		cons = queue->rx.rsp_cons;
1050 	}
1051 
1052 	for (;;) {
1053 		/*
1054 		 * This definitely indicates a bug, either in this driver or in
1055 		 * the backend driver. In future this should flag the bad
1056 		 * situation to the system controller to reboot the backend.
1057 		 */
1058 		if (ref == INVALID_GRANT_REF) {
1059 			if (net_ratelimit())
1060 				dev_warn(dev, "Bad rx response id %d.\n",
1061 					 rx->id);
1062 			err = -EINVAL;
1063 			goto next;
1064 		}
1065 
1066 		if (unlikely(rx->status < 0 ||
1067 			     rx->offset + rx->status > XEN_PAGE_SIZE)) {
1068 			if (net_ratelimit())
1069 				dev_warn(dev, "rx->offset: %u, size: %d\n",
1070 					 rx->offset, rx->status);
1071 			xennet_move_rx_slot(queue, skb, ref);
1072 			err = -EINVAL;
1073 			goto next;
1074 		}
1075 
1076 		if (!gnttab_end_foreign_access_ref(ref)) {
1077 			dev_alert(dev,
1078 				  "Grant still in use by backend domain\n");
1079 			queue->info->broken = true;
1080 			dev_alert(dev, "Disabled for further use\n");
1081 			return -EINVAL;
1082 		}
1083 
1084 		gnttab_release_grant_reference(&queue->gref_rx_head, ref);
1085 
1086 		rcu_read_lock();
1087 		xdp_prog = rcu_dereference(queue->xdp_prog);
1088 		if (xdp_prog) {
1089 			if (!(rx->flags & XEN_NETRXF_more_data)) {
1090 				/* currently only a single page contains data */
1091 				verdict = xennet_run_xdp(queue,
1092 							 skb_frag_page(&skb_shinfo(skb)->frags[0]),
1093 							 rx, xdp_prog, &xdp, need_xdp_flush);
1094 				if (verdict != XDP_PASS)
1095 					err = -EINVAL;
1096 			} else {
1097 				/* drop the frame */
1098 				err = -EINVAL;
1099 			}
1100 		}
1101 		rcu_read_unlock();
1102 
1103 		__skb_queue_tail(list, skb);
1104 
1105 next:
1106 		if (!(rx->flags & XEN_NETRXF_more_data))
1107 			break;
1108 
1109 		if (cons + slots == rp) {
1110 			if (net_ratelimit())
1111 				dev_warn(dev, "Need more slots\n");
1112 			err = -ENOENT;
1113 			break;
1114 		}
1115 
1116 		RING_COPY_RESPONSE(&queue->rx, cons + slots, &rx_local);
1117 		rx = &rx_local;
1118 		skb = xennet_get_rx_skb(queue, cons + slots);
1119 		ref = xennet_get_rx_ref(queue, cons + slots);
1120 		slots++;
1121 	}
1122 
1123 	if (unlikely(slots > max)) {
1124 		if (net_ratelimit())
1125 			dev_warn(dev, "Too many slots\n");
1126 		err = -E2BIG;
1127 	}
1128 
1129 	if (unlikely(err))
1130 		xennet_set_rx_rsp_cons(queue, cons + slots);
1131 
1132 	return err;
1133 }
1134 
1135 static int xennet_set_skb_gso(struct sk_buff *skb,
1136 			      struct xen_netif_extra_info *gso)
1137 {
1138 	if (!gso->u.gso.size) {
1139 		if (net_ratelimit())
1140 			pr_warn("GSO size must not be zero\n");
1141 		return -EINVAL;
1142 	}
1143 
1144 	if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4 &&
1145 	    gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV6) {
1146 		if (net_ratelimit())
1147 			pr_warn("Bad GSO type %d\n", gso->u.gso.type);
1148 		return -EINVAL;
1149 	}
1150 
1151 	skb_shinfo(skb)->gso_size = gso->u.gso.size;
1152 	skb_shinfo(skb)->gso_type =
1153 		(gso->u.gso.type == XEN_NETIF_GSO_TYPE_TCPV4) ?
1154 		SKB_GSO_TCPV4 :
1155 		SKB_GSO_TCPV6;
1156 
1157 	/* Header must be checked, and gso_segs computed. */
1158 	skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1159 	skb_shinfo(skb)->gso_segs = 0;
1160 
1161 	return 0;
1162 }
1163 
1164 static int xennet_fill_frags(struct netfront_queue *queue,
1165 			     struct sk_buff *skb,
1166 			     struct sk_buff_head *list)
1167 {
1168 	RING_IDX cons = queue->rx.rsp_cons;
1169 	struct sk_buff *nskb;
1170 
1171 	while ((nskb = __skb_dequeue(list))) {
1172 		struct xen_netif_rx_response rx;
1173 		skb_frag_t *nfrag = &skb_shinfo(nskb)->frags[0];
1174 
1175 		RING_COPY_RESPONSE(&queue->rx, ++cons, &rx);
1176 
1177 		if (skb_shinfo(skb)->nr_frags == MAX_SKB_FRAGS) {
1178 			unsigned int pull_to = NETFRONT_SKB_CB(skb)->pull_to;
1179 
1180 			BUG_ON(pull_to < skb_headlen(skb));
1181 			__pskb_pull_tail(skb, pull_to - skb_headlen(skb));
1182 		}
1183 		if (unlikely(skb_shinfo(skb)->nr_frags >= MAX_SKB_FRAGS)) {
1184 			xennet_set_rx_rsp_cons(queue,
1185 					       ++cons + skb_queue_len(list));
1186 			kfree_skb(nskb);
1187 			return -ENOENT;
1188 		}
1189 
1190 		skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags,
1191 				skb_frag_page(nfrag),
1192 				rx.offset, rx.status, PAGE_SIZE);
1193 
1194 		skb_shinfo(nskb)->nr_frags = 0;
1195 		kfree_skb(nskb);
1196 	}
1197 
1198 	xennet_set_rx_rsp_cons(queue, cons);
1199 
1200 	return 0;
1201 }
1202 
1203 static int checksum_setup(struct net_device *dev, struct sk_buff *skb)
1204 {
1205 	bool recalculate_partial_csum = false;
1206 
1207 	/*
1208 	 * A GSO SKB must be CHECKSUM_PARTIAL. However some buggy
1209 	 * peers can fail to set NETRXF_csum_blank when sending a GSO
1210 	 * frame. In this case force the SKB to CHECKSUM_PARTIAL and
1211 	 * recalculate the partial checksum.
1212 	 */
1213 	if (skb->ip_summed != CHECKSUM_PARTIAL && skb_is_gso(skb)) {
1214 		struct netfront_info *np = netdev_priv(dev);
1215 		atomic_inc(&np->rx_gso_checksum_fixup);
1216 		skb->ip_summed = CHECKSUM_PARTIAL;
1217 		recalculate_partial_csum = true;
1218 	}
1219 
1220 	/* A non-CHECKSUM_PARTIAL SKB does not require setup. */
1221 	if (skb->ip_summed != CHECKSUM_PARTIAL)
1222 		return 0;
1223 
1224 	return skb_checksum_setup(skb, recalculate_partial_csum);
1225 }
1226 
1227 static int handle_incoming_queue(struct netfront_queue *queue,
1228 				 struct sk_buff_head *rxq)
1229 {
1230 	struct netfront_stats *rx_stats = this_cpu_ptr(queue->info->rx_stats);
1231 	int packets_dropped = 0;
1232 	struct sk_buff *skb;
1233 
1234 	while ((skb = __skb_dequeue(rxq)) != NULL) {
1235 		int pull_to = NETFRONT_SKB_CB(skb)->pull_to;
1236 
1237 		/* pull_to comes from the first slot's length, which the
1238 		 * backend controls.  Make sure the head holds at least an
1239 		 * Ethernet header for eth_type_trans().
1240 		 */
1241 		if (!pskb_may_pull(skb, max(pull_to, ETH_HLEN))) {
1242 			kfree_skb(skb);
1243 			packets_dropped++;
1244 			queue->info->netdev->stats.rx_errors++;
1245 			continue;
1246 		}
1247 
1248 		/* Ethernet work: Delayed to here as it peeks the header. */
1249 		skb->protocol = eth_type_trans(skb, queue->info->netdev);
1250 		skb_reset_network_header(skb);
1251 
1252 		if (checksum_setup(queue->info->netdev, skb)) {
1253 			kfree_skb(skb);
1254 			packets_dropped++;
1255 			queue->info->netdev->stats.rx_errors++;
1256 			continue;
1257 		}
1258 
1259 		u64_stats_update_begin(&rx_stats->syncp);
1260 		u64_stats_inc(&rx_stats->packets);
1261 		u64_stats_add(&rx_stats->bytes, skb->len);
1262 		u64_stats_update_end(&rx_stats->syncp);
1263 
1264 		/* Pass it up. */
1265 		napi_gro_receive(&queue->napi, skb);
1266 	}
1267 
1268 	return packets_dropped;
1269 }
1270 
1271 static int xennet_poll(struct napi_struct *napi, int budget)
1272 {
1273 	struct netfront_queue *queue = container_of(napi, struct netfront_queue, napi);
1274 	struct net_device *dev = queue->info->netdev;
1275 	struct sk_buff *skb;
1276 	struct netfront_rx_info rinfo;
1277 	struct xen_netif_rx_response *rx = &rinfo.rx;
1278 	struct xen_netif_extra_info *extras = rinfo.extras;
1279 	RING_IDX i, rp;
1280 	int work_done;
1281 	struct sk_buff_head rxq;
1282 	struct sk_buff_head errq;
1283 	struct sk_buff_head tmpq;
1284 	int err;
1285 	bool need_xdp_flush = false;
1286 
1287 	spin_lock(&queue->rx_lock);
1288 
1289 	skb_queue_head_init(&rxq);
1290 	skb_queue_head_init(&errq);
1291 	skb_queue_head_init(&tmpq);
1292 
1293 	rp = queue->rx.sring->rsp_prod;
1294 	if (RING_RESPONSE_PROD_OVERFLOW(&queue->rx, rp)) {
1295 		dev_alert(&dev->dev, "Illegal number of responses %u\n",
1296 			  rp - queue->rx.rsp_cons);
1297 		queue->info->broken = true;
1298 		spin_unlock(&queue->rx_lock);
1299 		return 0;
1300 	}
1301 	rmb(); /* Ensure we see queued responses up to 'rp'. */
1302 
1303 	i = queue->rx.rsp_cons;
1304 	work_done = 0;
1305 	while ((i != rp) && (work_done < budget)) {
1306 		RING_COPY_RESPONSE(&queue->rx, i, rx);
1307 		memset(extras, 0, sizeof(rinfo.extras));
1308 
1309 		err = xennet_get_responses(queue, &rinfo, rp, &tmpq,
1310 					   &need_xdp_flush);
1311 
1312 		if (unlikely(err)) {
1313 			if (queue->info->broken) {
1314 				spin_unlock(&queue->rx_lock);
1315 				return 0;
1316 			}
1317 err:
1318 			while ((skb = __skb_dequeue(&tmpq)))
1319 				__skb_queue_tail(&errq, skb);
1320 			dev->stats.rx_errors++;
1321 			i = queue->rx.rsp_cons;
1322 			continue;
1323 		}
1324 
1325 		skb = __skb_dequeue(&tmpq);
1326 
1327 		if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
1328 			struct xen_netif_extra_info *gso;
1329 			gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
1330 
1331 			if (unlikely(xennet_set_skb_gso(skb, gso))) {
1332 				__skb_queue_head(&tmpq, skb);
1333 				xennet_set_rx_rsp_cons(queue,
1334 						       queue->rx.rsp_cons +
1335 						       skb_queue_len(&tmpq));
1336 				goto err;
1337 			}
1338 		}
1339 
1340 		NETFRONT_SKB_CB(skb)->pull_to = rx->status;
1341 		if (NETFRONT_SKB_CB(skb)->pull_to > RX_COPY_THRESHOLD)
1342 			NETFRONT_SKB_CB(skb)->pull_to = RX_COPY_THRESHOLD;
1343 
1344 		skb_frag_off_set(&skb_shinfo(skb)->frags[0], rx->offset);
1345 		skb_frag_size_set(&skb_shinfo(skb)->frags[0], rx->status);
1346 		skb->data_len = rx->status;
1347 		skb->len += rx->status;
1348 
1349 		if (unlikely(xennet_fill_frags(queue, skb, &tmpq))) {
1350 			__skb_queue_head(&tmpq, skb);
1351 			goto err;
1352 		}
1353 
1354 		if (rx->flags & XEN_NETRXF_csum_blank)
1355 			skb->ip_summed = CHECKSUM_PARTIAL;
1356 		else if (rx->flags & XEN_NETRXF_data_validated)
1357 			skb->ip_summed = CHECKSUM_UNNECESSARY;
1358 
1359 		__skb_queue_tail(&rxq, skb);
1360 
1361 		i = queue->rx.rsp_cons + 1;
1362 		xennet_set_rx_rsp_cons(queue, i);
1363 		work_done++;
1364 	}
1365 	if (need_xdp_flush)
1366 		xdp_do_flush();
1367 
1368 	__skb_queue_purge(&errq);
1369 
1370 	work_done -= handle_incoming_queue(queue, &rxq);
1371 
1372 	xennet_alloc_rx_buffers(queue);
1373 
1374 	if (work_done < budget) {
1375 		int more_to_do = 0;
1376 
1377 		napi_complete_done(napi, work_done);
1378 
1379 		RING_FINAL_CHECK_FOR_RESPONSES(&queue->rx, more_to_do);
1380 		if (more_to_do)
1381 			napi_schedule(napi);
1382 	}
1383 
1384 	spin_unlock(&queue->rx_lock);
1385 
1386 	return work_done;
1387 }
1388 
1389 static int xennet_change_mtu(struct net_device *dev, int mtu)
1390 {
1391 	int max = xennet_can_sg(dev) ? XEN_NETIF_MAX_TX_SIZE : ETH_DATA_LEN;
1392 
1393 	if (mtu > max)
1394 		return -EINVAL;
1395 	WRITE_ONCE(dev->mtu, mtu);
1396 	return 0;
1397 }
1398 
1399 static void xennet_get_stats64(struct net_device *dev,
1400 			       struct rtnl_link_stats64 *tot)
1401 {
1402 	struct netfront_info *np = netdev_priv(dev);
1403 	int cpu;
1404 
1405 	for_each_possible_cpu(cpu) {
1406 		struct netfront_stats *rx_stats = per_cpu_ptr(np->rx_stats, cpu);
1407 		struct netfront_stats *tx_stats = per_cpu_ptr(np->tx_stats, cpu);
1408 		u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
1409 		unsigned int start;
1410 
1411 		do {
1412 			start = u64_stats_fetch_begin(&tx_stats->syncp);
1413 			tx_packets = u64_stats_read(&tx_stats->packets);
1414 			tx_bytes = u64_stats_read(&tx_stats->bytes);
1415 		} while (u64_stats_fetch_retry(&tx_stats->syncp, start));
1416 
1417 		do {
1418 			start = u64_stats_fetch_begin(&rx_stats->syncp);
1419 			rx_packets = u64_stats_read(&rx_stats->packets);
1420 			rx_bytes = u64_stats_read(&rx_stats->bytes);
1421 		} while (u64_stats_fetch_retry(&rx_stats->syncp, start));
1422 
1423 		tot->rx_packets += rx_packets;
1424 		tot->tx_packets += tx_packets;
1425 		tot->rx_bytes   += rx_bytes;
1426 		tot->tx_bytes   += tx_bytes;
1427 	}
1428 
1429 	tot->rx_errors  = dev->stats.rx_errors;
1430 	tot->tx_dropped = dev->stats.tx_dropped;
1431 }
1432 
1433 static void xennet_release_tx_bufs(struct netfront_queue *queue)
1434 {
1435 	struct sk_buff *skb;
1436 	int i;
1437 
1438 	for (i = 0; i < NET_TX_RING_SIZE; i++) {
1439 		/* Skip over entries which are actually freelist references */
1440 		if (!queue->tx_skbs[i])
1441 			continue;
1442 
1443 		skb = queue->tx_skbs[i];
1444 		queue->tx_skbs[i] = NULL;
1445 		get_page(queue->grant_tx_page[i]);
1446 		gnttab_end_foreign_access(queue->grant_tx_ref[i],
1447 					  queue->grant_tx_page[i]);
1448 		queue->grant_tx_page[i] = NULL;
1449 		queue->grant_tx_ref[i] = INVALID_GRANT_REF;
1450 		add_id_to_list(&queue->tx_skb_freelist, queue->tx_link, i);
1451 		dev_kfree_skb_irq(skb);
1452 	}
1453 }
1454 
1455 static void xennet_release_rx_bufs(struct netfront_queue *queue)
1456 {
1457 	int id, ref;
1458 
1459 	spin_lock_bh(&queue->rx_lock);
1460 
1461 	for (id = 0; id < NET_RX_RING_SIZE; id++) {
1462 		struct sk_buff *skb;
1463 		struct page *page;
1464 
1465 		skb = queue->rx_skbs[id];
1466 		if (!skb)
1467 			continue;
1468 
1469 		ref = queue->grant_rx_ref[id];
1470 		if (ref == INVALID_GRANT_REF)
1471 			continue;
1472 
1473 		page = skb_frag_page(&skb_shinfo(skb)->frags[0]);
1474 
1475 		/* gnttab_end_foreign_access() needs a page ref until
1476 		 * foreign access is ended (which may be deferred).
1477 		 */
1478 		get_page(page);
1479 		gnttab_end_foreign_access(ref, page);
1480 		queue->grant_rx_ref[id] = INVALID_GRANT_REF;
1481 
1482 		kfree_skb(skb);
1483 	}
1484 
1485 	spin_unlock_bh(&queue->rx_lock);
1486 }
1487 
1488 static netdev_features_t xennet_fix_features(struct net_device *dev,
1489 	netdev_features_t features)
1490 {
1491 	struct netfront_info *np = netdev_priv(dev);
1492 
1493 	if (features & NETIF_F_SG &&
1494 	    !xenbus_read_unsigned(np->xbdev->otherend, "feature-sg", 0))
1495 		features &= ~NETIF_F_SG;
1496 
1497 	if (features & NETIF_F_IPV6_CSUM &&
1498 	    !xenbus_read_unsigned(np->xbdev->otherend,
1499 				  "feature-ipv6-csum-offload", 0))
1500 		features &= ~NETIF_F_IPV6_CSUM;
1501 
1502 	if (features & NETIF_F_TSO &&
1503 	    !xenbus_read_unsigned(np->xbdev->otherend, "feature-gso-tcpv4", 0))
1504 		features &= ~NETIF_F_TSO;
1505 
1506 	if (features & NETIF_F_TSO6 &&
1507 	    !xenbus_read_unsigned(np->xbdev->otherend, "feature-gso-tcpv6", 0))
1508 		features &= ~NETIF_F_TSO6;
1509 
1510 	return features;
1511 }
1512 
1513 static int xennet_set_features(struct net_device *dev,
1514 	netdev_features_t features)
1515 {
1516 	if (!(features & NETIF_F_SG) && dev->mtu > ETH_DATA_LEN) {
1517 		netdev_info(dev, "Reducing MTU because no SG offload");
1518 		dev->mtu = ETH_DATA_LEN;
1519 	}
1520 
1521 	return 0;
1522 }
1523 
1524 static bool xennet_handle_tx(struct netfront_queue *queue, unsigned int *eoi)
1525 {
1526 	unsigned long flags;
1527 
1528 	if (unlikely(queue->info->broken))
1529 		return false;
1530 
1531 	spin_lock_irqsave(&queue->tx_lock, flags);
1532 	if (xennet_tx_buf_gc(queue))
1533 		*eoi = 0;
1534 	spin_unlock_irqrestore(&queue->tx_lock, flags);
1535 
1536 	return true;
1537 }
1538 
1539 static irqreturn_t xennet_tx_interrupt(int irq, void *dev_id)
1540 {
1541 	unsigned int eoiflag = XEN_EOI_FLAG_SPURIOUS;
1542 
1543 	if (likely(xennet_handle_tx(dev_id, &eoiflag)))
1544 		xen_irq_lateeoi(irq, eoiflag);
1545 
1546 	return IRQ_HANDLED;
1547 }
1548 
1549 static bool xennet_handle_rx(struct netfront_queue *queue, unsigned int *eoi)
1550 {
1551 	unsigned int work_queued;
1552 	unsigned long flags;
1553 
1554 	if (unlikely(queue->info->broken))
1555 		return false;
1556 
1557 	spin_lock_irqsave(&queue->rx_cons_lock, flags);
1558 	work_queued = XEN_RING_NR_UNCONSUMED_RESPONSES(&queue->rx);
1559 	if (work_queued > queue->rx_rsp_unconsumed) {
1560 		queue->rx_rsp_unconsumed = work_queued;
1561 		*eoi = 0;
1562 	} else if (unlikely(work_queued < queue->rx_rsp_unconsumed)) {
1563 		const struct device *dev = &queue->info->netdev->dev;
1564 
1565 		spin_unlock_irqrestore(&queue->rx_cons_lock, flags);
1566 		dev_alert(dev, "RX producer index going backwards\n");
1567 		dev_alert(dev, "Disabled for further use\n");
1568 		queue->info->broken = true;
1569 		return false;
1570 	}
1571 	spin_unlock_irqrestore(&queue->rx_cons_lock, flags);
1572 
1573 	if (likely(netif_carrier_ok(queue->info->netdev) && work_queued))
1574 		napi_schedule(&queue->napi);
1575 
1576 	return true;
1577 }
1578 
1579 static irqreturn_t xennet_rx_interrupt(int irq, void *dev_id)
1580 {
1581 	unsigned int eoiflag = XEN_EOI_FLAG_SPURIOUS;
1582 
1583 	if (likely(xennet_handle_rx(dev_id, &eoiflag)))
1584 		xen_irq_lateeoi(irq, eoiflag);
1585 
1586 	return IRQ_HANDLED;
1587 }
1588 
1589 static irqreturn_t xennet_interrupt(int irq, void *dev_id)
1590 {
1591 	unsigned int eoiflag = XEN_EOI_FLAG_SPURIOUS;
1592 
1593 	if (xennet_handle_tx(dev_id, &eoiflag) &&
1594 	    xennet_handle_rx(dev_id, &eoiflag))
1595 		xen_irq_lateeoi(irq, eoiflag);
1596 
1597 	return IRQ_HANDLED;
1598 }
1599 
1600 #ifdef CONFIG_NET_POLL_CONTROLLER
1601 static void xennet_poll_controller(struct net_device *dev)
1602 {
1603 	/* Poll each queue */
1604 	struct netfront_info *info = netdev_priv(dev);
1605 	unsigned int num_queues = dev->real_num_tx_queues;
1606 	unsigned int i;
1607 
1608 	if (info->broken)
1609 		return;
1610 
1611 	for (i = 0; i < num_queues; ++i)
1612 		xennet_interrupt(0, &info->queues[i]);
1613 }
1614 #endif
1615 
1616 #define NETBACK_XDP_HEADROOM_DISABLE	0
1617 #define NETBACK_XDP_HEADROOM_ENABLE	1
1618 
1619 static int talk_to_netback_xdp(struct netfront_info *np, int xdp)
1620 {
1621 	int err;
1622 	unsigned short headroom;
1623 
1624 	headroom = xdp ? XDP_PACKET_HEADROOM : 0;
1625 	err = xenbus_printf(XBT_NIL, np->xbdev->nodename,
1626 			    "xdp-headroom", "%hu",
1627 			    headroom);
1628 	if (err)
1629 		pr_warn("Error writing xdp-headroom\n");
1630 
1631 	return err;
1632 }
1633 
1634 static int xennet_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1635 			  struct netlink_ext_ack *extack)
1636 {
1637 	unsigned long max_mtu = XEN_PAGE_SIZE - XDP_PACKET_HEADROOM;
1638 	struct netfront_info *np = netdev_priv(dev);
1639 	struct bpf_prog *old_prog;
1640 	unsigned int i, err;
1641 
1642 	if (dev->mtu > max_mtu) {
1643 		netdev_warn(dev, "XDP requires MTU less than %lu\n", max_mtu);
1644 		return -EINVAL;
1645 	}
1646 
1647 	if (!np->netback_has_xdp_headroom)
1648 		return 0;
1649 
1650 	xenbus_switch_state(np->xbdev, XenbusStateReconfiguring);
1651 
1652 	err = talk_to_netback_xdp(np, prog ? NETBACK_XDP_HEADROOM_ENABLE :
1653 				  NETBACK_XDP_HEADROOM_DISABLE);
1654 	if (err)
1655 		return err;
1656 
1657 	/* avoid the race with XDP headroom adjustment */
1658 	wait_event(module_wq,
1659 		   xenbus_read_driver_state(np->xbdev, np->xbdev->otherend) ==
1660 		   XenbusStateReconfigured);
1661 	np->netfront_xdp_enabled = true;
1662 
1663 	old_prog = rtnl_dereference(np->queues[0].xdp_prog);
1664 
1665 	if (prog)
1666 		bpf_prog_add(prog, dev->real_num_tx_queues);
1667 
1668 	for (i = 0; i < dev->real_num_tx_queues; ++i)
1669 		rcu_assign_pointer(np->queues[i].xdp_prog, prog);
1670 
1671 	if (old_prog)
1672 		for (i = 0; i < dev->real_num_tx_queues; ++i)
1673 			bpf_prog_put(old_prog);
1674 
1675 	xenbus_switch_state(np->xbdev, XenbusStateConnected);
1676 
1677 	return 0;
1678 }
1679 
1680 static int xennet_xdp(struct net_device *dev, struct netdev_bpf *xdp)
1681 {
1682 	struct netfront_info *np = netdev_priv(dev);
1683 
1684 	if (np->broken)
1685 		return -ENODEV;
1686 
1687 	switch (xdp->command) {
1688 	case XDP_SETUP_PROG:
1689 		return xennet_xdp_set(dev, xdp->prog, xdp->extack);
1690 	default:
1691 		return -EINVAL;
1692 	}
1693 }
1694 
1695 static const struct net_device_ops xennet_netdev_ops = {
1696 	.ndo_uninit          = xennet_uninit,
1697 	.ndo_open            = xennet_open,
1698 	.ndo_stop            = xennet_close,
1699 	.ndo_start_xmit      = xennet_start_xmit,
1700 	.ndo_change_mtu	     = xennet_change_mtu,
1701 	.ndo_get_stats64     = xennet_get_stats64,
1702 	.ndo_set_mac_address = eth_mac_addr,
1703 	.ndo_validate_addr   = eth_validate_addr,
1704 	.ndo_fix_features    = xennet_fix_features,
1705 	.ndo_set_features    = xennet_set_features,
1706 	.ndo_select_queue    = xennet_select_queue,
1707 	.ndo_bpf            = xennet_xdp,
1708 	.ndo_xdp_xmit	    = xennet_xdp_xmit,
1709 #ifdef CONFIG_NET_POLL_CONTROLLER
1710 	.ndo_poll_controller = xennet_poll_controller,
1711 #endif
1712 };
1713 
1714 static void xennet_free_netdev(struct net_device *netdev)
1715 {
1716 	struct netfront_info *np = netdev_priv(netdev);
1717 
1718 	free_percpu(np->rx_stats);
1719 	free_percpu(np->tx_stats);
1720 	free_netdev(netdev);
1721 }
1722 
1723 static struct net_device *xennet_create_dev(struct xenbus_device *dev)
1724 {
1725 	int err;
1726 	struct net_device *netdev;
1727 	struct netfront_info *np;
1728 
1729 	netdev = alloc_etherdev_mq(sizeof(struct netfront_info), xennet_max_queues);
1730 	if (!netdev)
1731 		return ERR_PTR(-ENOMEM);
1732 
1733 	np                   = netdev_priv(netdev);
1734 	np->xbdev            = dev;
1735 
1736 	np->queues = NULL;
1737 
1738 	err = -ENOMEM;
1739 	np->rx_stats = netdev_alloc_pcpu_stats(struct netfront_stats);
1740 	if (np->rx_stats == NULL)
1741 		goto exit;
1742 	np->tx_stats = netdev_alloc_pcpu_stats(struct netfront_stats);
1743 	if (np->tx_stats == NULL)
1744 		goto exit;
1745 
1746 	netdev->netdev_ops	= &xennet_netdev_ops;
1747 
1748 	netdev->features        = NETIF_F_IP_CSUM | NETIF_F_RXCSUM |
1749 				  NETIF_F_GSO_ROBUST;
1750 	netdev->hw_features	= NETIF_F_SG |
1751 				  NETIF_F_IPV6_CSUM |
1752 				  NETIF_F_TSO | NETIF_F_TSO6;
1753 
1754 	/*
1755          * Assume that all hw features are available for now. This set
1756          * will be adjusted by the call to netdev_update_features() in
1757          * xennet_connect() which is the earliest point where we can
1758          * negotiate with the backend regarding supported features.
1759          */
1760 	netdev->features |= netdev->hw_features;
1761 	netdev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT |
1762 			       NETDEV_XDP_ACT_NDO_XMIT;
1763 
1764 	netdev->ethtool_ops = &xennet_ethtool_ops;
1765 	netdev->min_mtu = ETH_MIN_MTU;
1766 	netdev->max_mtu = XEN_NETIF_MAX_TX_SIZE;
1767 	SET_NETDEV_DEV(netdev, &dev->dev);
1768 
1769 	np->netdev = netdev;
1770 	np->netfront_xdp_enabled = false;
1771 
1772 	netif_carrier_off(netdev);
1773 
1774 	do {
1775 		xenbus_switch_state(dev, XenbusStateInitialising);
1776 		err = wait_event_timeout(module_wq,
1777 				 xenbus_read_driver_state(dev, dev->otherend) !=
1778 				 XenbusStateClosed &&
1779 				 xenbus_read_driver_state(dev, dev->otherend) !=
1780 				 XenbusStateUnknown, XENNET_TIMEOUT);
1781 	} while (!err);
1782 
1783 	return netdev;
1784 
1785  exit:
1786 	xennet_free_netdev(netdev);
1787 	return ERR_PTR(err);
1788 }
1789 
1790 /*
1791  * Entry point to this code when a new device is created.  Allocate the basic
1792  * structures and the ring buffers for communication with the backend, and
1793  * inform the backend of the appropriate details for those.
1794  */
1795 static int netfront_probe(struct xenbus_device *dev,
1796 			  const struct xenbus_device_id *id)
1797 {
1798 	int err;
1799 	struct net_device *netdev;
1800 	struct netfront_info *info;
1801 
1802 	netdev = xennet_create_dev(dev);
1803 	if (IS_ERR(netdev)) {
1804 		err = PTR_ERR(netdev);
1805 		xenbus_dev_fatal(dev, err, "creating netdev");
1806 		return err;
1807 	}
1808 
1809 	info = netdev_priv(netdev);
1810 	dev_set_drvdata(&dev->dev, info);
1811 #ifdef CONFIG_SYSFS
1812 	info->netdev->sysfs_groups[0] = &xennet_dev_group;
1813 #endif
1814 
1815 	return 0;
1816 }
1817 
1818 static void xennet_end_access(int ref, void *page)
1819 {
1820 	/* This frees the page as a side-effect */
1821 	if (ref != INVALID_GRANT_REF)
1822 		gnttab_end_foreign_access(ref, virt_to_page(page));
1823 }
1824 
1825 static void xennet_disconnect_backend(struct netfront_info *info)
1826 {
1827 	unsigned int i = 0;
1828 	unsigned int num_queues = info->netdev->real_num_tx_queues;
1829 
1830 	netif_carrier_off(info->netdev);
1831 
1832 	for (i = 0; i < num_queues && info->queues; ++i) {
1833 		struct netfront_queue *queue = &info->queues[i];
1834 
1835 		timer_delete_sync(&queue->rx_refill_timer);
1836 
1837 		if (queue->tx_irq && (queue->tx_irq == queue->rx_irq))
1838 			unbind_from_irqhandler(queue->tx_irq, queue);
1839 		if (queue->tx_irq && (queue->tx_irq != queue->rx_irq)) {
1840 			unbind_from_irqhandler(queue->tx_irq, queue);
1841 			unbind_from_irqhandler(queue->rx_irq, queue);
1842 		}
1843 		queue->tx_evtchn = queue->rx_evtchn = 0;
1844 		queue->tx_irq = queue->rx_irq = 0;
1845 
1846 		if (netif_running(info->netdev))
1847 			napi_synchronize(&queue->napi);
1848 
1849 		xennet_release_tx_bufs(queue);
1850 		xennet_release_rx_bufs(queue);
1851 		gnttab_free_grant_references(queue->gref_tx_head);
1852 		gnttab_free_grant_references(queue->gref_rx_head);
1853 
1854 		/* End access and free the pages */
1855 		xennet_end_access(queue->tx_ring_ref, queue->tx.sring);
1856 		xennet_end_access(queue->rx_ring_ref, queue->rx.sring);
1857 
1858 		queue->tx_ring_ref = INVALID_GRANT_REF;
1859 		queue->rx_ring_ref = INVALID_GRANT_REF;
1860 		queue->tx.sring = NULL;
1861 		queue->rx.sring = NULL;
1862 
1863 		page_pool_destroy(queue->page_pool);
1864 	}
1865 }
1866 
1867 /*
1868  * We are reconnecting to the backend, due to a suspend/resume, or a backend
1869  * driver restart.  We tear down our netif structure and recreate it, but
1870  * leave the device-layer structures intact so that this is transparent to the
1871  * rest of the kernel.
1872  */
1873 static int netfront_resume(struct xenbus_device *dev)
1874 {
1875 	struct netfront_info *info = dev_get_drvdata(&dev->dev);
1876 
1877 	dev_dbg(&dev->dev, "%s\n", dev->nodename);
1878 
1879 	netif_tx_lock_bh(info->netdev);
1880 	netif_device_detach(info->netdev);
1881 	netif_tx_unlock_bh(info->netdev);
1882 
1883 	xennet_disconnect_backend(info);
1884 
1885 	rtnl_lock();
1886 	if (info->queues)
1887 		xennet_destroy_queues(info);
1888 	rtnl_unlock();
1889 
1890 	return 0;
1891 }
1892 
1893 static int xen_net_read_mac(struct xenbus_device *dev, u8 mac[])
1894 {
1895 	char *s, *e, *macstr;
1896 	int i;
1897 
1898 	macstr = s = xenbus_read(XBT_NIL, dev->nodename, "mac", NULL);
1899 	if (IS_ERR(macstr))
1900 		return PTR_ERR(macstr);
1901 
1902 	for (i = 0; i < ETH_ALEN; i++) {
1903 		mac[i] = simple_strtoul(s, &e, 16);
1904 		if ((s == e) || (*e != ((i == ETH_ALEN-1) ? '\0' : ':'))) {
1905 			kfree(macstr);
1906 			return -ENOENT;
1907 		}
1908 		s = e+1;
1909 	}
1910 
1911 	kfree(macstr);
1912 	return 0;
1913 }
1914 
1915 static int setup_netfront_single(struct netfront_queue *queue)
1916 {
1917 	int err;
1918 
1919 	err = xenbus_alloc_evtchn(queue->info->xbdev, &queue->tx_evtchn);
1920 	if (err < 0)
1921 		goto fail;
1922 
1923 	err = bind_evtchn_to_irqhandler_lateeoi(queue->tx_evtchn,
1924 						xennet_interrupt, 0,
1925 						queue->info->netdev->name,
1926 						queue);
1927 	if (err < 0)
1928 		goto bind_fail;
1929 	queue->rx_evtchn = queue->tx_evtchn;
1930 	queue->rx_irq = queue->tx_irq = err;
1931 
1932 	return 0;
1933 
1934 bind_fail:
1935 	xenbus_free_evtchn(queue->info->xbdev, queue->tx_evtchn);
1936 	queue->tx_evtchn = 0;
1937 fail:
1938 	return err;
1939 }
1940 
1941 static int setup_netfront_split(struct netfront_queue *queue)
1942 {
1943 	int err;
1944 
1945 	err = xenbus_alloc_evtchn(queue->info->xbdev, &queue->tx_evtchn);
1946 	if (err < 0)
1947 		goto fail;
1948 	err = xenbus_alloc_evtchn(queue->info->xbdev, &queue->rx_evtchn);
1949 	if (err < 0)
1950 		goto alloc_rx_evtchn_fail;
1951 
1952 	snprintf(queue->tx_irq_name, sizeof(queue->tx_irq_name),
1953 		 "%s-tx", queue->name);
1954 	err = bind_evtchn_to_irqhandler_lateeoi(queue->tx_evtchn,
1955 						xennet_tx_interrupt, 0,
1956 						queue->tx_irq_name, queue);
1957 	if (err < 0)
1958 		goto bind_tx_fail;
1959 	queue->tx_irq = err;
1960 
1961 	snprintf(queue->rx_irq_name, sizeof(queue->rx_irq_name),
1962 		 "%s-rx", queue->name);
1963 	err = bind_evtchn_to_irqhandler_lateeoi(queue->rx_evtchn,
1964 						xennet_rx_interrupt, 0,
1965 						queue->rx_irq_name, queue);
1966 	if (err < 0)
1967 		goto bind_rx_fail;
1968 	queue->rx_irq = err;
1969 
1970 	return 0;
1971 
1972 bind_rx_fail:
1973 	unbind_from_irqhandler(queue->tx_irq, queue);
1974 	queue->tx_irq = 0;
1975 bind_tx_fail:
1976 	xenbus_free_evtchn(queue->info->xbdev, queue->rx_evtchn);
1977 	queue->rx_evtchn = 0;
1978 alloc_rx_evtchn_fail:
1979 	xenbus_free_evtchn(queue->info->xbdev, queue->tx_evtchn);
1980 	queue->tx_evtchn = 0;
1981 fail:
1982 	return err;
1983 }
1984 
1985 static int setup_netfront(struct xenbus_device *dev,
1986 			struct netfront_queue *queue, unsigned int feature_split_evtchn)
1987 {
1988 	struct xen_netif_tx_sring *txs;
1989 	struct xen_netif_rx_sring *rxs;
1990 	int err;
1991 
1992 	queue->tx_ring_ref = INVALID_GRANT_REF;
1993 	queue->rx_ring_ref = INVALID_GRANT_REF;
1994 	queue->rx.sring = NULL;
1995 	queue->tx.sring = NULL;
1996 
1997 	err = xenbus_setup_ring(dev, GFP_NOIO | __GFP_HIGH, (void **)&txs,
1998 				1, &queue->tx_ring_ref);
1999 	if (err)
2000 		goto fail;
2001 
2002 	XEN_FRONT_RING_INIT(&queue->tx, txs, XEN_PAGE_SIZE);
2003 
2004 	err = xenbus_setup_ring(dev, GFP_NOIO | __GFP_HIGH, (void **)&rxs,
2005 				1, &queue->rx_ring_ref);
2006 	if (err)
2007 		goto fail;
2008 
2009 	XEN_FRONT_RING_INIT(&queue->rx, rxs, XEN_PAGE_SIZE);
2010 
2011 	if (feature_split_evtchn)
2012 		err = setup_netfront_split(queue);
2013 	/* setup single event channel if
2014 	 *  a) feature-split-event-channels == 0
2015 	 *  b) feature-split-event-channels == 1 but failed to setup
2016 	 */
2017 	if (!feature_split_evtchn || err)
2018 		err = setup_netfront_single(queue);
2019 
2020 	if (err)
2021 		goto fail;
2022 
2023 	return 0;
2024 
2025  fail:
2026 	xenbus_teardown_ring((void **)&queue->rx.sring, 1, &queue->rx_ring_ref);
2027 	xenbus_teardown_ring((void **)&queue->tx.sring, 1, &queue->tx_ring_ref);
2028 
2029 	return err;
2030 }
2031 
2032 /* Queue-specific initialisation
2033  * This used to be done in xennet_create_dev() but must now
2034  * be run per-queue.
2035  */
2036 static int xennet_init_queue(struct netfront_queue *queue)
2037 {
2038 	unsigned short i;
2039 	int err = 0;
2040 	char *devid;
2041 
2042 	spin_lock_init(&queue->tx_lock);
2043 	spin_lock_init(&queue->rx_lock);
2044 	spin_lock_init(&queue->rx_cons_lock);
2045 
2046 	timer_setup(&queue->rx_refill_timer, rx_refill_timeout, 0);
2047 
2048 	devid = strrchr(queue->info->xbdev->nodename, '/') + 1;
2049 	snprintf(queue->name, sizeof(queue->name), "vif%s-q%u",
2050 		 devid, queue->id);
2051 
2052 	/* Initialise tx_skb_freelist as a free chain containing every entry. */
2053 	queue->tx_skb_freelist = 0;
2054 	queue->tx_pend_queue = TX_LINK_NONE;
2055 	for (i = 0; i < NET_TX_RING_SIZE; i++) {
2056 		queue->tx_link[i] = i + 1;
2057 		queue->grant_tx_ref[i] = INVALID_GRANT_REF;
2058 		queue->grant_tx_page[i] = NULL;
2059 	}
2060 	queue->tx_link[NET_TX_RING_SIZE - 1] = TX_LINK_NONE;
2061 
2062 	/* Clear out rx_skbs */
2063 	for (i = 0; i < NET_RX_RING_SIZE; i++) {
2064 		queue->rx_skbs[i] = NULL;
2065 		queue->grant_rx_ref[i] = INVALID_GRANT_REF;
2066 	}
2067 
2068 	/* A grant for every tx ring slot */
2069 	if (gnttab_alloc_grant_references(NET_TX_RING_SIZE,
2070 					  &queue->gref_tx_head) < 0) {
2071 		pr_alert("can't alloc tx grant refs\n");
2072 		err = -ENOMEM;
2073 		goto exit;
2074 	}
2075 
2076 	/* A grant for every rx ring slot */
2077 	if (gnttab_alloc_grant_references(NET_RX_RING_SIZE,
2078 					  &queue->gref_rx_head) < 0) {
2079 		pr_alert("can't alloc rx grant refs\n");
2080 		err = -ENOMEM;
2081 		goto exit_free_tx;
2082 	}
2083 
2084 	return 0;
2085 
2086  exit_free_tx:
2087 	gnttab_free_grant_references(queue->gref_tx_head);
2088  exit:
2089 	return err;
2090 }
2091 
2092 static int write_queue_xenstore_keys(struct netfront_queue *queue,
2093 			   struct xenbus_transaction *xbt, int write_hierarchical)
2094 {
2095 	/* Write the queue-specific keys into XenStore in the traditional
2096 	 * way for a single queue, or in a queue subkeys for multiple
2097 	 * queues.
2098 	 */
2099 	struct xenbus_device *dev = queue->info->xbdev;
2100 	int err;
2101 	const char *message;
2102 	char *path;
2103 	size_t pathsize;
2104 
2105 	/* Choose the correct place to write the keys */
2106 	if (write_hierarchical) {
2107 		pathsize = strlen(dev->nodename) + 10;
2108 		path = kzalloc(pathsize, GFP_KERNEL);
2109 		if (!path) {
2110 			err = -ENOMEM;
2111 			message = "out of memory while writing ring references";
2112 			goto error;
2113 		}
2114 		snprintf(path, pathsize, "%s/queue-%u",
2115 				dev->nodename, queue->id);
2116 	} else {
2117 		path = (char *)dev->nodename;
2118 	}
2119 
2120 	/* Write ring references */
2121 	err = xenbus_printf(*xbt, path, "tx-ring-ref", "%u",
2122 			queue->tx_ring_ref);
2123 	if (err) {
2124 		message = "writing tx-ring-ref";
2125 		goto error;
2126 	}
2127 
2128 	err = xenbus_printf(*xbt, path, "rx-ring-ref", "%u",
2129 			queue->rx_ring_ref);
2130 	if (err) {
2131 		message = "writing rx-ring-ref";
2132 		goto error;
2133 	}
2134 
2135 	/* Write event channels; taking into account both shared
2136 	 * and split event channel scenarios.
2137 	 */
2138 	if (queue->tx_evtchn == queue->rx_evtchn) {
2139 		/* Shared event channel */
2140 		err = xenbus_printf(*xbt, path,
2141 				"event-channel", "%u", queue->tx_evtchn);
2142 		if (err) {
2143 			message = "writing event-channel";
2144 			goto error;
2145 		}
2146 	} else {
2147 		/* Split event channels */
2148 		err = xenbus_printf(*xbt, path,
2149 				"event-channel-tx", "%u", queue->tx_evtchn);
2150 		if (err) {
2151 			message = "writing event-channel-tx";
2152 			goto error;
2153 		}
2154 
2155 		err = xenbus_printf(*xbt, path,
2156 				"event-channel-rx", "%u", queue->rx_evtchn);
2157 		if (err) {
2158 			message = "writing event-channel-rx";
2159 			goto error;
2160 		}
2161 	}
2162 
2163 	if (write_hierarchical)
2164 		kfree(path);
2165 	return 0;
2166 
2167 error:
2168 	if (write_hierarchical)
2169 		kfree(path);
2170 	xenbus_dev_fatal(dev, err, "%s", message);
2171 	return err;
2172 }
2173 
2174 
2175 
2176 static int xennet_create_page_pool(struct netfront_queue *queue)
2177 {
2178 	int err;
2179 	struct page_pool_params pp_params = {
2180 		.order = 0,
2181 		.flags = 0,
2182 		.pool_size = NET_RX_RING_SIZE,
2183 		.nid = NUMA_NO_NODE,
2184 		.dev = &queue->info->netdev->dev,
2185 		.offset = XDP_PACKET_HEADROOM,
2186 		.max_len = XEN_PAGE_SIZE - XDP_PACKET_HEADROOM,
2187 	};
2188 
2189 	queue->page_pool = page_pool_create(&pp_params);
2190 	if (IS_ERR(queue->page_pool)) {
2191 		err = PTR_ERR(queue->page_pool);
2192 		queue->page_pool = NULL;
2193 		return err;
2194 	}
2195 
2196 	err = xdp_rxq_info_reg(&queue->xdp_rxq, queue->info->netdev,
2197 			       queue->id, 0);
2198 	if (err) {
2199 		netdev_err(queue->info->netdev, "xdp_rxq_info_reg failed\n");
2200 		goto err_free_pp;
2201 	}
2202 
2203 	err = xdp_rxq_info_reg_mem_model(&queue->xdp_rxq,
2204 					 MEM_TYPE_PAGE_POOL, queue->page_pool);
2205 	if (err) {
2206 		netdev_err(queue->info->netdev, "xdp_rxq_info_reg_mem_model failed\n");
2207 		goto err_unregister_rxq;
2208 	}
2209 	return 0;
2210 
2211 err_unregister_rxq:
2212 	xdp_rxq_info_unreg(&queue->xdp_rxq);
2213 err_free_pp:
2214 	page_pool_destroy(queue->page_pool);
2215 	queue->page_pool = NULL;
2216 	return err;
2217 }
2218 
2219 static int xennet_create_queues(struct netfront_info *info,
2220 				unsigned int *num_queues)
2221 {
2222 	unsigned int i;
2223 	int ret;
2224 
2225 	info->queues = kzalloc_objs(struct netfront_queue, *num_queues);
2226 	if (!info->queues)
2227 		return -ENOMEM;
2228 
2229 	for (i = 0; i < *num_queues; i++) {
2230 		struct netfront_queue *queue = &info->queues[i];
2231 
2232 		queue->id = i;
2233 		queue->info = info;
2234 
2235 		ret = xennet_init_queue(queue);
2236 		if (ret < 0) {
2237 			dev_warn(&info->xbdev->dev,
2238 				 "only created %d queues\n", i);
2239 			*num_queues = i;
2240 			break;
2241 		}
2242 
2243 		/* use page pool recycling instead of buddy allocator */
2244 		ret = xennet_create_page_pool(queue);
2245 		if (ret < 0) {
2246 			dev_err(&info->xbdev->dev, "can't allocate page pool\n");
2247 			*num_queues = i;
2248 			return ret;
2249 		}
2250 
2251 		netif_napi_add(queue->info->netdev, &queue->napi, xennet_poll);
2252 		if (netif_running(info->netdev))
2253 			napi_enable(&queue->napi);
2254 	}
2255 
2256 	netif_set_real_num_tx_queues(info->netdev, *num_queues);
2257 
2258 	if (*num_queues == 0) {
2259 		dev_err(&info->xbdev->dev, "no queues\n");
2260 		return -EINVAL;
2261 	}
2262 	return 0;
2263 }
2264 
2265 /* Common code used when first setting up, and when resuming. */
2266 static int talk_to_netback(struct xenbus_device *dev,
2267 			   struct netfront_info *info)
2268 {
2269 	const char *message;
2270 	struct xenbus_transaction xbt;
2271 	int err;
2272 	unsigned int feature_split_evtchn;
2273 	unsigned int i = 0;
2274 	unsigned int max_queues = 0;
2275 	struct netfront_queue *queue = NULL;
2276 	unsigned int num_queues = 1;
2277 	u8 addr[ETH_ALEN];
2278 
2279 	info->netdev->irq = 0;
2280 
2281 	/* Check if backend is trusted. */
2282 	info->bounce = !xennet_trusted ||
2283 		       !xenbus_read_unsigned(dev->nodename, "trusted", 1);
2284 
2285 	/* Check if backend supports multiple queues */
2286 	max_queues = xenbus_read_unsigned(info->xbdev->otherend,
2287 					  "multi-queue-max-queues", 1);
2288 	num_queues = min(max_queues, xennet_max_queues);
2289 
2290 	/* Check feature-split-event-channels */
2291 	feature_split_evtchn = xenbus_read_unsigned(info->xbdev->otherend,
2292 					"feature-split-event-channels", 0);
2293 
2294 	/* Read mac addr. */
2295 	err = xen_net_read_mac(dev, addr);
2296 	if (err) {
2297 		xenbus_dev_fatal(dev, err, "parsing %s/mac", dev->nodename);
2298 		goto out_unlocked;
2299 	}
2300 	eth_hw_addr_set(info->netdev, addr);
2301 
2302 	info->netback_has_xdp_headroom = xenbus_read_unsigned(info->xbdev->otherend,
2303 							      "feature-xdp-headroom", 0);
2304 	if (info->netback_has_xdp_headroom) {
2305 		/* set the current xen-netfront xdp state */
2306 		err = talk_to_netback_xdp(info, info->netfront_xdp_enabled ?
2307 					  NETBACK_XDP_HEADROOM_ENABLE :
2308 					  NETBACK_XDP_HEADROOM_DISABLE);
2309 		if (err)
2310 			goto out_unlocked;
2311 	}
2312 
2313 	rtnl_lock();
2314 	if (info->queues)
2315 		xennet_destroy_queues(info);
2316 
2317 	/* For the case of a reconnect reset the "broken" indicator. */
2318 	info->broken = false;
2319 
2320 	err = xennet_create_queues(info, &num_queues);
2321 	if (err < 0) {
2322 		xenbus_dev_fatal(dev, err, "creating queues");
2323 		kfree(info->queues);
2324 		info->queues = NULL;
2325 		goto out;
2326 	}
2327 	rtnl_unlock();
2328 
2329 	/* Create shared ring, alloc event channel -- for each queue */
2330 	for (i = 0; i < num_queues; ++i) {
2331 		queue = &info->queues[i];
2332 		err = setup_netfront(dev, queue, feature_split_evtchn);
2333 		if (err)
2334 			goto destroy_ring;
2335 	}
2336 
2337 again:
2338 	err = xenbus_transaction_start(&xbt);
2339 	if (err) {
2340 		xenbus_dev_fatal(dev, err, "starting transaction");
2341 		goto destroy_ring;
2342 	}
2343 
2344 	if (xenbus_exists(XBT_NIL,
2345 			  info->xbdev->otherend, "multi-queue-max-queues")) {
2346 		/* Write the number of queues */
2347 		err = xenbus_printf(xbt, dev->nodename,
2348 				    "multi-queue-num-queues", "%u", num_queues);
2349 		if (err) {
2350 			message = "writing multi-queue-num-queues";
2351 			goto abort_transaction_no_dev_fatal;
2352 		}
2353 	}
2354 
2355 	if (num_queues == 1) {
2356 		err = write_queue_xenstore_keys(&info->queues[0], &xbt, 0); /* flat */
2357 		if (err)
2358 			goto abort_transaction_no_dev_fatal;
2359 	} else {
2360 		/* Write the keys for each queue */
2361 		for (i = 0; i < num_queues; ++i) {
2362 			queue = &info->queues[i];
2363 			err = write_queue_xenstore_keys(queue, &xbt, 1); /* hierarchical */
2364 			if (err)
2365 				goto abort_transaction_no_dev_fatal;
2366 		}
2367 	}
2368 
2369 	/* The remaining keys are not queue-specific */
2370 	err = xenbus_printf(xbt, dev->nodename, "request-rx-copy", "%u",
2371 			    1);
2372 	if (err) {
2373 		message = "writing request-rx-copy";
2374 		goto abort_transaction;
2375 	}
2376 
2377 	err = xenbus_printf(xbt, dev->nodename, "feature-rx-notify", "%d", 1);
2378 	if (err) {
2379 		message = "writing feature-rx-notify";
2380 		goto abort_transaction;
2381 	}
2382 
2383 	err = xenbus_printf(xbt, dev->nodename, "feature-sg", "%d", 1);
2384 	if (err) {
2385 		message = "writing feature-sg";
2386 		goto abort_transaction;
2387 	}
2388 
2389 	err = xenbus_printf(xbt, dev->nodename, "feature-gso-tcpv4", "%d", 1);
2390 	if (err) {
2391 		message = "writing feature-gso-tcpv4";
2392 		goto abort_transaction;
2393 	}
2394 
2395 	err = xenbus_write(xbt, dev->nodename, "feature-gso-tcpv6", "1");
2396 	if (err) {
2397 		message = "writing feature-gso-tcpv6";
2398 		goto abort_transaction;
2399 	}
2400 
2401 	err = xenbus_write(xbt, dev->nodename, "feature-ipv6-csum-offload",
2402 			   "1");
2403 	if (err) {
2404 		message = "writing feature-ipv6-csum-offload";
2405 		goto abort_transaction;
2406 	}
2407 
2408 	err = xenbus_transaction_end(xbt, 0);
2409 	if (err) {
2410 		if (err == -EAGAIN)
2411 			goto again;
2412 		xenbus_dev_fatal(dev, err, "completing transaction");
2413 		goto destroy_ring;
2414 	}
2415 
2416 	return 0;
2417 
2418  abort_transaction:
2419 	xenbus_dev_fatal(dev, err, "%s", message);
2420 abort_transaction_no_dev_fatal:
2421 	xenbus_transaction_end(xbt, 1);
2422  destroy_ring:
2423 	xennet_disconnect_backend(info);
2424 	rtnl_lock();
2425 	xennet_destroy_queues(info);
2426  out:
2427 	rtnl_unlock();
2428 out_unlocked:
2429 	device_unregister(&dev->dev);
2430 	return err;
2431 }
2432 
2433 static int xennet_connect(struct net_device *dev)
2434 {
2435 	struct netfront_info *np = netdev_priv(dev);
2436 	unsigned int num_queues = 0;
2437 	int err;
2438 	unsigned int j = 0;
2439 	struct netfront_queue *queue = NULL;
2440 
2441 	if (!xenbus_read_unsigned(np->xbdev->otherend, "feature-rx-copy", 0)) {
2442 		dev_info(&dev->dev,
2443 			 "backend does not support copying receive path\n");
2444 		return -ENODEV;
2445 	}
2446 
2447 	err = talk_to_netback(np->xbdev, np);
2448 	if (err)
2449 		return err;
2450 	if (np->netback_has_xdp_headroom)
2451 		pr_info("backend supports XDP headroom\n");
2452 	if (np->bounce)
2453 		dev_info(&np->xbdev->dev,
2454 			 "bouncing transmitted data to zeroed pages\n");
2455 
2456 	/* talk_to_netback() sets the correct number of queues */
2457 	num_queues = dev->real_num_tx_queues;
2458 
2459 	if (dev->reg_state == NETREG_UNINITIALIZED) {
2460 		err = register_netdev(dev);
2461 		if (err) {
2462 			pr_warn("%s: register_netdev err=%d\n", __func__, err);
2463 			device_unregister(&np->xbdev->dev);
2464 			return err;
2465 		}
2466 	}
2467 
2468 	rtnl_lock();
2469 	netdev_update_features(dev);
2470 	rtnl_unlock();
2471 
2472 	/*
2473 	 * All public and private state should now be sane.  Get
2474 	 * ready to start sending and receiving packets and give the driver
2475 	 * domain a kick because we've probably just requeued some
2476 	 * packets.
2477 	 */
2478 	netif_tx_lock_bh(np->netdev);
2479 	netif_device_attach(np->netdev);
2480 	netif_tx_unlock_bh(np->netdev);
2481 
2482 	netif_carrier_on(np->netdev);
2483 	for (j = 0; j < num_queues; ++j) {
2484 		queue = &np->queues[j];
2485 
2486 		notify_remote_via_irq(queue->tx_irq);
2487 		if (queue->tx_irq != queue->rx_irq)
2488 			notify_remote_via_irq(queue->rx_irq);
2489 
2490 		spin_lock_bh(&queue->rx_lock);
2491 		xennet_alloc_rx_buffers(queue);
2492 		spin_unlock_bh(&queue->rx_lock);
2493 	}
2494 
2495 	return 0;
2496 }
2497 
2498 /*
2499  * Callback received when the backend's state changes.
2500  */
2501 static void netback_changed(struct xenbus_device *dev,
2502 			    enum xenbus_state backend_state)
2503 {
2504 	struct netfront_info *np = dev_get_drvdata(&dev->dev);
2505 	struct net_device *netdev = np->netdev;
2506 
2507 	dev_dbg(&dev->dev, "%s\n", xenbus_strstate(backend_state));
2508 
2509 	wake_up_all(&module_wq);
2510 
2511 	switch (backend_state) {
2512 	case XenbusStateInitialising:
2513 	case XenbusStateInitialised:
2514 	case XenbusStateReconfiguring:
2515 	case XenbusStateReconfigured:
2516 	case XenbusStateUnknown:
2517 		break;
2518 
2519 	case XenbusStateInitWait:
2520 		if (dev->state != XenbusStateInitialising)
2521 			break;
2522 		if (xennet_connect(netdev) != 0)
2523 			break;
2524 		xenbus_switch_state(dev, XenbusStateConnected);
2525 		break;
2526 
2527 	case XenbusStateConnected:
2528 		netdev_notify_peers(netdev);
2529 		break;
2530 
2531 	case XenbusStateClosed:
2532 		if (dev->state == XenbusStateClosed)
2533 			break;
2534 		fallthrough;	/* Missed the backend's CLOSING state */
2535 	case XenbusStateClosing:
2536 		xenbus_frontend_closed(dev);
2537 		break;
2538 	}
2539 }
2540 
2541 static const struct xennet_stat {
2542 	char name[ETH_GSTRING_LEN];
2543 	u16 offset;
2544 } xennet_stats[] = {
2545 	{
2546 		"rx_gso_checksum_fixup",
2547 		offsetof(struct netfront_info, rx_gso_checksum_fixup)
2548 	},
2549 };
2550 
2551 static int xennet_get_sset_count(struct net_device *dev, int string_set)
2552 {
2553 	switch (string_set) {
2554 	case ETH_SS_STATS:
2555 		return ARRAY_SIZE(xennet_stats);
2556 	default:
2557 		return -EINVAL;
2558 	}
2559 }
2560 
2561 static void xennet_get_ethtool_stats(struct net_device *dev,
2562 				     struct ethtool_stats *stats, u64 * data)
2563 {
2564 	void *np = netdev_priv(dev);
2565 	int i;
2566 
2567 	for (i = 0; i < ARRAY_SIZE(xennet_stats); i++)
2568 		data[i] = atomic_read((atomic_t *)(np + xennet_stats[i].offset));
2569 }
2570 
2571 static void xennet_get_strings(struct net_device *dev, u32 stringset, u8 * data)
2572 {
2573 	int i;
2574 
2575 	switch (stringset) {
2576 	case ETH_SS_STATS:
2577 		for (i = 0; i < ARRAY_SIZE(xennet_stats); i++)
2578 			memcpy(data + i * ETH_GSTRING_LEN,
2579 			       xennet_stats[i].name, ETH_GSTRING_LEN);
2580 		break;
2581 	}
2582 }
2583 
2584 static const struct ethtool_ops xennet_ethtool_ops =
2585 {
2586 	.get_link = ethtool_op_get_link,
2587 
2588 	.get_sset_count = xennet_get_sset_count,
2589 	.get_ethtool_stats = xennet_get_ethtool_stats,
2590 	.get_strings = xennet_get_strings,
2591 	.get_ts_info = ethtool_op_get_ts_info,
2592 };
2593 
2594 #ifdef CONFIG_SYSFS
2595 static ssize_t show_rxbuf(struct device *dev,
2596 			  struct device_attribute *attr, char *buf)
2597 {
2598 	return sprintf(buf, "%lu\n", NET_RX_RING_SIZE);
2599 }
2600 
2601 static ssize_t store_rxbuf(struct device *dev,
2602 			   struct device_attribute *attr,
2603 			   const char *buf, size_t len)
2604 {
2605 	char *endp;
2606 
2607 	if (!capable(CAP_NET_ADMIN))
2608 		return -EPERM;
2609 
2610 	simple_strtoul(buf, &endp, 0);
2611 	if (endp == buf)
2612 		return -EBADMSG;
2613 
2614 	/* rxbuf_min and rxbuf_max are no longer configurable. */
2615 
2616 	return len;
2617 }
2618 
2619 static DEVICE_ATTR(rxbuf_min, 0644, show_rxbuf, store_rxbuf);
2620 static DEVICE_ATTR(rxbuf_max, 0644, show_rxbuf, store_rxbuf);
2621 static DEVICE_ATTR(rxbuf_cur, 0444, show_rxbuf, NULL);
2622 
2623 static struct attribute *xennet_dev_attrs[] = {
2624 	&dev_attr_rxbuf_min.attr,
2625 	&dev_attr_rxbuf_max.attr,
2626 	&dev_attr_rxbuf_cur.attr,
2627 	NULL
2628 };
2629 
2630 static const struct attribute_group xennet_dev_group = {
2631 	.attrs = xennet_dev_attrs
2632 };
2633 #endif /* CONFIG_SYSFS */
2634 
2635 static void xennet_bus_close(struct xenbus_device *dev)
2636 {
2637 	int ret;
2638 
2639 	if (xenbus_read_driver_state(dev, dev->otherend) == XenbusStateClosed)
2640 		return;
2641 	do {
2642 		xenbus_switch_state(dev, XenbusStateClosing);
2643 		ret = wait_event_timeout(module_wq,
2644 				xenbus_read_driver_state(dev, dev->otherend) ==
2645 				XenbusStateClosing ||
2646 				xenbus_read_driver_state(dev, dev->otherend) ==
2647 				XenbusStateClosed ||
2648 				xenbus_read_driver_state(dev, dev->otherend) ==
2649 				XenbusStateUnknown,
2650 				XENNET_TIMEOUT);
2651 	} while (!ret);
2652 
2653 	if (xenbus_read_driver_state(dev, dev->otherend) == XenbusStateClosed)
2654 		return;
2655 
2656 	do {
2657 		xenbus_switch_state(dev, XenbusStateClosed);
2658 		ret = wait_event_timeout(module_wq,
2659 				xenbus_read_driver_state(dev, dev->otherend) ==
2660 				XenbusStateClosed ||
2661 				xenbus_read_driver_state(dev, dev->otherend) ==
2662 				XenbusStateUnknown,
2663 				XENNET_TIMEOUT);
2664 	} while (!ret);
2665 }
2666 
2667 static void xennet_remove(struct xenbus_device *dev)
2668 {
2669 	struct netfront_info *info = dev_get_drvdata(&dev->dev);
2670 
2671 	xennet_bus_close(dev);
2672 	xennet_disconnect_backend(info);
2673 
2674 	if (info->netdev->reg_state == NETREG_REGISTERED)
2675 		unregister_netdev(info->netdev);
2676 
2677 	if (info->queues) {
2678 		rtnl_lock();
2679 		xennet_destroy_queues(info);
2680 		rtnl_unlock();
2681 	}
2682 	xennet_free_netdev(info->netdev);
2683 }
2684 
2685 static const struct xenbus_device_id netfront_ids[] = {
2686 	{ "vif" },
2687 	{ "" }
2688 };
2689 
2690 static struct xenbus_driver netfront_driver = {
2691 	.ids = netfront_ids,
2692 	.probe = netfront_probe,
2693 	.remove = xennet_remove,
2694 	.resume = netfront_resume,
2695 	.otherend_changed = netback_changed,
2696 };
2697 
2698 static int __init netif_init(void)
2699 {
2700 	if (!xen_domain())
2701 		return -ENODEV;
2702 
2703 	if (!xen_has_pv_nic_devices())
2704 		return -ENODEV;
2705 
2706 	pr_info("Initialising Xen virtual ethernet driver\n");
2707 
2708 	/* Allow the number of queues to match the number of CPUs, but not exceed
2709 	 * the maximum limit. If the user has not specified a value, the default
2710 	 * maximum limit is 8.
2711 	 */
2712 	if (xennet_max_queues == 0)
2713 		xennet_max_queues = min_t(unsigned int, MAX_QUEUES_DEFAULT,
2714 					  num_online_cpus());
2715 
2716 	return xenbus_register_frontend(&netfront_driver);
2717 }
2718 module_init(netif_init);
2719 
2720 
2721 static void __exit netif_exit(void)
2722 {
2723 	xenbus_unregister_driver(&netfront_driver);
2724 }
2725 module_exit(netif_exit);
2726 
2727 MODULE_DESCRIPTION("Xen virtual network device frontend");
2728 MODULE_LICENSE("GPL");
2729 MODULE_ALIAS("xen:vif");
2730 MODULE_ALIAS("xennet");
2731