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