xref: /openbmc/linux/drivers/net/xen-netfront.c (revision a13f2ef1)
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 
48 #include <xen/xen.h>
49 #include <xen/xenbus.h>
50 #include <xen/events.h>
51 #include <xen/page.h>
52 #include <xen/platform_pci.h>
53 #include <xen/grant_table.h>
54 
55 #include <xen/interface/io/netif.h>
56 #include <xen/interface/memory.h>
57 #include <xen/interface/grant_table.h>
58 
59 /* Module parameters */
60 #define MAX_QUEUES_DEFAULT 8
61 static unsigned int xennet_max_queues;
62 module_param_named(max_queues, xennet_max_queues, uint, 0644);
63 MODULE_PARM_DESC(max_queues,
64 		 "Maximum number of queues per virtual interface");
65 
66 #define XENNET_TIMEOUT  (5 * HZ)
67 
68 static const struct ethtool_ops xennet_ethtool_ops;
69 
70 struct netfront_cb {
71 	int pull_to;
72 };
73 
74 #define NETFRONT_SKB_CB(skb)	((struct netfront_cb *)((skb)->cb))
75 
76 #define RX_COPY_THRESHOLD 256
77 
78 #define GRANT_INVALID_REF	0
79 
80 #define NET_TX_RING_SIZE __CONST_RING_SIZE(xen_netif_tx, XEN_PAGE_SIZE)
81 #define NET_RX_RING_SIZE __CONST_RING_SIZE(xen_netif_rx, XEN_PAGE_SIZE)
82 
83 /* Minimum number of Rx slots (includes slot for GSO metadata). */
84 #define NET_RX_SLOTS_MIN (XEN_NETIF_NR_SLOTS_MIN + 1)
85 
86 /* Queue name is interface name with "-qNNN" appended */
87 #define QUEUE_NAME_SIZE (IFNAMSIZ + 6)
88 
89 /* IRQ name is queue name with "-tx" or "-rx" appended */
90 #define IRQ_NAME_SIZE (QUEUE_NAME_SIZE + 3)
91 
92 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
93 
94 struct netfront_stats {
95 	u64			packets;
96 	u64			bytes;
97 	struct u64_stats_sync	syncp;
98 };
99 
100 struct netfront_info;
101 
102 struct netfront_queue {
103 	unsigned int id; /* Queue ID, 0-based */
104 	char name[QUEUE_NAME_SIZE]; /* DEVNAME-qN */
105 	struct netfront_info *info;
106 
107 	struct napi_struct napi;
108 
109 	/* Split event channels support, tx_* == rx_* when using
110 	 * single event channel.
111 	 */
112 	unsigned int tx_evtchn, rx_evtchn;
113 	unsigned int tx_irq, rx_irq;
114 	/* Only used when split event channels support is enabled */
115 	char tx_irq_name[IRQ_NAME_SIZE]; /* DEVNAME-qN-tx */
116 	char rx_irq_name[IRQ_NAME_SIZE]; /* DEVNAME-qN-rx */
117 
118 	spinlock_t   tx_lock;
119 	struct xen_netif_tx_front_ring tx;
120 	int tx_ring_ref;
121 
122 	/*
123 	 * {tx,rx}_skbs store outstanding skbuffs. Free tx_skb entries
124 	 * are linked from tx_skb_freelist through skb_entry.link.
125 	 *
126 	 *  NB. Freelist index entries are always going to be less than
127 	 *  PAGE_OFFSET, whereas pointers to skbs will always be equal or
128 	 *  greater than PAGE_OFFSET: we use this property to distinguish
129 	 *  them.
130 	 */
131 	union skb_entry {
132 		struct sk_buff *skb;
133 		unsigned long link;
134 	} tx_skbs[NET_TX_RING_SIZE];
135 	grant_ref_t gref_tx_head;
136 	grant_ref_t grant_tx_ref[NET_TX_RING_SIZE];
137 	struct page *grant_tx_page[NET_TX_RING_SIZE];
138 	unsigned tx_skb_freelist;
139 
140 	spinlock_t   rx_lock ____cacheline_aligned_in_smp;
141 	struct xen_netif_rx_front_ring rx;
142 	int rx_ring_ref;
143 
144 	struct timer_list rx_refill_timer;
145 
146 	struct sk_buff *rx_skbs[NET_RX_RING_SIZE];
147 	grant_ref_t gref_rx_head;
148 	grant_ref_t grant_rx_ref[NET_RX_RING_SIZE];
149 };
150 
151 struct netfront_info {
152 	struct list_head list;
153 	struct net_device *netdev;
154 
155 	struct xenbus_device *xbdev;
156 
157 	/* Multi-queue support */
158 	struct netfront_queue *queues;
159 
160 	/* Statistics */
161 	struct netfront_stats __percpu *rx_stats;
162 	struct netfront_stats __percpu *tx_stats;
163 
164 	atomic_t rx_gso_checksum_fixup;
165 };
166 
167 struct netfront_rx_info {
168 	struct xen_netif_rx_response rx;
169 	struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX - 1];
170 };
171 
172 static void skb_entry_set_link(union skb_entry *list, unsigned short id)
173 {
174 	list->link = id;
175 }
176 
177 static int skb_entry_is_link(const union skb_entry *list)
178 {
179 	BUILD_BUG_ON(sizeof(list->skb) != sizeof(list->link));
180 	return (unsigned long)list->skb < PAGE_OFFSET;
181 }
182 
183 /*
184  * Access macros for acquiring freeing slots in tx_skbs[].
185  */
186 
187 static void add_id_to_freelist(unsigned *head, union skb_entry *list,
188 			       unsigned short id)
189 {
190 	skb_entry_set_link(&list[id], *head);
191 	*head = id;
192 }
193 
194 static unsigned short get_id_from_freelist(unsigned *head,
195 					   union skb_entry *list)
196 {
197 	unsigned int id = *head;
198 	*head = list[id].link;
199 	return id;
200 }
201 
202 static int xennet_rxidx(RING_IDX idx)
203 {
204 	return idx & (NET_RX_RING_SIZE - 1);
205 }
206 
207 static struct sk_buff *xennet_get_rx_skb(struct netfront_queue *queue,
208 					 RING_IDX ri)
209 {
210 	int i = xennet_rxidx(ri);
211 	struct sk_buff *skb = queue->rx_skbs[i];
212 	queue->rx_skbs[i] = NULL;
213 	return skb;
214 }
215 
216 static grant_ref_t xennet_get_rx_ref(struct netfront_queue *queue,
217 					    RING_IDX ri)
218 {
219 	int i = xennet_rxidx(ri);
220 	grant_ref_t ref = queue->grant_rx_ref[i];
221 	queue->grant_rx_ref[i] = GRANT_INVALID_REF;
222 	return ref;
223 }
224 
225 #ifdef CONFIG_SYSFS
226 static const struct attribute_group xennet_dev_group;
227 #endif
228 
229 static bool xennet_can_sg(struct net_device *dev)
230 {
231 	return dev->features & NETIF_F_SG;
232 }
233 
234 
235 static void rx_refill_timeout(struct timer_list *t)
236 {
237 	struct netfront_queue *queue = from_timer(queue, t, rx_refill_timer);
238 	napi_schedule(&queue->napi);
239 }
240 
241 static int netfront_tx_slot_available(struct netfront_queue *queue)
242 {
243 	return (queue->tx.req_prod_pvt - queue->tx.rsp_cons) <
244 		(NET_TX_RING_SIZE - XEN_NETIF_NR_SLOTS_MIN - 1);
245 }
246 
247 static void xennet_maybe_wake_tx(struct netfront_queue *queue)
248 {
249 	struct net_device *dev = queue->info->netdev;
250 	struct netdev_queue *dev_queue = netdev_get_tx_queue(dev, queue->id);
251 
252 	if (unlikely(netif_tx_queue_stopped(dev_queue)) &&
253 	    netfront_tx_slot_available(queue) &&
254 	    likely(netif_running(dev)))
255 		netif_tx_wake_queue(netdev_get_tx_queue(dev, queue->id));
256 }
257 
258 
259 static struct sk_buff *xennet_alloc_one_rx_buffer(struct netfront_queue *queue)
260 {
261 	struct sk_buff *skb;
262 	struct page *page;
263 
264 	skb = __netdev_alloc_skb(queue->info->netdev,
265 				 RX_COPY_THRESHOLD + NET_IP_ALIGN,
266 				 GFP_ATOMIC | __GFP_NOWARN);
267 	if (unlikely(!skb))
268 		return NULL;
269 
270 	page = alloc_page(GFP_ATOMIC | __GFP_NOWARN);
271 	if (!page) {
272 		kfree_skb(skb);
273 		return NULL;
274 	}
275 	skb_add_rx_frag(skb, 0, page, 0, 0, PAGE_SIZE);
276 
277 	/* Align ip header to a 16 bytes boundary */
278 	skb_reserve(skb, NET_IP_ALIGN);
279 	skb->dev = queue->info->netdev;
280 
281 	return skb;
282 }
283 
284 
285 static void xennet_alloc_rx_buffers(struct netfront_queue *queue)
286 {
287 	RING_IDX req_prod = queue->rx.req_prod_pvt;
288 	int notify;
289 	int err = 0;
290 
291 	if (unlikely(!netif_carrier_ok(queue->info->netdev)))
292 		return;
293 
294 	for (req_prod = queue->rx.req_prod_pvt;
295 	     req_prod - queue->rx.rsp_cons < NET_RX_RING_SIZE;
296 	     req_prod++) {
297 		struct sk_buff *skb;
298 		unsigned short id;
299 		grant_ref_t ref;
300 		struct page *page;
301 		struct xen_netif_rx_request *req;
302 
303 		skb = xennet_alloc_one_rx_buffer(queue);
304 		if (!skb) {
305 			err = -ENOMEM;
306 			break;
307 		}
308 
309 		id = xennet_rxidx(req_prod);
310 
311 		BUG_ON(queue->rx_skbs[id]);
312 		queue->rx_skbs[id] = skb;
313 
314 		ref = gnttab_claim_grant_reference(&queue->gref_rx_head);
315 		WARN_ON_ONCE(IS_ERR_VALUE((unsigned long)(int)ref));
316 		queue->grant_rx_ref[id] = ref;
317 
318 		page = skb_frag_page(&skb_shinfo(skb)->frags[0]);
319 
320 		req = RING_GET_REQUEST(&queue->rx, req_prod);
321 		gnttab_page_grant_foreign_access_ref_one(ref,
322 							 queue->info->xbdev->otherend_id,
323 							 page,
324 							 0);
325 		req->id = id;
326 		req->gref = ref;
327 	}
328 
329 	queue->rx.req_prod_pvt = req_prod;
330 
331 	/* Try again later if there are not enough requests or skb allocation
332 	 * failed.
333 	 * Enough requests is quantified as the sum of newly created slots and
334 	 * the unconsumed slots at the backend.
335 	 */
336 	if (req_prod - queue->rx.rsp_cons < NET_RX_SLOTS_MIN ||
337 	    unlikely(err)) {
338 		mod_timer(&queue->rx_refill_timer, jiffies + (HZ/10));
339 		return;
340 	}
341 
342 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&queue->rx, notify);
343 	if (notify)
344 		notify_remote_via_irq(queue->rx_irq);
345 }
346 
347 static int xennet_open(struct net_device *dev)
348 {
349 	struct netfront_info *np = netdev_priv(dev);
350 	unsigned int num_queues = dev->real_num_tx_queues;
351 	unsigned int i = 0;
352 	struct netfront_queue *queue = NULL;
353 
354 	if (!np->queues)
355 		return -ENODEV;
356 
357 	for (i = 0; i < num_queues; ++i) {
358 		queue = &np->queues[i];
359 		napi_enable(&queue->napi);
360 
361 		spin_lock_bh(&queue->rx_lock);
362 		if (netif_carrier_ok(dev)) {
363 			xennet_alloc_rx_buffers(queue);
364 			queue->rx.sring->rsp_event = queue->rx.rsp_cons + 1;
365 			if (RING_HAS_UNCONSUMED_RESPONSES(&queue->rx))
366 				napi_schedule(&queue->napi);
367 		}
368 		spin_unlock_bh(&queue->rx_lock);
369 	}
370 
371 	netif_tx_start_all_queues(dev);
372 
373 	return 0;
374 }
375 
376 static void xennet_tx_buf_gc(struct netfront_queue *queue)
377 {
378 	RING_IDX cons, prod;
379 	unsigned short id;
380 	struct sk_buff *skb;
381 	bool more_to_do;
382 
383 	BUG_ON(!netif_carrier_ok(queue->info->netdev));
384 
385 	do {
386 		prod = queue->tx.sring->rsp_prod;
387 		rmb(); /* Ensure we see responses up to 'rp'. */
388 
389 		for (cons = queue->tx.rsp_cons; cons != prod; cons++) {
390 			struct xen_netif_tx_response *txrsp;
391 
392 			txrsp = RING_GET_RESPONSE(&queue->tx, cons);
393 			if (txrsp->status == XEN_NETIF_RSP_NULL)
394 				continue;
395 
396 			id  = txrsp->id;
397 			skb = queue->tx_skbs[id].skb;
398 			if (unlikely(gnttab_query_foreign_access(
399 				queue->grant_tx_ref[id]) != 0)) {
400 				pr_alert("%s: warning -- grant still in use by backend domain\n",
401 					 __func__);
402 				BUG();
403 			}
404 			gnttab_end_foreign_access_ref(
405 				queue->grant_tx_ref[id], GNTMAP_readonly);
406 			gnttab_release_grant_reference(
407 				&queue->gref_tx_head, queue->grant_tx_ref[id]);
408 			queue->grant_tx_ref[id] = GRANT_INVALID_REF;
409 			queue->grant_tx_page[id] = NULL;
410 			add_id_to_freelist(&queue->tx_skb_freelist, queue->tx_skbs, id);
411 			dev_kfree_skb_irq(skb);
412 		}
413 
414 		queue->tx.rsp_cons = prod;
415 
416 		RING_FINAL_CHECK_FOR_RESPONSES(&queue->tx, more_to_do);
417 	} while (more_to_do);
418 
419 	xennet_maybe_wake_tx(queue);
420 }
421 
422 struct xennet_gnttab_make_txreq {
423 	struct netfront_queue *queue;
424 	struct sk_buff *skb;
425 	struct page *page;
426 	struct xen_netif_tx_request *tx; /* Last request */
427 	unsigned int size;
428 };
429 
430 static void xennet_tx_setup_grant(unsigned long gfn, unsigned int offset,
431 				  unsigned int len, void *data)
432 {
433 	struct xennet_gnttab_make_txreq *info = data;
434 	unsigned int id;
435 	struct xen_netif_tx_request *tx;
436 	grant_ref_t ref;
437 	/* convenient aliases */
438 	struct page *page = info->page;
439 	struct netfront_queue *queue = info->queue;
440 	struct sk_buff *skb = info->skb;
441 
442 	id = get_id_from_freelist(&queue->tx_skb_freelist, queue->tx_skbs);
443 	tx = RING_GET_REQUEST(&queue->tx, queue->tx.req_prod_pvt++);
444 	ref = gnttab_claim_grant_reference(&queue->gref_tx_head);
445 	WARN_ON_ONCE(IS_ERR_VALUE((unsigned long)(int)ref));
446 
447 	gnttab_grant_foreign_access_ref(ref, queue->info->xbdev->otherend_id,
448 					gfn, GNTMAP_readonly);
449 
450 	queue->tx_skbs[id].skb = skb;
451 	queue->grant_tx_page[id] = page;
452 	queue->grant_tx_ref[id] = ref;
453 
454 	tx->id = id;
455 	tx->gref = ref;
456 	tx->offset = offset;
457 	tx->size = len;
458 	tx->flags = 0;
459 
460 	info->tx = tx;
461 	info->size += tx->size;
462 }
463 
464 static struct xen_netif_tx_request *xennet_make_first_txreq(
465 	struct netfront_queue *queue, struct sk_buff *skb,
466 	struct page *page, unsigned int offset, unsigned int len)
467 {
468 	struct xennet_gnttab_make_txreq info = {
469 		.queue = queue,
470 		.skb = skb,
471 		.page = page,
472 		.size = 0,
473 	};
474 
475 	gnttab_for_one_grant(page, offset, len, xennet_tx_setup_grant, &info);
476 
477 	return info.tx;
478 }
479 
480 static void xennet_make_one_txreq(unsigned long gfn, unsigned int offset,
481 				  unsigned int len, void *data)
482 {
483 	struct xennet_gnttab_make_txreq *info = data;
484 
485 	info->tx->flags |= XEN_NETTXF_more_data;
486 	skb_get(info->skb);
487 	xennet_tx_setup_grant(gfn, offset, len, data);
488 }
489 
490 static struct xen_netif_tx_request *xennet_make_txreqs(
491 	struct netfront_queue *queue, struct xen_netif_tx_request *tx,
492 	struct sk_buff *skb, struct page *page,
493 	unsigned int offset, unsigned int len)
494 {
495 	struct xennet_gnttab_make_txreq info = {
496 		.queue = queue,
497 		.skb = skb,
498 		.tx = tx,
499 	};
500 
501 	/* Skip unused frames from start of page */
502 	page += offset >> PAGE_SHIFT;
503 	offset &= ~PAGE_MASK;
504 
505 	while (len) {
506 		info.page = page;
507 		info.size = 0;
508 
509 		gnttab_foreach_grant_in_range(page, offset, len,
510 					      xennet_make_one_txreq,
511 					      &info);
512 
513 		page++;
514 		offset = 0;
515 		len -= info.size;
516 	}
517 
518 	return info.tx;
519 }
520 
521 /*
522  * Count how many ring slots are required to send this skb. Each frag
523  * might be a compound page.
524  */
525 static int xennet_count_skb_slots(struct sk_buff *skb)
526 {
527 	int i, frags = skb_shinfo(skb)->nr_frags;
528 	int slots;
529 
530 	slots = gnttab_count_grant(offset_in_page(skb->data),
531 				   skb_headlen(skb));
532 
533 	for (i = 0; i < frags; i++) {
534 		skb_frag_t *frag = skb_shinfo(skb)->frags + i;
535 		unsigned long size = skb_frag_size(frag);
536 		unsigned long offset = skb_frag_off(frag);
537 
538 		/* Skip unused frames from start of page */
539 		offset &= ~PAGE_MASK;
540 
541 		slots += gnttab_count_grant(offset, size);
542 	}
543 
544 	return slots;
545 }
546 
547 static u16 xennet_select_queue(struct net_device *dev, struct sk_buff *skb,
548 			       struct net_device *sb_dev)
549 {
550 	unsigned int num_queues = dev->real_num_tx_queues;
551 	u32 hash;
552 	u16 queue_idx;
553 
554 	/* First, check if there is only one queue */
555 	if (num_queues == 1) {
556 		queue_idx = 0;
557 	} else {
558 		hash = skb_get_hash(skb);
559 		queue_idx = hash % num_queues;
560 	}
561 
562 	return queue_idx;
563 }
564 
565 #define MAX_XEN_SKB_FRAGS (65536 / XEN_PAGE_SIZE + 1)
566 
567 static netdev_tx_t xennet_start_xmit(struct sk_buff *skb, struct net_device *dev)
568 {
569 	struct netfront_info *np = netdev_priv(dev);
570 	struct netfront_stats *tx_stats = this_cpu_ptr(np->tx_stats);
571 	struct xen_netif_tx_request *tx, *first_tx;
572 	unsigned int i;
573 	int notify;
574 	int slots;
575 	struct page *page;
576 	unsigned int offset;
577 	unsigned int len;
578 	unsigned long flags;
579 	struct netfront_queue *queue = NULL;
580 	unsigned int num_queues = dev->real_num_tx_queues;
581 	u16 queue_index;
582 	struct sk_buff *nskb;
583 
584 	/* Drop the packet if no queues are set up */
585 	if (num_queues < 1)
586 		goto drop;
587 	/* Determine which queue to transmit this SKB on */
588 	queue_index = skb_get_queue_mapping(skb);
589 	queue = &np->queues[queue_index];
590 
591 	/* If skb->len is too big for wire format, drop skb and alert
592 	 * user about misconfiguration.
593 	 */
594 	if (unlikely(skb->len > XEN_NETIF_MAX_TX_SIZE)) {
595 		net_alert_ratelimited(
596 			"xennet: skb->len = %u, too big for wire format\n",
597 			skb->len);
598 		goto drop;
599 	}
600 
601 	slots = xennet_count_skb_slots(skb);
602 	if (unlikely(slots > MAX_XEN_SKB_FRAGS + 1)) {
603 		net_dbg_ratelimited("xennet: skb rides the rocket: %d slots, %d bytes\n",
604 				    slots, skb->len);
605 		if (skb_linearize(skb))
606 			goto drop;
607 	}
608 
609 	page = virt_to_page(skb->data);
610 	offset = offset_in_page(skb->data);
611 
612 	/* The first req should be at least ETH_HLEN size or the packet will be
613 	 * dropped by netback.
614 	 */
615 	if (unlikely(PAGE_SIZE - offset < ETH_HLEN)) {
616 		nskb = skb_copy(skb, GFP_ATOMIC);
617 		if (!nskb)
618 			goto drop;
619 		dev_consume_skb_any(skb);
620 		skb = nskb;
621 		page = virt_to_page(skb->data);
622 		offset = offset_in_page(skb->data);
623 	}
624 
625 	len = skb_headlen(skb);
626 
627 	spin_lock_irqsave(&queue->tx_lock, flags);
628 
629 	if (unlikely(!netif_carrier_ok(dev) ||
630 		     (slots > 1 && !xennet_can_sg(dev)) ||
631 		     netif_needs_gso(skb, netif_skb_features(skb)))) {
632 		spin_unlock_irqrestore(&queue->tx_lock, flags);
633 		goto drop;
634 	}
635 
636 	/* First request for the linear area. */
637 	first_tx = tx = xennet_make_first_txreq(queue, skb,
638 						page, offset, len);
639 	offset += tx->size;
640 	if (offset == PAGE_SIZE) {
641 		page++;
642 		offset = 0;
643 	}
644 	len -= tx->size;
645 
646 	if (skb->ip_summed == CHECKSUM_PARTIAL)
647 		/* local packet? */
648 		tx->flags |= XEN_NETTXF_csum_blank | XEN_NETTXF_data_validated;
649 	else if (skb->ip_summed == CHECKSUM_UNNECESSARY)
650 		/* remote but checksummed. */
651 		tx->flags |= XEN_NETTXF_data_validated;
652 
653 	/* Optional extra info after the first request. */
654 	if (skb_shinfo(skb)->gso_size) {
655 		struct xen_netif_extra_info *gso;
656 
657 		gso = (struct xen_netif_extra_info *)
658 			RING_GET_REQUEST(&queue->tx, queue->tx.req_prod_pvt++);
659 
660 		tx->flags |= XEN_NETTXF_extra_info;
661 
662 		gso->u.gso.size = skb_shinfo(skb)->gso_size;
663 		gso->u.gso.type = (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) ?
664 			XEN_NETIF_GSO_TYPE_TCPV6 :
665 			XEN_NETIF_GSO_TYPE_TCPV4;
666 		gso->u.gso.pad = 0;
667 		gso->u.gso.features = 0;
668 
669 		gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
670 		gso->flags = 0;
671 	}
672 
673 	/* Requests for the rest of the linear area. */
674 	tx = xennet_make_txreqs(queue, tx, skb, page, offset, len);
675 
676 	/* Requests for all the frags. */
677 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
678 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
679 		tx = xennet_make_txreqs(queue, tx, skb, skb_frag_page(frag),
680 					skb_frag_off(frag),
681 					skb_frag_size(frag));
682 	}
683 
684 	/* First request has the packet length. */
685 	first_tx->size = skb->len;
686 
687 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&queue->tx, notify);
688 	if (notify)
689 		notify_remote_via_irq(queue->tx_irq);
690 
691 	u64_stats_update_begin(&tx_stats->syncp);
692 	tx_stats->bytes += skb->len;
693 	tx_stats->packets++;
694 	u64_stats_update_end(&tx_stats->syncp);
695 
696 	/* Note: It is not safe to access skb after xennet_tx_buf_gc()! */
697 	xennet_tx_buf_gc(queue);
698 
699 	if (!netfront_tx_slot_available(queue))
700 		netif_tx_stop_queue(netdev_get_tx_queue(dev, queue->id));
701 
702 	spin_unlock_irqrestore(&queue->tx_lock, flags);
703 
704 	return NETDEV_TX_OK;
705 
706  drop:
707 	dev->stats.tx_dropped++;
708 	dev_kfree_skb_any(skb);
709 	return NETDEV_TX_OK;
710 }
711 
712 static int xennet_close(struct net_device *dev)
713 {
714 	struct netfront_info *np = netdev_priv(dev);
715 	unsigned int num_queues = dev->real_num_tx_queues;
716 	unsigned int i;
717 	struct netfront_queue *queue;
718 	netif_tx_stop_all_queues(np->netdev);
719 	for (i = 0; i < num_queues; ++i) {
720 		queue = &np->queues[i];
721 		napi_disable(&queue->napi);
722 	}
723 	return 0;
724 }
725 
726 static void xennet_move_rx_slot(struct netfront_queue *queue, struct sk_buff *skb,
727 				grant_ref_t ref)
728 {
729 	int new = xennet_rxidx(queue->rx.req_prod_pvt);
730 
731 	BUG_ON(queue->rx_skbs[new]);
732 	queue->rx_skbs[new] = skb;
733 	queue->grant_rx_ref[new] = ref;
734 	RING_GET_REQUEST(&queue->rx, queue->rx.req_prod_pvt)->id = new;
735 	RING_GET_REQUEST(&queue->rx, queue->rx.req_prod_pvt)->gref = ref;
736 	queue->rx.req_prod_pvt++;
737 }
738 
739 static int xennet_get_extras(struct netfront_queue *queue,
740 			     struct xen_netif_extra_info *extras,
741 			     RING_IDX rp)
742 
743 {
744 	struct xen_netif_extra_info *extra;
745 	struct device *dev = &queue->info->netdev->dev;
746 	RING_IDX cons = queue->rx.rsp_cons;
747 	int err = 0;
748 
749 	do {
750 		struct sk_buff *skb;
751 		grant_ref_t ref;
752 
753 		if (unlikely(cons + 1 == rp)) {
754 			if (net_ratelimit())
755 				dev_warn(dev, "Missing extra info\n");
756 			err = -EBADR;
757 			break;
758 		}
759 
760 		extra = (struct xen_netif_extra_info *)
761 			RING_GET_RESPONSE(&queue->rx, ++cons);
762 
763 		if (unlikely(!extra->type ||
764 			     extra->type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
765 			if (net_ratelimit())
766 				dev_warn(dev, "Invalid extra type: %d\n",
767 					extra->type);
768 			err = -EINVAL;
769 		} else {
770 			memcpy(&extras[extra->type - 1], extra,
771 			       sizeof(*extra));
772 		}
773 
774 		skb = xennet_get_rx_skb(queue, cons);
775 		ref = xennet_get_rx_ref(queue, cons);
776 		xennet_move_rx_slot(queue, skb, ref);
777 	} while (extra->flags & XEN_NETIF_EXTRA_FLAG_MORE);
778 
779 	queue->rx.rsp_cons = cons;
780 	return err;
781 }
782 
783 static int xennet_get_responses(struct netfront_queue *queue,
784 				struct netfront_rx_info *rinfo, RING_IDX rp,
785 				struct sk_buff_head *list)
786 {
787 	struct xen_netif_rx_response *rx = &rinfo->rx;
788 	struct xen_netif_extra_info *extras = rinfo->extras;
789 	struct device *dev = &queue->info->netdev->dev;
790 	RING_IDX cons = queue->rx.rsp_cons;
791 	struct sk_buff *skb = xennet_get_rx_skb(queue, cons);
792 	grant_ref_t ref = xennet_get_rx_ref(queue, cons);
793 	int max = XEN_NETIF_NR_SLOTS_MIN + (rx->status <= RX_COPY_THRESHOLD);
794 	int slots = 1;
795 	int err = 0;
796 	unsigned long ret;
797 
798 	if (rx->flags & XEN_NETRXF_extra_info) {
799 		err = xennet_get_extras(queue, extras, rp);
800 		cons = queue->rx.rsp_cons;
801 	}
802 
803 	for (;;) {
804 		if (unlikely(rx->status < 0 ||
805 			     rx->offset + rx->status > XEN_PAGE_SIZE)) {
806 			if (net_ratelimit())
807 				dev_warn(dev, "rx->offset: %u, size: %d\n",
808 					 rx->offset, rx->status);
809 			xennet_move_rx_slot(queue, skb, ref);
810 			err = -EINVAL;
811 			goto next;
812 		}
813 
814 		/*
815 		 * This definitely indicates a bug, either in this driver or in
816 		 * the backend driver. In future this should flag the bad
817 		 * situation to the system controller to reboot the backend.
818 		 */
819 		if (ref == GRANT_INVALID_REF) {
820 			if (net_ratelimit())
821 				dev_warn(dev, "Bad rx response id %d.\n",
822 					 rx->id);
823 			err = -EINVAL;
824 			goto next;
825 		}
826 
827 		ret = gnttab_end_foreign_access_ref(ref, 0);
828 		BUG_ON(!ret);
829 
830 		gnttab_release_grant_reference(&queue->gref_rx_head, ref);
831 
832 		__skb_queue_tail(list, skb);
833 
834 next:
835 		if (!(rx->flags & XEN_NETRXF_more_data))
836 			break;
837 
838 		if (cons + slots == rp) {
839 			if (net_ratelimit())
840 				dev_warn(dev, "Need more slots\n");
841 			err = -ENOENT;
842 			break;
843 		}
844 
845 		rx = RING_GET_RESPONSE(&queue->rx, cons + slots);
846 		skb = xennet_get_rx_skb(queue, cons + slots);
847 		ref = xennet_get_rx_ref(queue, cons + slots);
848 		slots++;
849 	}
850 
851 	if (unlikely(slots > max)) {
852 		if (net_ratelimit())
853 			dev_warn(dev, "Too many slots\n");
854 		err = -E2BIG;
855 	}
856 
857 	if (unlikely(err))
858 		queue->rx.rsp_cons = cons + slots;
859 
860 	return err;
861 }
862 
863 static int xennet_set_skb_gso(struct sk_buff *skb,
864 			      struct xen_netif_extra_info *gso)
865 {
866 	if (!gso->u.gso.size) {
867 		if (net_ratelimit())
868 			pr_warn("GSO size must not be zero\n");
869 		return -EINVAL;
870 	}
871 
872 	if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4 &&
873 	    gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV6) {
874 		if (net_ratelimit())
875 			pr_warn("Bad GSO type %d\n", gso->u.gso.type);
876 		return -EINVAL;
877 	}
878 
879 	skb_shinfo(skb)->gso_size = gso->u.gso.size;
880 	skb_shinfo(skb)->gso_type =
881 		(gso->u.gso.type == XEN_NETIF_GSO_TYPE_TCPV4) ?
882 		SKB_GSO_TCPV4 :
883 		SKB_GSO_TCPV6;
884 
885 	/* Header must be checked, and gso_segs computed. */
886 	skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
887 	skb_shinfo(skb)->gso_segs = 0;
888 
889 	return 0;
890 }
891 
892 static int xennet_fill_frags(struct netfront_queue *queue,
893 			     struct sk_buff *skb,
894 			     struct sk_buff_head *list)
895 {
896 	RING_IDX cons = queue->rx.rsp_cons;
897 	struct sk_buff *nskb;
898 
899 	while ((nskb = __skb_dequeue(list))) {
900 		struct xen_netif_rx_response *rx =
901 			RING_GET_RESPONSE(&queue->rx, ++cons);
902 		skb_frag_t *nfrag = &skb_shinfo(nskb)->frags[0];
903 
904 		if (skb_shinfo(skb)->nr_frags == MAX_SKB_FRAGS) {
905 			unsigned int pull_to = NETFRONT_SKB_CB(skb)->pull_to;
906 
907 			BUG_ON(pull_to < skb_headlen(skb));
908 			__pskb_pull_tail(skb, pull_to - skb_headlen(skb));
909 		}
910 		if (unlikely(skb_shinfo(skb)->nr_frags >= MAX_SKB_FRAGS)) {
911 			queue->rx.rsp_cons = ++cons + skb_queue_len(list);
912 			kfree_skb(nskb);
913 			return -ENOENT;
914 		}
915 
916 		skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags,
917 				skb_frag_page(nfrag),
918 				rx->offset, rx->status, PAGE_SIZE);
919 
920 		skb_shinfo(nskb)->nr_frags = 0;
921 		kfree_skb(nskb);
922 	}
923 
924 	queue->rx.rsp_cons = cons;
925 
926 	return 0;
927 }
928 
929 static int checksum_setup(struct net_device *dev, struct sk_buff *skb)
930 {
931 	bool recalculate_partial_csum = false;
932 
933 	/*
934 	 * A GSO SKB must be CHECKSUM_PARTIAL. However some buggy
935 	 * peers can fail to set NETRXF_csum_blank when sending a GSO
936 	 * frame. In this case force the SKB to CHECKSUM_PARTIAL and
937 	 * recalculate the partial checksum.
938 	 */
939 	if (skb->ip_summed != CHECKSUM_PARTIAL && skb_is_gso(skb)) {
940 		struct netfront_info *np = netdev_priv(dev);
941 		atomic_inc(&np->rx_gso_checksum_fixup);
942 		skb->ip_summed = CHECKSUM_PARTIAL;
943 		recalculate_partial_csum = true;
944 	}
945 
946 	/* A non-CHECKSUM_PARTIAL SKB does not require setup. */
947 	if (skb->ip_summed != CHECKSUM_PARTIAL)
948 		return 0;
949 
950 	return skb_checksum_setup(skb, recalculate_partial_csum);
951 }
952 
953 static int handle_incoming_queue(struct netfront_queue *queue,
954 				 struct sk_buff_head *rxq)
955 {
956 	struct netfront_stats *rx_stats = this_cpu_ptr(queue->info->rx_stats);
957 	int packets_dropped = 0;
958 	struct sk_buff *skb;
959 
960 	while ((skb = __skb_dequeue(rxq)) != NULL) {
961 		int pull_to = NETFRONT_SKB_CB(skb)->pull_to;
962 
963 		if (pull_to > skb_headlen(skb))
964 			__pskb_pull_tail(skb, pull_to - skb_headlen(skb));
965 
966 		/* Ethernet work: Delayed to here as it peeks the header. */
967 		skb->protocol = eth_type_trans(skb, queue->info->netdev);
968 		skb_reset_network_header(skb);
969 
970 		if (checksum_setup(queue->info->netdev, skb)) {
971 			kfree_skb(skb);
972 			packets_dropped++;
973 			queue->info->netdev->stats.rx_errors++;
974 			continue;
975 		}
976 
977 		u64_stats_update_begin(&rx_stats->syncp);
978 		rx_stats->packets++;
979 		rx_stats->bytes += skb->len;
980 		u64_stats_update_end(&rx_stats->syncp);
981 
982 		/* Pass it up. */
983 		napi_gro_receive(&queue->napi, skb);
984 	}
985 
986 	return packets_dropped;
987 }
988 
989 static int xennet_poll(struct napi_struct *napi, int budget)
990 {
991 	struct netfront_queue *queue = container_of(napi, struct netfront_queue, napi);
992 	struct net_device *dev = queue->info->netdev;
993 	struct sk_buff *skb;
994 	struct netfront_rx_info rinfo;
995 	struct xen_netif_rx_response *rx = &rinfo.rx;
996 	struct xen_netif_extra_info *extras = rinfo.extras;
997 	RING_IDX i, rp;
998 	int work_done;
999 	struct sk_buff_head rxq;
1000 	struct sk_buff_head errq;
1001 	struct sk_buff_head tmpq;
1002 	int err;
1003 
1004 	spin_lock(&queue->rx_lock);
1005 
1006 	skb_queue_head_init(&rxq);
1007 	skb_queue_head_init(&errq);
1008 	skb_queue_head_init(&tmpq);
1009 
1010 	rp = queue->rx.sring->rsp_prod;
1011 	rmb(); /* Ensure we see queued responses up to 'rp'. */
1012 
1013 	i = queue->rx.rsp_cons;
1014 	work_done = 0;
1015 	while ((i != rp) && (work_done < budget)) {
1016 		memcpy(rx, RING_GET_RESPONSE(&queue->rx, i), sizeof(*rx));
1017 		memset(extras, 0, sizeof(rinfo.extras));
1018 
1019 		err = xennet_get_responses(queue, &rinfo, rp, &tmpq);
1020 
1021 		if (unlikely(err)) {
1022 err:
1023 			while ((skb = __skb_dequeue(&tmpq)))
1024 				__skb_queue_tail(&errq, skb);
1025 			dev->stats.rx_errors++;
1026 			i = queue->rx.rsp_cons;
1027 			continue;
1028 		}
1029 
1030 		skb = __skb_dequeue(&tmpq);
1031 
1032 		if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
1033 			struct xen_netif_extra_info *gso;
1034 			gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
1035 
1036 			if (unlikely(xennet_set_skb_gso(skb, gso))) {
1037 				__skb_queue_head(&tmpq, skb);
1038 				queue->rx.rsp_cons += skb_queue_len(&tmpq);
1039 				goto err;
1040 			}
1041 		}
1042 
1043 		NETFRONT_SKB_CB(skb)->pull_to = rx->status;
1044 		if (NETFRONT_SKB_CB(skb)->pull_to > RX_COPY_THRESHOLD)
1045 			NETFRONT_SKB_CB(skb)->pull_to = RX_COPY_THRESHOLD;
1046 
1047 		skb_frag_off_set(&skb_shinfo(skb)->frags[0], rx->offset);
1048 		skb_frag_size_set(&skb_shinfo(skb)->frags[0], rx->status);
1049 		skb->data_len = rx->status;
1050 		skb->len += rx->status;
1051 
1052 		if (unlikely(xennet_fill_frags(queue, skb, &tmpq)))
1053 			goto err;
1054 
1055 		if (rx->flags & XEN_NETRXF_csum_blank)
1056 			skb->ip_summed = CHECKSUM_PARTIAL;
1057 		else if (rx->flags & XEN_NETRXF_data_validated)
1058 			skb->ip_summed = CHECKSUM_UNNECESSARY;
1059 
1060 		__skb_queue_tail(&rxq, skb);
1061 
1062 		i = ++queue->rx.rsp_cons;
1063 		work_done++;
1064 	}
1065 
1066 	__skb_queue_purge(&errq);
1067 
1068 	work_done -= handle_incoming_queue(queue, &rxq);
1069 
1070 	xennet_alloc_rx_buffers(queue);
1071 
1072 	if (work_done < budget) {
1073 		int more_to_do = 0;
1074 
1075 		napi_complete_done(napi, work_done);
1076 
1077 		RING_FINAL_CHECK_FOR_RESPONSES(&queue->rx, more_to_do);
1078 		if (more_to_do)
1079 			napi_schedule(napi);
1080 	}
1081 
1082 	spin_unlock(&queue->rx_lock);
1083 
1084 	return work_done;
1085 }
1086 
1087 static int xennet_change_mtu(struct net_device *dev, int mtu)
1088 {
1089 	int max = xennet_can_sg(dev) ? XEN_NETIF_MAX_TX_SIZE : ETH_DATA_LEN;
1090 
1091 	if (mtu > max)
1092 		return -EINVAL;
1093 	dev->mtu = mtu;
1094 	return 0;
1095 }
1096 
1097 static void xennet_get_stats64(struct net_device *dev,
1098 			       struct rtnl_link_stats64 *tot)
1099 {
1100 	struct netfront_info *np = netdev_priv(dev);
1101 	int cpu;
1102 
1103 	for_each_possible_cpu(cpu) {
1104 		struct netfront_stats *rx_stats = per_cpu_ptr(np->rx_stats, cpu);
1105 		struct netfront_stats *tx_stats = per_cpu_ptr(np->tx_stats, cpu);
1106 		u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
1107 		unsigned int start;
1108 
1109 		do {
1110 			start = u64_stats_fetch_begin_irq(&tx_stats->syncp);
1111 			tx_packets = tx_stats->packets;
1112 			tx_bytes = tx_stats->bytes;
1113 		} while (u64_stats_fetch_retry_irq(&tx_stats->syncp, start));
1114 
1115 		do {
1116 			start = u64_stats_fetch_begin_irq(&rx_stats->syncp);
1117 			rx_packets = rx_stats->packets;
1118 			rx_bytes = rx_stats->bytes;
1119 		} while (u64_stats_fetch_retry_irq(&rx_stats->syncp, start));
1120 
1121 		tot->rx_packets += rx_packets;
1122 		tot->tx_packets += tx_packets;
1123 		tot->rx_bytes   += rx_bytes;
1124 		tot->tx_bytes   += tx_bytes;
1125 	}
1126 
1127 	tot->rx_errors  = dev->stats.rx_errors;
1128 	tot->tx_dropped = dev->stats.tx_dropped;
1129 }
1130 
1131 static void xennet_release_tx_bufs(struct netfront_queue *queue)
1132 {
1133 	struct sk_buff *skb;
1134 	int i;
1135 
1136 	for (i = 0; i < NET_TX_RING_SIZE; i++) {
1137 		/* Skip over entries which are actually freelist references */
1138 		if (skb_entry_is_link(&queue->tx_skbs[i]))
1139 			continue;
1140 
1141 		skb = queue->tx_skbs[i].skb;
1142 		get_page(queue->grant_tx_page[i]);
1143 		gnttab_end_foreign_access(queue->grant_tx_ref[i],
1144 					  GNTMAP_readonly,
1145 					  (unsigned long)page_address(queue->grant_tx_page[i]));
1146 		queue->grant_tx_page[i] = NULL;
1147 		queue->grant_tx_ref[i] = GRANT_INVALID_REF;
1148 		add_id_to_freelist(&queue->tx_skb_freelist, queue->tx_skbs, i);
1149 		dev_kfree_skb_irq(skb);
1150 	}
1151 }
1152 
1153 static void xennet_release_rx_bufs(struct netfront_queue *queue)
1154 {
1155 	int id, ref;
1156 
1157 	spin_lock_bh(&queue->rx_lock);
1158 
1159 	for (id = 0; id < NET_RX_RING_SIZE; id++) {
1160 		struct sk_buff *skb;
1161 		struct page *page;
1162 
1163 		skb = queue->rx_skbs[id];
1164 		if (!skb)
1165 			continue;
1166 
1167 		ref = queue->grant_rx_ref[id];
1168 		if (ref == GRANT_INVALID_REF)
1169 			continue;
1170 
1171 		page = skb_frag_page(&skb_shinfo(skb)->frags[0]);
1172 
1173 		/* gnttab_end_foreign_access() needs a page ref until
1174 		 * foreign access is ended (which may be deferred).
1175 		 */
1176 		get_page(page);
1177 		gnttab_end_foreign_access(ref, 0,
1178 					  (unsigned long)page_address(page));
1179 		queue->grant_rx_ref[id] = GRANT_INVALID_REF;
1180 
1181 		kfree_skb(skb);
1182 	}
1183 
1184 	spin_unlock_bh(&queue->rx_lock);
1185 }
1186 
1187 static netdev_features_t xennet_fix_features(struct net_device *dev,
1188 	netdev_features_t features)
1189 {
1190 	struct netfront_info *np = netdev_priv(dev);
1191 
1192 	if (features & NETIF_F_SG &&
1193 	    !xenbus_read_unsigned(np->xbdev->otherend, "feature-sg", 0))
1194 		features &= ~NETIF_F_SG;
1195 
1196 	if (features & NETIF_F_IPV6_CSUM &&
1197 	    !xenbus_read_unsigned(np->xbdev->otherend,
1198 				  "feature-ipv6-csum-offload", 0))
1199 		features &= ~NETIF_F_IPV6_CSUM;
1200 
1201 	if (features & NETIF_F_TSO &&
1202 	    !xenbus_read_unsigned(np->xbdev->otherend, "feature-gso-tcpv4", 0))
1203 		features &= ~NETIF_F_TSO;
1204 
1205 	if (features & NETIF_F_TSO6 &&
1206 	    !xenbus_read_unsigned(np->xbdev->otherend, "feature-gso-tcpv6", 0))
1207 		features &= ~NETIF_F_TSO6;
1208 
1209 	return features;
1210 }
1211 
1212 static int xennet_set_features(struct net_device *dev,
1213 	netdev_features_t features)
1214 {
1215 	if (!(features & NETIF_F_SG) && dev->mtu > ETH_DATA_LEN) {
1216 		netdev_info(dev, "Reducing MTU because no SG offload");
1217 		dev->mtu = ETH_DATA_LEN;
1218 	}
1219 
1220 	return 0;
1221 }
1222 
1223 static irqreturn_t xennet_tx_interrupt(int irq, void *dev_id)
1224 {
1225 	struct netfront_queue *queue = dev_id;
1226 	unsigned long flags;
1227 
1228 	spin_lock_irqsave(&queue->tx_lock, flags);
1229 	xennet_tx_buf_gc(queue);
1230 	spin_unlock_irqrestore(&queue->tx_lock, flags);
1231 
1232 	return IRQ_HANDLED;
1233 }
1234 
1235 static irqreturn_t xennet_rx_interrupt(int irq, void *dev_id)
1236 {
1237 	struct netfront_queue *queue = dev_id;
1238 	struct net_device *dev = queue->info->netdev;
1239 
1240 	if (likely(netif_carrier_ok(dev) &&
1241 		   RING_HAS_UNCONSUMED_RESPONSES(&queue->rx)))
1242 		napi_schedule(&queue->napi);
1243 
1244 	return IRQ_HANDLED;
1245 }
1246 
1247 static irqreturn_t xennet_interrupt(int irq, void *dev_id)
1248 {
1249 	xennet_tx_interrupt(irq, dev_id);
1250 	xennet_rx_interrupt(irq, dev_id);
1251 	return IRQ_HANDLED;
1252 }
1253 
1254 #ifdef CONFIG_NET_POLL_CONTROLLER
1255 static void xennet_poll_controller(struct net_device *dev)
1256 {
1257 	/* Poll each queue */
1258 	struct netfront_info *info = netdev_priv(dev);
1259 	unsigned int num_queues = dev->real_num_tx_queues;
1260 	unsigned int i;
1261 	for (i = 0; i < num_queues; ++i)
1262 		xennet_interrupt(0, &info->queues[i]);
1263 }
1264 #endif
1265 
1266 static const struct net_device_ops xennet_netdev_ops = {
1267 	.ndo_open            = xennet_open,
1268 	.ndo_stop            = xennet_close,
1269 	.ndo_start_xmit      = xennet_start_xmit,
1270 	.ndo_change_mtu	     = xennet_change_mtu,
1271 	.ndo_get_stats64     = xennet_get_stats64,
1272 	.ndo_set_mac_address = eth_mac_addr,
1273 	.ndo_validate_addr   = eth_validate_addr,
1274 	.ndo_fix_features    = xennet_fix_features,
1275 	.ndo_set_features    = xennet_set_features,
1276 	.ndo_select_queue    = xennet_select_queue,
1277 #ifdef CONFIG_NET_POLL_CONTROLLER
1278 	.ndo_poll_controller = xennet_poll_controller,
1279 #endif
1280 };
1281 
1282 static void xennet_free_netdev(struct net_device *netdev)
1283 {
1284 	struct netfront_info *np = netdev_priv(netdev);
1285 
1286 	free_percpu(np->rx_stats);
1287 	free_percpu(np->tx_stats);
1288 	free_netdev(netdev);
1289 }
1290 
1291 static struct net_device *xennet_create_dev(struct xenbus_device *dev)
1292 {
1293 	int err;
1294 	struct net_device *netdev;
1295 	struct netfront_info *np;
1296 
1297 	netdev = alloc_etherdev_mq(sizeof(struct netfront_info), xennet_max_queues);
1298 	if (!netdev)
1299 		return ERR_PTR(-ENOMEM);
1300 
1301 	np                   = netdev_priv(netdev);
1302 	np->xbdev            = dev;
1303 
1304 	np->queues = NULL;
1305 
1306 	err = -ENOMEM;
1307 	np->rx_stats = netdev_alloc_pcpu_stats(struct netfront_stats);
1308 	if (np->rx_stats == NULL)
1309 		goto exit;
1310 	np->tx_stats = netdev_alloc_pcpu_stats(struct netfront_stats);
1311 	if (np->tx_stats == NULL)
1312 		goto exit;
1313 
1314 	netdev->netdev_ops	= &xennet_netdev_ops;
1315 
1316 	netdev->features        = NETIF_F_IP_CSUM | NETIF_F_RXCSUM |
1317 				  NETIF_F_GSO_ROBUST;
1318 	netdev->hw_features	= NETIF_F_SG |
1319 				  NETIF_F_IPV6_CSUM |
1320 				  NETIF_F_TSO | NETIF_F_TSO6;
1321 
1322 	/*
1323          * Assume that all hw features are available for now. This set
1324          * will be adjusted by the call to netdev_update_features() in
1325          * xennet_connect() which is the earliest point where we can
1326          * negotiate with the backend regarding supported features.
1327          */
1328 	netdev->features |= netdev->hw_features;
1329 
1330 	netdev->ethtool_ops = &xennet_ethtool_ops;
1331 	netdev->min_mtu = ETH_MIN_MTU;
1332 	netdev->max_mtu = XEN_NETIF_MAX_TX_SIZE;
1333 	SET_NETDEV_DEV(netdev, &dev->dev);
1334 
1335 	np->netdev = netdev;
1336 
1337 	netif_carrier_off(netdev);
1338 
1339 	do {
1340 		xenbus_switch_state(dev, XenbusStateInitialising);
1341 		err = wait_event_timeout(module_wq,
1342 				 xenbus_read_driver_state(dev->otherend) !=
1343 				 XenbusStateClosed &&
1344 				 xenbus_read_driver_state(dev->otherend) !=
1345 				 XenbusStateUnknown, XENNET_TIMEOUT);
1346 	} while (!err);
1347 
1348 	return netdev;
1349 
1350  exit:
1351 	xennet_free_netdev(netdev);
1352 	return ERR_PTR(err);
1353 }
1354 
1355 /**
1356  * Entry point to this code when a new device is created.  Allocate the basic
1357  * structures and the ring buffers for communication with the backend, and
1358  * inform the backend of the appropriate details for those.
1359  */
1360 static int netfront_probe(struct xenbus_device *dev,
1361 			  const struct xenbus_device_id *id)
1362 {
1363 	int err;
1364 	struct net_device *netdev;
1365 	struct netfront_info *info;
1366 
1367 	netdev = xennet_create_dev(dev);
1368 	if (IS_ERR(netdev)) {
1369 		err = PTR_ERR(netdev);
1370 		xenbus_dev_fatal(dev, err, "creating netdev");
1371 		return err;
1372 	}
1373 
1374 	info = netdev_priv(netdev);
1375 	dev_set_drvdata(&dev->dev, info);
1376 #ifdef CONFIG_SYSFS
1377 	info->netdev->sysfs_groups[0] = &xennet_dev_group;
1378 #endif
1379 
1380 	return 0;
1381 }
1382 
1383 static void xennet_end_access(int ref, void *page)
1384 {
1385 	/* This frees the page as a side-effect */
1386 	if (ref != GRANT_INVALID_REF)
1387 		gnttab_end_foreign_access(ref, 0, (unsigned long)page);
1388 }
1389 
1390 static void xennet_disconnect_backend(struct netfront_info *info)
1391 {
1392 	unsigned int i = 0;
1393 	unsigned int num_queues = info->netdev->real_num_tx_queues;
1394 
1395 	netif_carrier_off(info->netdev);
1396 
1397 	for (i = 0; i < num_queues && info->queues; ++i) {
1398 		struct netfront_queue *queue = &info->queues[i];
1399 
1400 		del_timer_sync(&queue->rx_refill_timer);
1401 
1402 		if (queue->tx_irq && (queue->tx_irq == queue->rx_irq))
1403 			unbind_from_irqhandler(queue->tx_irq, queue);
1404 		if (queue->tx_irq && (queue->tx_irq != queue->rx_irq)) {
1405 			unbind_from_irqhandler(queue->tx_irq, queue);
1406 			unbind_from_irqhandler(queue->rx_irq, queue);
1407 		}
1408 		queue->tx_evtchn = queue->rx_evtchn = 0;
1409 		queue->tx_irq = queue->rx_irq = 0;
1410 
1411 		if (netif_running(info->netdev))
1412 			napi_synchronize(&queue->napi);
1413 
1414 		xennet_release_tx_bufs(queue);
1415 		xennet_release_rx_bufs(queue);
1416 		gnttab_free_grant_references(queue->gref_tx_head);
1417 		gnttab_free_grant_references(queue->gref_rx_head);
1418 
1419 		/* End access and free the pages */
1420 		xennet_end_access(queue->tx_ring_ref, queue->tx.sring);
1421 		xennet_end_access(queue->rx_ring_ref, queue->rx.sring);
1422 
1423 		queue->tx_ring_ref = GRANT_INVALID_REF;
1424 		queue->rx_ring_ref = GRANT_INVALID_REF;
1425 		queue->tx.sring = NULL;
1426 		queue->rx.sring = NULL;
1427 	}
1428 }
1429 
1430 /**
1431  * We are reconnecting to the backend, due to a suspend/resume, or a backend
1432  * driver restart.  We tear down our netif structure and recreate it, but
1433  * leave the device-layer structures intact so that this is transparent to the
1434  * rest of the kernel.
1435  */
1436 static int netfront_resume(struct xenbus_device *dev)
1437 {
1438 	struct netfront_info *info = dev_get_drvdata(&dev->dev);
1439 
1440 	dev_dbg(&dev->dev, "%s\n", dev->nodename);
1441 
1442 	xennet_disconnect_backend(info);
1443 	return 0;
1444 }
1445 
1446 static int xen_net_read_mac(struct xenbus_device *dev, u8 mac[])
1447 {
1448 	char *s, *e, *macstr;
1449 	int i;
1450 
1451 	macstr = s = xenbus_read(XBT_NIL, dev->nodename, "mac", NULL);
1452 	if (IS_ERR(macstr))
1453 		return PTR_ERR(macstr);
1454 
1455 	for (i = 0; i < ETH_ALEN; i++) {
1456 		mac[i] = simple_strtoul(s, &e, 16);
1457 		if ((s == e) || (*e != ((i == ETH_ALEN-1) ? '\0' : ':'))) {
1458 			kfree(macstr);
1459 			return -ENOENT;
1460 		}
1461 		s = e+1;
1462 	}
1463 
1464 	kfree(macstr);
1465 	return 0;
1466 }
1467 
1468 static int setup_netfront_single(struct netfront_queue *queue)
1469 {
1470 	int err;
1471 
1472 	err = xenbus_alloc_evtchn(queue->info->xbdev, &queue->tx_evtchn);
1473 	if (err < 0)
1474 		goto fail;
1475 
1476 	err = bind_evtchn_to_irqhandler(queue->tx_evtchn,
1477 					xennet_interrupt,
1478 					0, queue->info->netdev->name, queue);
1479 	if (err < 0)
1480 		goto bind_fail;
1481 	queue->rx_evtchn = queue->tx_evtchn;
1482 	queue->rx_irq = queue->tx_irq = err;
1483 
1484 	return 0;
1485 
1486 bind_fail:
1487 	xenbus_free_evtchn(queue->info->xbdev, queue->tx_evtchn);
1488 	queue->tx_evtchn = 0;
1489 fail:
1490 	return err;
1491 }
1492 
1493 static int setup_netfront_split(struct netfront_queue *queue)
1494 {
1495 	int err;
1496 
1497 	err = xenbus_alloc_evtchn(queue->info->xbdev, &queue->tx_evtchn);
1498 	if (err < 0)
1499 		goto fail;
1500 	err = xenbus_alloc_evtchn(queue->info->xbdev, &queue->rx_evtchn);
1501 	if (err < 0)
1502 		goto alloc_rx_evtchn_fail;
1503 
1504 	snprintf(queue->tx_irq_name, sizeof(queue->tx_irq_name),
1505 		 "%s-tx", queue->name);
1506 	err = bind_evtchn_to_irqhandler(queue->tx_evtchn,
1507 					xennet_tx_interrupt,
1508 					0, queue->tx_irq_name, queue);
1509 	if (err < 0)
1510 		goto bind_tx_fail;
1511 	queue->tx_irq = err;
1512 
1513 	snprintf(queue->rx_irq_name, sizeof(queue->rx_irq_name),
1514 		 "%s-rx", queue->name);
1515 	err = bind_evtchn_to_irqhandler(queue->rx_evtchn,
1516 					xennet_rx_interrupt,
1517 					0, queue->rx_irq_name, queue);
1518 	if (err < 0)
1519 		goto bind_rx_fail;
1520 	queue->rx_irq = err;
1521 
1522 	return 0;
1523 
1524 bind_rx_fail:
1525 	unbind_from_irqhandler(queue->tx_irq, queue);
1526 	queue->tx_irq = 0;
1527 bind_tx_fail:
1528 	xenbus_free_evtchn(queue->info->xbdev, queue->rx_evtchn);
1529 	queue->rx_evtchn = 0;
1530 alloc_rx_evtchn_fail:
1531 	xenbus_free_evtchn(queue->info->xbdev, queue->tx_evtchn);
1532 	queue->tx_evtchn = 0;
1533 fail:
1534 	return err;
1535 }
1536 
1537 static int setup_netfront(struct xenbus_device *dev,
1538 			struct netfront_queue *queue, unsigned int feature_split_evtchn)
1539 {
1540 	struct xen_netif_tx_sring *txs;
1541 	struct xen_netif_rx_sring *rxs;
1542 	grant_ref_t gref;
1543 	int err;
1544 
1545 	queue->tx_ring_ref = GRANT_INVALID_REF;
1546 	queue->rx_ring_ref = GRANT_INVALID_REF;
1547 	queue->rx.sring = NULL;
1548 	queue->tx.sring = NULL;
1549 
1550 	txs = (struct xen_netif_tx_sring *)get_zeroed_page(GFP_NOIO | __GFP_HIGH);
1551 	if (!txs) {
1552 		err = -ENOMEM;
1553 		xenbus_dev_fatal(dev, err, "allocating tx ring page");
1554 		goto fail;
1555 	}
1556 	SHARED_RING_INIT(txs);
1557 	FRONT_RING_INIT(&queue->tx, txs, XEN_PAGE_SIZE);
1558 
1559 	err = xenbus_grant_ring(dev, txs, 1, &gref);
1560 	if (err < 0)
1561 		goto grant_tx_ring_fail;
1562 	queue->tx_ring_ref = gref;
1563 
1564 	rxs = (struct xen_netif_rx_sring *)get_zeroed_page(GFP_NOIO | __GFP_HIGH);
1565 	if (!rxs) {
1566 		err = -ENOMEM;
1567 		xenbus_dev_fatal(dev, err, "allocating rx ring page");
1568 		goto alloc_rx_ring_fail;
1569 	}
1570 	SHARED_RING_INIT(rxs);
1571 	FRONT_RING_INIT(&queue->rx, rxs, XEN_PAGE_SIZE);
1572 
1573 	err = xenbus_grant_ring(dev, rxs, 1, &gref);
1574 	if (err < 0)
1575 		goto grant_rx_ring_fail;
1576 	queue->rx_ring_ref = gref;
1577 
1578 	if (feature_split_evtchn)
1579 		err = setup_netfront_split(queue);
1580 	/* setup single event channel if
1581 	 *  a) feature-split-event-channels == 0
1582 	 *  b) feature-split-event-channels == 1 but failed to setup
1583 	 */
1584 	if (!feature_split_evtchn || (feature_split_evtchn && err))
1585 		err = setup_netfront_single(queue);
1586 
1587 	if (err)
1588 		goto alloc_evtchn_fail;
1589 
1590 	return 0;
1591 
1592 	/* If we fail to setup netfront, it is safe to just revoke access to
1593 	 * granted pages because backend is not accessing it at this point.
1594 	 */
1595 alloc_evtchn_fail:
1596 	gnttab_end_foreign_access_ref(queue->rx_ring_ref, 0);
1597 grant_rx_ring_fail:
1598 	free_page((unsigned long)rxs);
1599 alloc_rx_ring_fail:
1600 	gnttab_end_foreign_access_ref(queue->tx_ring_ref, 0);
1601 grant_tx_ring_fail:
1602 	free_page((unsigned long)txs);
1603 fail:
1604 	return err;
1605 }
1606 
1607 /* Queue-specific initialisation
1608  * This used to be done in xennet_create_dev() but must now
1609  * be run per-queue.
1610  */
1611 static int xennet_init_queue(struct netfront_queue *queue)
1612 {
1613 	unsigned short i;
1614 	int err = 0;
1615 	char *devid;
1616 
1617 	spin_lock_init(&queue->tx_lock);
1618 	spin_lock_init(&queue->rx_lock);
1619 
1620 	timer_setup(&queue->rx_refill_timer, rx_refill_timeout, 0);
1621 
1622 	devid = strrchr(queue->info->xbdev->nodename, '/') + 1;
1623 	snprintf(queue->name, sizeof(queue->name), "vif%s-q%u",
1624 		 devid, queue->id);
1625 
1626 	/* Initialise tx_skbs as a free chain containing every entry. */
1627 	queue->tx_skb_freelist = 0;
1628 	for (i = 0; i < NET_TX_RING_SIZE; i++) {
1629 		skb_entry_set_link(&queue->tx_skbs[i], i+1);
1630 		queue->grant_tx_ref[i] = GRANT_INVALID_REF;
1631 		queue->grant_tx_page[i] = NULL;
1632 	}
1633 
1634 	/* Clear out rx_skbs */
1635 	for (i = 0; i < NET_RX_RING_SIZE; i++) {
1636 		queue->rx_skbs[i] = NULL;
1637 		queue->grant_rx_ref[i] = GRANT_INVALID_REF;
1638 	}
1639 
1640 	/* A grant for every tx ring slot */
1641 	if (gnttab_alloc_grant_references(NET_TX_RING_SIZE,
1642 					  &queue->gref_tx_head) < 0) {
1643 		pr_alert("can't alloc tx grant refs\n");
1644 		err = -ENOMEM;
1645 		goto exit;
1646 	}
1647 
1648 	/* A grant for every rx ring slot */
1649 	if (gnttab_alloc_grant_references(NET_RX_RING_SIZE,
1650 					  &queue->gref_rx_head) < 0) {
1651 		pr_alert("can't alloc rx grant refs\n");
1652 		err = -ENOMEM;
1653 		goto exit_free_tx;
1654 	}
1655 
1656 	return 0;
1657 
1658  exit_free_tx:
1659 	gnttab_free_grant_references(queue->gref_tx_head);
1660  exit:
1661 	return err;
1662 }
1663 
1664 static int write_queue_xenstore_keys(struct netfront_queue *queue,
1665 			   struct xenbus_transaction *xbt, int write_hierarchical)
1666 {
1667 	/* Write the queue-specific keys into XenStore in the traditional
1668 	 * way for a single queue, or in a queue subkeys for multiple
1669 	 * queues.
1670 	 */
1671 	struct xenbus_device *dev = queue->info->xbdev;
1672 	int err;
1673 	const char *message;
1674 	char *path;
1675 	size_t pathsize;
1676 
1677 	/* Choose the correct place to write the keys */
1678 	if (write_hierarchical) {
1679 		pathsize = strlen(dev->nodename) + 10;
1680 		path = kzalloc(pathsize, GFP_KERNEL);
1681 		if (!path) {
1682 			err = -ENOMEM;
1683 			message = "out of memory while writing ring references";
1684 			goto error;
1685 		}
1686 		snprintf(path, pathsize, "%s/queue-%u",
1687 				dev->nodename, queue->id);
1688 	} else {
1689 		path = (char *)dev->nodename;
1690 	}
1691 
1692 	/* Write ring references */
1693 	err = xenbus_printf(*xbt, path, "tx-ring-ref", "%u",
1694 			queue->tx_ring_ref);
1695 	if (err) {
1696 		message = "writing tx-ring-ref";
1697 		goto error;
1698 	}
1699 
1700 	err = xenbus_printf(*xbt, path, "rx-ring-ref", "%u",
1701 			queue->rx_ring_ref);
1702 	if (err) {
1703 		message = "writing rx-ring-ref";
1704 		goto error;
1705 	}
1706 
1707 	/* Write event channels; taking into account both shared
1708 	 * and split event channel scenarios.
1709 	 */
1710 	if (queue->tx_evtchn == queue->rx_evtchn) {
1711 		/* Shared event channel */
1712 		err = xenbus_printf(*xbt, path,
1713 				"event-channel", "%u", queue->tx_evtchn);
1714 		if (err) {
1715 			message = "writing event-channel";
1716 			goto error;
1717 		}
1718 	} else {
1719 		/* Split event channels */
1720 		err = xenbus_printf(*xbt, path,
1721 				"event-channel-tx", "%u", queue->tx_evtchn);
1722 		if (err) {
1723 			message = "writing event-channel-tx";
1724 			goto error;
1725 		}
1726 
1727 		err = xenbus_printf(*xbt, path,
1728 				"event-channel-rx", "%u", queue->rx_evtchn);
1729 		if (err) {
1730 			message = "writing event-channel-rx";
1731 			goto error;
1732 		}
1733 	}
1734 
1735 	if (write_hierarchical)
1736 		kfree(path);
1737 	return 0;
1738 
1739 error:
1740 	if (write_hierarchical)
1741 		kfree(path);
1742 	xenbus_dev_fatal(dev, err, "%s", message);
1743 	return err;
1744 }
1745 
1746 static void xennet_destroy_queues(struct netfront_info *info)
1747 {
1748 	unsigned int i;
1749 
1750 	for (i = 0; i < info->netdev->real_num_tx_queues; i++) {
1751 		struct netfront_queue *queue = &info->queues[i];
1752 
1753 		if (netif_running(info->netdev))
1754 			napi_disable(&queue->napi);
1755 		netif_napi_del(&queue->napi);
1756 	}
1757 
1758 	kfree(info->queues);
1759 	info->queues = NULL;
1760 }
1761 
1762 static int xennet_create_queues(struct netfront_info *info,
1763 				unsigned int *num_queues)
1764 {
1765 	unsigned int i;
1766 	int ret;
1767 
1768 	info->queues = kcalloc(*num_queues, sizeof(struct netfront_queue),
1769 			       GFP_KERNEL);
1770 	if (!info->queues)
1771 		return -ENOMEM;
1772 
1773 	for (i = 0; i < *num_queues; i++) {
1774 		struct netfront_queue *queue = &info->queues[i];
1775 
1776 		queue->id = i;
1777 		queue->info = info;
1778 
1779 		ret = xennet_init_queue(queue);
1780 		if (ret < 0) {
1781 			dev_warn(&info->xbdev->dev,
1782 				 "only created %d queues\n", i);
1783 			*num_queues = i;
1784 			break;
1785 		}
1786 
1787 		netif_napi_add(queue->info->netdev, &queue->napi,
1788 			       xennet_poll, 64);
1789 		if (netif_running(info->netdev))
1790 			napi_enable(&queue->napi);
1791 	}
1792 
1793 	netif_set_real_num_tx_queues(info->netdev, *num_queues);
1794 
1795 	if (*num_queues == 0) {
1796 		dev_err(&info->xbdev->dev, "no queues\n");
1797 		return -EINVAL;
1798 	}
1799 	return 0;
1800 }
1801 
1802 /* Common code used when first setting up, and when resuming. */
1803 static int talk_to_netback(struct xenbus_device *dev,
1804 			   struct netfront_info *info)
1805 {
1806 	const char *message;
1807 	struct xenbus_transaction xbt;
1808 	int err;
1809 	unsigned int feature_split_evtchn;
1810 	unsigned int i = 0;
1811 	unsigned int max_queues = 0;
1812 	struct netfront_queue *queue = NULL;
1813 	unsigned int num_queues = 1;
1814 
1815 	info->netdev->irq = 0;
1816 
1817 	/* Check if backend supports multiple queues */
1818 	max_queues = xenbus_read_unsigned(info->xbdev->otherend,
1819 					  "multi-queue-max-queues", 1);
1820 	num_queues = min(max_queues, xennet_max_queues);
1821 
1822 	/* Check feature-split-event-channels */
1823 	feature_split_evtchn = xenbus_read_unsigned(info->xbdev->otherend,
1824 					"feature-split-event-channels", 0);
1825 
1826 	/* Read mac addr. */
1827 	err = xen_net_read_mac(dev, info->netdev->dev_addr);
1828 	if (err) {
1829 		xenbus_dev_fatal(dev, err, "parsing %s/mac", dev->nodename);
1830 		goto out_unlocked;
1831 	}
1832 
1833 	rtnl_lock();
1834 	if (info->queues)
1835 		xennet_destroy_queues(info);
1836 
1837 	err = xennet_create_queues(info, &num_queues);
1838 	if (err < 0) {
1839 		xenbus_dev_fatal(dev, err, "creating queues");
1840 		kfree(info->queues);
1841 		info->queues = NULL;
1842 		goto out;
1843 	}
1844 	rtnl_unlock();
1845 
1846 	/* Create shared ring, alloc event channel -- for each queue */
1847 	for (i = 0; i < num_queues; ++i) {
1848 		queue = &info->queues[i];
1849 		err = setup_netfront(dev, queue, feature_split_evtchn);
1850 		if (err)
1851 			goto destroy_ring;
1852 	}
1853 
1854 again:
1855 	err = xenbus_transaction_start(&xbt);
1856 	if (err) {
1857 		xenbus_dev_fatal(dev, err, "starting transaction");
1858 		goto destroy_ring;
1859 	}
1860 
1861 	if (xenbus_exists(XBT_NIL,
1862 			  info->xbdev->otherend, "multi-queue-max-queues")) {
1863 		/* Write the number of queues */
1864 		err = xenbus_printf(xbt, dev->nodename,
1865 				    "multi-queue-num-queues", "%u", num_queues);
1866 		if (err) {
1867 			message = "writing multi-queue-num-queues";
1868 			goto abort_transaction_no_dev_fatal;
1869 		}
1870 	}
1871 
1872 	if (num_queues == 1) {
1873 		err = write_queue_xenstore_keys(&info->queues[0], &xbt, 0); /* flat */
1874 		if (err)
1875 			goto abort_transaction_no_dev_fatal;
1876 	} else {
1877 		/* Write the keys for each queue */
1878 		for (i = 0; i < num_queues; ++i) {
1879 			queue = &info->queues[i];
1880 			err = write_queue_xenstore_keys(queue, &xbt, 1); /* hierarchical */
1881 			if (err)
1882 				goto abort_transaction_no_dev_fatal;
1883 		}
1884 	}
1885 
1886 	/* The remaining keys are not queue-specific */
1887 	err = xenbus_printf(xbt, dev->nodename, "request-rx-copy", "%u",
1888 			    1);
1889 	if (err) {
1890 		message = "writing request-rx-copy";
1891 		goto abort_transaction;
1892 	}
1893 
1894 	err = xenbus_printf(xbt, dev->nodename, "feature-rx-notify", "%d", 1);
1895 	if (err) {
1896 		message = "writing feature-rx-notify";
1897 		goto abort_transaction;
1898 	}
1899 
1900 	err = xenbus_printf(xbt, dev->nodename, "feature-sg", "%d", 1);
1901 	if (err) {
1902 		message = "writing feature-sg";
1903 		goto abort_transaction;
1904 	}
1905 
1906 	err = xenbus_printf(xbt, dev->nodename, "feature-gso-tcpv4", "%d", 1);
1907 	if (err) {
1908 		message = "writing feature-gso-tcpv4";
1909 		goto abort_transaction;
1910 	}
1911 
1912 	err = xenbus_write(xbt, dev->nodename, "feature-gso-tcpv6", "1");
1913 	if (err) {
1914 		message = "writing feature-gso-tcpv6";
1915 		goto abort_transaction;
1916 	}
1917 
1918 	err = xenbus_write(xbt, dev->nodename, "feature-ipv6-csum-offload",
1919 			   "1");
1920 	if (err) {
1921 		message = "writing feature-ipv6-csum-offload";
1922 		goto abort_transaction;
1923 	}
1924 
1925 	err = xenbus_transaction_end(xbt, 0);
1926 	if (err) {
1927 		if (err == -EAGAIN)
1928 			goto again;
1929 		xenbus_dev_fatal(dev, err, "completing transaction");
1930 		goto destroy_ring;
1931 	}
1932 
1933 	return 0;
1934 
1935  abort_transaction:
1936 	xenbus_dev_fatal(dev, err, "%s", message);
1937 abort_transaction_no_dev_fatal:
1938 	xenbus_transaction_end(xbt, 1);
1939  destroy_ring:
1940 	xennet_disconnect_backend(info);
1941 	rtnl_lock();
1942 	xennet_destroy_queues(info);
1943  out:
1944 	rtnl_unlock();
1945 out_unlocked:
1946 	device_unregister(&dev->dev);
1947 	return err;
1948 }
1949 
1950 static int xennet_connect(struct net_device *dev)
1951 {
1952 	struct netfront_info *np = netdev_priv(dev);
1953 	unsigned int num_queues = 0;
1954 	int err;
1955 	unsigned int j = 0;
1956 	struct netfront_queue *queue = NULL;
1957 
1958 	if (!xenbus_read_unsigned(np->xbdev->otherend, "feature-rx-copy", 0)) {
1959 		dev_info(&dev->dev,
1960 			 "backend does not support copying receive path\n");
1961 		return -ENODEV;
1962 	}
1963 
1964 	err = talk_to_netback(np->xbdev, np);
1965 	if (err)
1966 		return err;
1967 
1968 	/* talk_to_netback() sets the correct number of queues */
1969 	num_queues = dev->real_num_tx_queues;
1970 
1971 	if (dev->reg_state == NETREG_UNINITIALIZED) {
1972 		err = register_netdev(dev);
1973 		if (err) {
1974 			pr_warn("%s: register_netdev err=%d\n", __func__, err);
1975 			device_unregister(&np->xbdev->dev);
1976 			return err;
1977 		}
1978 	}
1979 
1980 	rtnl_lock();
1981 	netdev_update_features(dev);
1982 	rtnl_unlock();
1983 
1984 	/*
1985 	 * All public and private state should now be sane.  Get
1986 	 * ready to start sending and receiving packets and give the driver
1987 	 * domain a kick because we've probably just requeued some
1988 	 * packets.
1989 	 */
1990 	netif_carrier_on(np->netdev);
1991 	for (j = 0; j < num_queues; ++j) {
1992 		queue = &np->queues[j];
1993 
1994 		notify_remote_via_irq(queue->tx_irq);
1995 		if (queue->tx_irq != queue->rx_irq)
1996 			notify_remote_via_irq(queue->rx_irq);
1997 
1998 		spin_lock_irq(&queue->tx_lock);
1999 		xennet_tx_buf_gc(queue);
2000 		spin_unlock_irq(&queue->tx_lock);
2001 
2002 		spin_lock_bh(&queue->rx_lock);
2003 		xennet_alloc_rx_buffers(queue);
2004 		spin_unlock_bh(&queue->rx_lock);
2005 	}
2006 
2007 	return 0;
2008 }
2009 
2010 /**
2011  * Callback received when the backend's state changes.
2012  */
2013 static void netback_changed(struct xenbus_device *dev,
2014 			    enum xenbus_state backend_state)
2015 {
2016 	struct netfront_info *np = dev_get_drvdata(&dev->dev);
2017 	struct net_device *netdev = np->netdev;
2018 
2019 	dev_dbg(&dev->dev, "%s\n", xenbus_strstate(backend_state));
2020 
2021 	wake_up_all(&module_wq);
2022 
2023 	switch (backend_state) {
2024 	case XenbusStateInitialising:
2025 	case XenbusStateInitialised:
2026 	case XenbusStateReconfiguring:
2027 	case XenbusStateReconfigured:
2028 	case XenbusStateUnknown:
2029 		break;
2030 
2031 	case XenbusStateInitWait:
2032 		if (dev->state != XenbusStateInitialising)
2033 			break;
2034 		if (xennet_connect(netdev) != 0)
2035 			break;
2036 		xenbus_switch_state(dev, XenbusStateConnected);
2037 		break;
2038 
2039 	case XenbusStateConnected:
2040 		netdev_notify_peers(netdev);
2041 		break;
2042 
2043 	case XenbusStateClosed:
2044 		if (dev->state == XenbusStateClosed)
2045 			break;
2046 		/* Fall through - Missed the backend's CLOSING state. */
2047 	case XenbusStateClosing:
2048 		xenbus_frontend_closed(dev);
2049 		break;
2050 	}
2051 }
2052 
2053 static const struct xennet_stat {
2054 	char name[ETH_GSTRING_LEN];
2055 	u16 offset;
2056 } xennet_stats[] = {
2057 	{
2058 		"rx_gso_checksum_fixup",
2059 		offsetof(struct netfront_info, rx_gso_checksum_fixup)
2060 	},
2061 };
2062 
2063 static int xennet_get_sset_count(struct net_device *dev, int string_set)
2064 {
2065 	switch (string_set) {
2066 	case ETH_SS_STATS:
2067 		return ARRAY_SIZE(xennet_stats);
2068 	default:
2069 		return -EINVAL;
2070 	}
2071 }
2072 
2073 static void xennet_get_ethtool_stats(struct net_device *dev,
2074 				     struct ethtool_stats *stats, u64 * data)
2075 {
2076 	void *np = netdev_priv(dev);
2077 	int i;
2078 
2079 	for (i = 0; i < ARRAY_SIZE(xennet_stats); i++)
2080 		data[i] = atomic_read((atomic_t *)(np + xennet_stats[i].offset));
2081 }
2082 
2083 static void xennet_get_strings(struct net_device *dev, u32 stringset, u8 * data)
2084 {
2085 	int i;
2086 
2087 	switch (stringset) {
2088 	case ETH_SS_STATS:
2089 		for (i = 0; i < ARRAY_SIZE(xennet_stats); i++)
2090 			memcpy(data + i * ETH_GSTRING_LEN,
2091 			       xennet_stats[i].name, ETH_GSTRING_LEN);
2092 		break;
2093 	}
2094 }
2095 
2096 static const struct ethtool_ops xennet_ethtool_ops =
2097 {
2098 	.get_link = ethtool_op_get_link,
2099 
2100 	.get_sset_count = xennet_get_sset_count,
2101 	.get_ethtool_stats = xennet_get_ethtool_stats,
2102 	.get_strings = xennet_get_strings,
2103 };
2104 
2105 #ifdef CONFIG_SYSFS
2106 static ssize_t show_rxbuf(struct device *dev,
2107 			  struct device_attribute *attr, char *buf)
2108 {
2109 	return sprintf(buf, "%lu\n", NET_RX_RING_SIZE);
2110 }
2111 
2112 static ssize_t store_rxbuf(struct device *dev,
2113 			   struct device_attribute *attr,
2114 			   const char *buf, size_t len)
2115 {
2116 	char *endp;
2117 	unsigned long target;
2118 
2119 	if (!capable(CAP_NET_ADMIN))
2120 		return -EPERM;
2121 
2122 	target = simple_strtoul(buf, &endp, 0);
2123 	if (endp == buf)
2124 		return -EBADMSG;
2125 
2126 	/* rxbuf_min and rxbuf_max are no longer configurable. */
2127 
2128 	return len;
2129 }
2130 
2131 static DEVICE_ATTR(rxbuf_min, 0644, show_rxbuf, store_rxbuf);
2132 static DEVICE_ATTR(rxbuf_max, 0644, show_rxbuf, store_rxbuf);
2133 static DEVICE_ATTR(rxbuf_cur, 0444, show_rxbuf, NULL);
2134 
2135 static struct attribute *xennet_dev_attrs[] = {
2136 	&dev_attr_rxbuf_min.attr,
2137 	&dev_attr_rxbuf_max.attr,
2138 	&dev_attr_rxbuf_cur.attr,
2139 	NULL
2140 };
2141 
2142 static const struct attribute_group xennet_dev_group = {
2143 	.attrs = xennet_dev_attrs
2144 };
2145 #endif /* CONFIG_SYSFS */
2146 
2147 static void xennet_bus_close(struct xenbus_device *dev)
2148 {
2149 	int ret;
2150 
2151 	if (xenbus_read_driver_state(dev->otherend) == XenbusStateClosed)
2152 		return;
2153 	do {
2154 		xenbus_switch_state(dev, XenbusStateClosing);
2155 		ret = wait_event_timeout(module_wq,
2156 				   xenbus_read_driver_state(dev->otherend) ==
2157 				   XenbusStateClosing ||
2158 				   xenbus_read_driver_state(dev->otherend) ==
2159 				   XenbusStateClosed ||
2160 				   xenbus_read_driver_state(dev->otherend) ==
2161 				   XenbusStateUnknown,
2162 				   XENNET_TIMEOUT);
2163 	} while (!ret);
2164 
2165 	if (xenbus_read_driver_state(dev->otherend) == XenbusStateClosed)
2166 		return;
2167 
2168 	do {
2169 		xenbus_switch_state(dev, XenbusStateClosed);
2170 		ret = wait_event_timeout(module_wq,
2171 				   xenbus_read_driver_state(dev->otherend) ==
2172 				   XenbusStateClosed ||
2173 				   xenbus_read_driver_state(dev->otherend) ==
2174 				   XenbusStateUnknown,
2175 				   XENNET_TIMEOUT);
2176 	} while (!ret);
2177 }
2178 
2179 static int xennet_remove(struct xenbus_device *dev)
2180 {
2181 	struct netfront_info *info = dev_get_drvdata(&dev->dev);
2182 
2183 	xennet_bus_close(dev);
2184 	xennet_disconnect_backend(info);
2185 
2186 	if (info->netdev->reg_state == NETREG_REGISTERED)
2187 		unregister_netdev(info->netdev);
2188 
2189 	if (info->queues) {
2190 		rtnl_lock();
2191 		xennet_destroy_queues(info);
2192 		rtnl_unlock();
2193 	}
2194 	xennet_free_netdev(info->netdev);
2195 
2196 	return 0;
2197 }
2198 
2199 static const struct xenbus_device_id netfront_ids[] = {
2200 	{ "vif" },
2201 	{ "" }
2202 };
2203 
2204 static struct xenbus_driver netfront_driver = {
2205 	.ids = netfront_ids,
2206 	.probe = netfront_probe,
2207 	.remove = xennet_remove,
2208 	.resume = netfront_resume,
2209 	.otherend_changed = netback_changed,
2210 };
2211 
2212 static int __init netif_init(void)
2213 {
2214 	if (!xen_domain())
2215 		return -ENODEV;
2216 
2217 	if (!xen_has_pv_nic_devices())
2218 		return -ENODEV;
2219 
2220 	pr_info("Initialising Xen virtual ethernet driver\n");
2221 
2222 	/* Allow as many queues as there are CPUs inut max. 8 if user has not
2223 	 * specified a value.
2224 	 */
2225 	if (xennet_max_queues == 0)
2226 		xennet_max_queues = min_t(unsigned int, MAX_QUEUES_DEFAULT,
2227 					  num_online_cpus());
2228 
2229 	return xenbus_register_frontend(&netfront_driver);
2230 }
2231 module_init(netif_init);
2232 
2233 
2234 static void __exit netif_exit(void)
2235 {
2236 	xenbus_unregister_driver(&netfront_driver);
2237 }
2238 module_exit(netif_exit);
2239 
2240 MODULE_DESCRIPTION("Xen virtual network device frontend");
2241 MODULE_LICENSE("GPL");
2242 MODULE_ALIAS("xen:vif");
2243 MODULE_ALIAS("xennet");
2244