eeed0ce620f3d8bcdad897cd188dfaacb924a03b
[cascardo/linux.git] / drivers / net / xen-netfront.c
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                 data = skb->data;
631                 offset = offset_in_page(data);
632                 len = skb_headlen(skb);
633         }
634
635         spin_lock_irqsave(&queue->tx_lock, flags);
636
637         if (unlikely(!netif_carrier_ok(dev) ||
638                      (slots > 1 && !xennet_can_sg(dev)) ||
639                      netif_needs_gso(dev, skb, netif_skb_features(skb)))) {
640                 spin_unlock_irqrestore(&queue->tx_lock, flags);
641                 goto drop;
642         }
643
644         i = queue->tx.req_prod_pvt;
645
646         id = get_id_from_freelist(&queue->tx_skb_freelist, queue->tx_skbs);
647         queue->tx_skbs[id].skb = skb;
648
649         tx = RING_GET_REQUEST(&queue->tx, i);
650
651         tx->id   = id;
652         ref = gnttab_claim_grant_reference(&queue->gref_tx_head);
653         BUG_ON((signed short)ref < 0);
654         mfn = virt_to_mfn(data);
655         gnttab_grant_foreign_access_ref(
656                 ref, queue->info->xbdev->otherend_id, mfn, GNTMAP_readonly);
657         queue->grant_tx_page[id] = virt_to_page(data);
658         tx->gref = queue->grant_tx_ref[id] = ref;
659         tx->offset = offset;
660         tx->size = len;
661
662         tx->flags = 0;
663         if (skb->ip_summed == CHECKSUM_PARTIAL)
664                 /* local packet? */
665                 tx->flags |= XEN_NETTXF_csum_blank | XEN_NETTXF_data_validated;
666         else if (skb->ip_summed == CHECKSUM_UNNECESSARY)
667                 /* remote but checksummed. */
668                 tx->flags |= XEN_NETTXF_data_validated;
669
670         if (skb_shinfo(skb)->gso_size) {
671                 struct xen_netif_extra_info *gso;
672
673                 gso = (struct xen_netif_extra_info *)
674                         RING_GET_REQUEST(&queue->tx, ++i);
675
676                 tx->flags |= XEN_NETTXF_extra_info;
677
678                 gso->u.gso.size = skb_shinfo(skb)->gso_size;
679                 gso->u.gso.type = (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) ?
680                         XEN_NETIF_GSO_TYPE_TCPV6 :
681                         XEN_NETIF_GSO_TYPE_TCPV4;
682                 gso->u.gso.pad = 0;
683                 gso->u.gso.features = 0;
684
685                 gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
686                 gso->flags = 0;
687         }
688
689         queue->tx.req_prod_pvt = i + 1;
690
691         xennet_make_frags(skb, queue, tx);
692         tx->size = skb->len;
693
694         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&queue->tx, notify);
695         if (notify)
696                 notify_remote_via_irq(queue->tx_irq);
697
698         u64_stats_update_begin(&stats->syncp);
699         stats->tx_bytes += skb->len;
700         stats->tx_packets++;
701         u64_stats_update_end(&stats->syncp);
702
703         /* Note: It is not safe to access skb after xennet_tx_buf_gc()! */
704         xennet_tx_buf_gc(queue);
705
706         if (!netfront_tx_slot_available(queue))
707                 netif_tx_stop_queue(netdev_get_tx_queue(dev, queue->id));
708
709         spin_unlock_irqrestore(&queue->tx_lock, flags);
710
711         return NETDEV_TX_OK;
712
713  drop:
714         dev->stats.tx_dropped++;
715         dev_kfree_skb_any(skb);
716         return NETDEV_TX_OK;
717 }
718
719 static int xennet_close(struct net_device *dev)
720 {
721         struct netfront_info *np = netdev_priv(dev);
722         unsigned int num_queues = dev->real_num_tx_queues;
723         unsigned int i;
724         struct netfront_queue *queue;
725         netif_tx_stop_all_queues(np->netdev);
726         for (i = 0; i < num_queues; ++i) {
727                 queue = &np->queues[i];
728                 napi_disable(&queue->napi);
729         }
730         return 0;
731 }
732
733 static void xennet_move_rx_slot(struct netfront_queue *queue, struct sk_buff *skb,
734                                 grant_ref_t ref)
735 {
736         int new = xennet_rxidx(queue->rx.req_prod_pvt);
737
738         BUG_ON(queue->rx_skbs[new]);
739         queue->rx_skbs[new] = skb;
740         queue->grant_rx_ref[new] = ref;
741         RING_GET_REQUEST(&queue->rx, queue->rx.req_prod_pvt)->id = new;
742         RING_GET_REQUEST(&queue->rx, queue->rx.req_prod_pvt)->gref = ref;
743         queue->rx.req_prod_pvt++;
744 }
745
746 static int xennet_get_extras(struct netfront_queue *queue,
747                              struct xen_netif_extra_info *extras,
748                              RING_IDX rp)
749
750 {
751         struct xen_netif_extra_info *extra;
752         struct device *dev = &queue->info->netdev->dev;
753         RING_IDX cons = queue->rx.rsp_cons;
754         int err = 0;
755
756         do {
757                 struct sk_buff *skb;
758                 grant_ref_t ref;
759
760                 if (unlikely(cons + 1 == rp)) {
761                         if (net_ratelimit())
762                                 dev_warn(dev, "Missing extra info\n");
763                         err = -EBADR;
764                         break;
765                 }
766
767                 extra = (struct xen_netif_extra_info *)
768                         RING_GET_RESPONSE(&queue->rx, ++cons);
769
770                 if (unlikely(!extra->type ||
771                              extra->type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
772                         if (net_ratelimit())
773                                 dev_warn(dev, "Invalid extra type: %d\n",
774                                         extra->type);
775                         err = -EINVAL;
776                 } else {
777                         memcpy(&extras[extra->type - 1], extra,
778                                sizeof(*extra));
779                 }
780
781                 skb = xennet_get_rx_skb(queue, cons);
782                 ref = xennet_get_rx_ref(queue, cons);
783                 xennet_move_rx_slot(queue, skb, ref);
784         } while (extra->flags & XEN_NETIF_EXTRA_FLAG_MORE);
785
786         queue->rx.rsp_cons = cons;
787         return err;
788 }
789
790 static int xennet_get_responses(struct netfront_queue *queue,
791                                 struct netfront_rx_info *rinfo, RING_IDX rp,
792                                 struct sk_buff_head *list)
793 {
794         struct xen_netif_rx_response *rx = &rinfo->rx;
795         struct xen_netif_extra_info *extras = rinfo->extras;
796         struct device *dev = &queue->info->netdev->dev;
797         RING_IDX cons = queue->rx.rsp_cons;
798         struct sk_buff *skb = xennet_get_rx_skb(queue, cons);
799         grant_ref_t ref = xennet_get_rx_ref(queue, cons);
800         int max = MAX_SKB_FRAGS + (rx->status <= RX_COPY_THRESHOLD);
801         int slots = 1;
802         int err = 0;
803         unsigned long ret;
804
805         if (rx->flags & XEN_NETRXF_extra_info) {
806                 err = xennet_get_extras(queue, extras, rp);
807                 cons = queue->rx.rsp_cons;
808         }
809
810         for (;;) {
811                 if (unlikely(rx->status < 0 ||
812                              rx->offset + rx->status > PAGE_SIZE)) {
813                         if (net_ratelimit())
814                                 dev_warn(dev, "rx->offset: %x, size: %u\n",
815                                          rx->offset, rx->status);
816                         xennet_move_rx_slot(queue, skb, ref);
817                         err = -EINVAL;
818                         goto next;
819                 }
820
821                 /*
822                  * This definitely indicates a bug, either in this driver or in
823                  * the backend driver. In future this should flag the bad
824                  * situation to the system controller to reboot the backend.
825                  */
826                 if (ref == GRANT_INVALID_REF) {
827                         if (net_ratelimit())
828                                 dev_warn(dev, "Bad rx response id %d.\n",
829                                          rx->id);
830                         err = -EINVAL;
831                         goto next;
832                 }
833
834                 ret = gnttab_end_foreign_access_ref(ref, 0);
835                 BUG_ON(!ret);
836
837                 gnttab_release_grant_reference(&queue->gref_rx_head, ref);
838
839                 __skb_queue_tail(list, skb);
840
841 next:
842                 if (!(rx->flags & XEN_NETRXF_more_data))
843                         break;
844
845                 if (cons + slots == rp) {
846                         if (net_ratelimit())
847                                 dev_warn(dev, "Need more slots\n");
848                         err = -ENOENT;
849                         break;
850                 }
851
852                 rx = RING_GET_RESPONSE(&queue->rx, cons + slots);
853                 skb = xennet_get_rx_skb(queue, cons + slots);
854                 ref = xennet_get_rx_ref(queue, cons + slots);
855                 slots++;
856         }
857
858         if (unlikely(slots > max)) {
859                 if (net_ratelimit())
860                         dev_warn(dev, "Too many slots\n");
861                 err = -E2BIG;
862         }
863
864         if (unlikely(err))
865                 queue->rx.rsp_cons = cons + slots;
866
867         return err;
868 }
869
870 static int xennet_set_skb_gso(struct sk_buff *skb,
871                               struct xen_netif_extra_info *gso)
872 {
873         if (!gso->u.gso.size) {
874                 if (net_ratelimit())
875                         pr_warn("GSO size must not be zero\n");
876                 return -EINVAL;
877         }
878
879         if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4 &&
880             gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV6) {
881                 if (net_ratelimit())
882                         pr_warn("Bad GSO type %d\n", gso->u.gso.type);
883                 return -EINVAL;
884         }
885
886         skb_shinfo(skb)->gso_size = gso->u.gso.size;
887         skb_shinfo(skb)->gso_type =
888                 (gso->u.gso.type == XEN_NETIF_GSO_TYPE_TCPV4) ?
889                 SKB_GSO_TCPV4 :
890                 SKB_GSO_TCPV6;
891
892         /* Header must be checked, and gso_segs computed. */
893         skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
894         skb_shinfo(skb)->gso_segs = 0;
895
896         return 0;
897 }
898
899 static RING_IDX xennet_fill_frags(struct netfront_queue *queue,
900                                   struct sk_buff *skb,
901                                   struct sk_buff_head *list)
902 {
903         struct skb_shared_info *shinfo = skb_shinfo(skb);
904         RING_IDX cons = queue->rx.rsp_cons;
905         struct sk_buff *nskb;
906
907         while ((nskb = __skb_dequeue(list))) {
908                 struct xen_netif_rx_response *rx =
909                         RING_GET_RESPONSE(&queue->rx, ++cons);
910                 skb_frag_t *nfrag = &skb_shinfo(nskb)->frags[0];
911
912                 if (shinfo->nr_frags == MAX_SKB_FRAGS) {
913                         unsigned int pull_to = NETFRONT_SKB_CB(skb)->pull_to;
914
915                         BUG_ON(pull_to <= skb_headlen(skb));
916                         __pskb_pull_tail(skb, pull_to - skb_headlen(skb));
917                 }
918                 BUG_ON(shinfo->nr_frags >= MAX_SKB_FRAGS);
919
920                 skb_add_rx_frag(skb, shinfo->nr_frags, skb_frag_page(nfrag),
921                                 rx->offset, rx->status, PAGE_SIZE);
922
923                 skb_shinfo(nskb)->nr_frags = 0;
924                 kfree_skb(nskb);
925         }
926
927         return cons;
928 }
929
930 static int checksum_setup(struct net_device *dev, struct sk_buff *skb)
931 {
932         bool recalculate_partial_csum = false;
933
934         /*
935          * A GSO SKB must be CHECKSUM_PARTIAL. However some buggy
936          * peers can fail to set NETRXF_csum_blank when sending a GSO
937          * frame. In this case force the SKB to CHECKSUM_PARTIAL and
938          * recalculate the partial checksum.
939          */
940         if (skb->ip_summed != CHECKSUM_PARTIAL && skb_is_gso(skb)) {
941                 struct netfront_info *np = netdev_priv(dev);
942                 atomic_inc(&np->rx_gso_checksum_fixup);
943                 skb->ip_summed = CHECKSUM_PARTIAL;
944                 recalculate_partial_csum = true;
945         }
946
947         /* A non-CHECKSUM_PARTIAL SKB does not require setup. */
948         if (skb->ip_summed != CHECKSUM_PARTIAL)
949                 return 0;
950
951         return skb_checksum_setup(skb, recalculate_partial_csum);
952 }
953
954 static int handle_incoming_queue(struct netfront_queue *queue,
955                                  struct sk_buff_head *rxq)
956 {
957         struct netfront_stats *stats = this_cpu_ptr(queue->info->stats);
958         int packets_dropped = 0;
959         struct sk_buff *skb;
960
961         while ((skb = __skb_dequeue(rxq)) != NULL) {
962                 int pull_to = NETFRONT_SKB_CB(skb)->pull_to;
963
964                 if (pull_to > skb_headlen(skb))
965                         __pskb_pull_tail(skb, pull_to - skb_headlen(skb));
966
967                 /* Ethernet work: Delayed to here as it peeks the header. */
968                 skb->protocol = eth_type_trans(skb, queue->info->netdev);
969                 skb_reset_network_header(skb);
970
971                 if (checksum_setup(queue->info->netdev, skb)) {
972                         kfree_skb(skb);
973                         packets_dropped++;
974                         queue->info->netdev->stats.rx_errors++;
975                         continue;
976                 }
977
978                 u64_stats_update_begin(&stats->syncp);
979                 stats->rx_packets++;
980                 stats->rx_bytes += skb->len;
981                 u64_stats_update_end(&stats->syncp);
982
983                 /* Pass it up. */
984                 napi_gro_receive(&queue->napi, skb);
985         }
986
987         return packets_dropped;
988 }
989
990 static int xennet_poll(struct napi_struct *napi, int budget)
991 {
992         struct netfront_queue *queue = container_of(napi, struct netfront_queue, napi);
993         struct net_device *dev = queue->info->netdev;
994         struct sk_buff *skb;
995         struct netfront_rx_info rinfo;
996         struct xen_netif_rx_response *rx = &rinfo.rx;
997         struct xen_netif_extra_info *extras = rinfo.extras;
998         RING_IDX i, rp;
999         int work_done;
1000         struct sk_buff_head rxq;
1001         struct sk_buff_head errq;
1002         struct sk_buff_head tmpq;
1003         unsigned long flags;
1004         int err;
1005
1006         spin_lock(&queue->rx_lock);
1007
1008         skb_queue_head_init(&rxq);
1009         skb_queue_head_init(&errq);
1010         skb_queue_head_init(&tmpq);
1011
1012         rp = queue->rx.sring->rsp_prod;
1013         rmb(); /* Ensure we see queued responses up to 'rp'. */
1014
1015         i = queue->rx.rsp_cons;
1016         work_done = 0;
1017         while ((i != rp) && (work_done < budget)) {
1018                 memcpy(rx, RING_GET_RESPONSE(&queue->rx, i), sizeof(*rx));
1019                 memset(extras, 0, sizeof(rinfo.extras));
1020
1021                 err = xennet_get_responses(queue, &rinfo, rp, &tmpq);
1022
1023                 if (unlikely(err)) {
1024 err:
1025                         while ((skb = __skb_dequeue(&tmpq)))
1026                                 __skb_queue_tail(&errq, skb);
1027                         dev->stats.rx_errors++;
1028                         i = queue->rx.rsp_cons;
1029                         continue;
1030                 }
1031
1032                 skb = __skb_dequeue(&tmpq);
1033
1034                 if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
1035                         struct xen_netif_extra_info *gso;
1036                         gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
1037
1038                         if (unlikely(xennet_set_skb_gso(skb, gso))) {
1039                                 __skb_queue_head(&tmpq, skb);
1040                                 queue->rx.rsp_cons += skb_queue_len(&tmpq);
1041                                 goto err;
1042                         }
1043                 }
1044
1045                 NETFRONT_SKB_CB(skb)->pull_to = rx->status;
1046                 if (NETFRONT_SKB_CB(skb)->pull_to > RX_COPY_THRESHOLD)
1047                         NETFRONT_SKB_CB(skb)->pull_to = RX_COPY_THRESHOLD;
1048
1049                 skb_shinfo(skb)->frags[0].page_offset = rx->offset;
1050                 skb_frag_size_set(&skb_shinfo(skb)->frags[0], rx->status);
1051                 skb->data_len = rx->status;
1052                 skb->len += rx->status;
1053
1054                 i = xennet_fill_frags(queue, skb, &tmpq);
1055
1056                 if (rx->flags & XEN_NETRXF_csum_blank)
1057                         skb->ip_summed = CHECKSUM_PARTIAL;
1058                 else if (rx->flags & XEN_NETRXF_data_validated)
1059                         skb->ip_summed = CHECKSUM_UNNECESSARY;
1060
1061                 __skb_queue_tail(&rxq, skb);
1062
1063                 queue->rx.rsp_cons = ++i;
1064                 work_done++;
1065         }
1066
1067         __skb_queue_purge(&errq);
1068
1069         work_done -= handle_incoming_queue(queue, &rxq);
1070
1071         /* If we get a callback with very few responses, reduce fill target. */
1072         /* NB. Note exponential increase, linear decrease. */
1073         if (((queue->rx.req_prod_pvt - queue->rx.sring->rsp_prod) >
1074              ((3*queue->rx_target) / 4)) &&
1075             (--queue->rx_target < queue->rx_min_target))
1076                 queue->rx_target = queue->rx_min_target;
1077
1078         xennet_alloc_rx_buffers(queue);
1079
1080         if (work_done < budget) {
1081                 int more_to_do = 0;
1082
1083                 napi_gro_flush(napi, false);
1084
1085                 local_irq_save(flags);
1086
1087                 RING_FINAL_CHECK_FOR_RESPONSES(&queue->rx, more_to_do);
1088                 if (!more_to_do)
1089                         __napi_complete(napi);
1090
1091                 local_irq_restore(flags);
1092         }
1093
1094         spin_unlock(&queue->rx_lock);
1095
1096         return work_done;
1097 }
1098
1099 static int xennet_change_mtu(struct net_device *dev, int mtu)
1100 {
1101         int max = xennet_can_sg(dev) ?
1102                 XEN_NETIF_MAX_TX_SIZE - MAX_TCP_HEADER : ETH_DATA_LEN;
1103
1104         if (mtu > max)
1105                 return -EINVAL;
1106         dev->mtu = mtu;
1107         return 0;
1108 }
1109
1110 static struct rtnl_link_stats64 *xennet_get_stats64(struct net_device *dev,
1111                                                     struct rtnl_link_stats64 *tot)
1112 {
1113         struct netfront_info *np = netdev_priv(dev);
1114         int cpu;
1115
1116         for_each_possible_cpu(cpu) {
1117                 struct netfront_stats *stats = per_cpu_ptr(np->stats, cpu);
1118                 u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
1119                 unsigned int start;
1120
1121                 do {
1122                         start = u64_stats_fetch_begin_irq(&stats->syncp);
1123
1124                         rx_packets = stats->rx_packets;
1125                         tx_packets = stats->tx_packets;
1126                         rx_bytes = stats->rx_bytes;
1127                         tx_bytes = stats->tx_bytes;
1128                 } while (u64_stats_fetch_retry_irq(&stats->syncp, start));
1129
1130                 tot->rx_packets += rx_packets;
1131                 tot->tx_packets += tx_packets;
1132                 tot->rx_bytes   += rx_bytes;
1133                 tot->tx_bytes   += tx_bytes;
1134         }
1135
1136         tot->rx_errors  = dev->stats.rx_errors;
1137         tot->tx_dropped = dev->stats.tx_dropped;
1138
1139         return tot;
1140 }
1141
1142 static void xennet_release_tx_bufs(struct netfront_queue *queue)
1143 {
1144         struct sk_buff *skb;
1145         int i;
1146
1147         for (i = 0; i < NET_TX_RING_SIZE; i++) {
1148                 /* Skip over entries which are actually freelist references */
1149                 if (skb_entry_is_link(&queue->tx_skbs[i]))
1150                         continue;
1151
1152                 skb = queue->tx_skbs[i].skb;
1153                 get_page(queue->grant_tx_page[i]);
1154                 gnttab_end_foreign_access(queue->grant_tx_ref[i],
1155                                           GNTMAP_readonly,
1156                                           (unsigned long)page_address(queue->grant_tx_page[i]));
1157                 queue->grant_tx_page[i] = NULL;
1158                 queue->grant_tx_ref[i] = GRANT_INVALID_REF;
1159                 add_id_to_freelist(&queue->tx_skb_freelist, queue->tx_skbs, i);
1160                 dev_kfree_skb_irq(skb);
1161         }
1162 }
1163
1164 static void xennet_release_rx_bufs(struct netfront_queue *queue)
1165 {
1166         int id, ref;
1167
1168         spin_lock_bh(&queue->rx_lock);
1169
1170         for (id = 0; id < NET_RX_RING_SIZE; id++) {
1171                 struct sk_buff *skb;
1172                 struct page *page;
1173
1174                 skb = queue->rx_skbs[id];
1175                 if (!skb)
1176                         continue;
1177
1178                 ref = queue->grant_rx_ref[id];
1179                 if (ref == GRANT_INVALID_REF)
1180                         continue;
1181
1182                 page = skb_frag_page(&skb_shinfo(skb)->frags[0]);
1183
1184                 /* gnttab_end_foreign_access() needs a page ref until
1185                  * foreign access is ended (which may be deferred).
1186                  */
1187                 get_page(page);
1188                 gnttab_end_foreign_access(ref, 0,
1189                                           (unsigned long)page_address(page));
1190                 queue->grant_rx_ref[id] = GRANT_INVALID_REF;
1191
1192                 kfree_skb(skb);
1193         }
1194
1195         spin_unlock_bh(&queue->rx_lock);
1196 }
1197
1198 static netdev_features_t xennet_fix_features(struct net_device *dev,
1199         netdev_features_t features)
1200 {
1201         struct netfront_info *np = netdev_priv(dev);
1202         int val;
1203
1204         if (features & NETIF_F_SG) {
1205                 if (xenbus_scanf(XBT_NIL, np->xbdev->otherend, "feature-sg",
1206                                  "%d", &val) < 0)
1207                         val = 0;
1208
1209                 if (!val)
1210                         features &= ~NETIF_F_SG;
1211         }
1212
1213         if (features & NETIF_F_IPV6_CSUM) {
1214                 if (xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1215                                  "feature-ipv6-csum-offload", "%d", &val) < 0)
1216                         val = 0;
1217
1218                 if (!val)
1219                         features &= ~NETIF_F_IPV6_CSUM;
1220         }
1221
1222         if (features & NETIF_F_TSO) {
1223                 if (xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1224                                  "feature-gso-tcpv4", "%d", &val) < 0)
1225                         val = 0;
1226
1227                 if (!val)
1228                         features &= ~NETIF_F_TSO;
1229         }
1230
1231         if (features & NETIF_F_TSO6) {
1232                 if (xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1233                                  "feature-gso-tcpv6", "%d", &val) < 0)
1234                         val = 0;
1235
1236                 if (!val)
1237                         features &= ~NETIF_F_TSO6;
1238         }
1239
1240         return features;
1241 }
1242
1243 static int xennet_set_features(struct net_device *dev,
1244         netdev_features_t features)
1245 {
1246         if (!(features & NETIF_F_SG) && dev->mtu > ETH_DATA_LEN) {
1247                 netdev_info(dev, "Reducing MTU because no SG offload");
1248                 dev->mtu = ETH_DATA_LEN;
1249         }
1250
1251         return 0;
1252 }
1253
1254 static irqreturn_t xennet_tx_interrupt(int irq, void *dev_id)
1255 {
1256         struct netfront_queue *queue = dev_id;
1257         unsigned long flags;
1258
1259         spin_lock_irqsave(&queue->tx_lock, flags);
1260         xennet_tx_buf_gc(queue);
1261         spin_unlock_irqrestore(&queue->tx_lock, flags);
1262
1263         return IRQ_HANDLED;
1264 }
1265
1266 static irqreturn_t xennet_rx_interrupt(int irq, void *dev_id)
1267 {
1268         struct netfront_queue *queue = dev_id;
1269         struct net_device *dev = queue->info->netdev;
1270
1271         if (likely(netif_carrier_ok(dev) &&
1272                    RING_HAS_UNCONSUMED_RESPONSES(&queue->rx)))
1273                 napi_schedule(&queue->napi);
1274
1275         return IRQ_HANDLED;
1276 }
1277
1278 static irqreturn_t xennet_interrupt(int irq, void *dev_id)
1279 {
1280         xennet_tx_interrupt(irq, dev_id);
1281         xennet_rx_interrupt(irq, dev_id);
1282         return IRQ_HANDLED;
1283 }
1284
1285 #ifdef CONFIG_NET_POLL_CONTROLLER
1286 static void xennet_poll_controller(struct net_device *dev)
1287 {
1288         /* Poll each queue */
1289         struct netfront_info *info = netdev_priv(dev);
1290         unsigned int num_queues = dev->real_num_tx_queues;
1291         unsigned int i;
1292         for (i = 0; i < num_queues; ++i)
1293                 xennet_interrupt(0, &info->queues[i]);
1294 }
1295 #endif
1296
1297 static const struct net_device_ops xennet_netdev_ops = {
1298         .ndo_open            = xennet_open,
1299         .ndo_stop            = xennet_close,
1300         .ndo_start_xmit      = xennet_start_xmit,
1301         .ndo_change_mtu      = xennet_change_mtu,
1302         .ndo_get_stats64     = xennet_get_stats64,
1303         .ndo_set_mac_address = eth_mac_addr,
1304         .ndo_validate_addr   = eth_validate_addr,
1305         .ndo_fix_features    = xennet_fix_features,
1306         .ndo_set_features    = xennet_set_features,
1307         .ndo_select_queue    = xennet_select_queue,
1308 #ifdef CONFIG_NET_POLL_CONTROLLER
1309         .ndo_poll_controller = xennet_poll_controller,
1310 #endif
1311 };
1312
1313 static struct net_device *xennet_create_dev(struct xenbus_device *dev)
1314 {
1315         int err;
1316         struct net_device *netdev;
1317         struct netfront_info *np;
1318
1319         netdev = alloc_etherdev_mq(sizeof(struct netfront_info), xennet_max_queues);
1320         if (!netdev)
1321                 return ERR_PTR(-ENOMEM);
1322
1323         np                   = netdev_priv(netdev);
1324         np->xbdev            = dev;
1325
1326         /* No need to use rtnl_lock() before the call below as it
1327          * happens before register_netdev().
1328          */
1329         netif_set_real_num_tx_queues(netdev, 0);
1330         np->queues = NULL;
1331
1332         err = -ENOMEM;
1333         np->stats = netdev_alloc_pcpu_stats(struct netfront_stats);
1334         if (np->stats == NULL)
1335                 goto exit;
1336
1337         netdev->netdev_ops      = &xennet_netdev_ops;
1338
1339         netdev->features        = NETIF_F_IP_CSUM | NETIF_F_RXCSUM |
1340                                   NETIF_F_GSO_ROBUST;
1341         netdev->hw_features     = NETIF_F_SG |
1342                                   NETIF_F_IPV6_CSUM |
1343                                   NETIF_F_TSO | NETIF_F_TSO6;
1344
1345         /*
1346          * Assume that all hw features are available for now. This set
1347          * will be adjusted by the call to netdev_update_features() in
1348          * xennet_connect() which is the earliest point where we can
1349          * negotiate with the backend regarding supported features.
1350          */
1351         netdev->features |= netdev->hw_features;
1352
1353         netdev->ethtool_ops = &xennet_ethtool_ops;
1354         SET_NETDEV_DEV(netdev, &dev->dev);
1355
1356         netif_set_gso_max_size(netdev, XEN_NETIF_MAX_TX_SIZE - MAX_TCP_HEADER);
1357
1358         np->netdev = netdev;
1359
1360         netif_carrier_off(netdev);
1361
1362         return netdev;
1363
1364  exit:
1365         free_netdev(netdev);
1366         return ERR_PTR(err);
1367 }
1368
1369 /**
1370  * Entry point to this code when a new device is created.  Allocate the basic
1371  * structures and the ring buffers for communication with the backend, and
1372  * inform the backend of the appropriate details for those.
1373  */
1374 static int netfront_probe(struct xenbus_device *dev,
1375                           const struct xenbus_device_id *id)
1376 {
1377         int err;
1378         struct net_device *netdev;
1379         struct netfront_info *info;
1380
1381         netdev = xennet_create_dev(dev);
1382         if (IS_ERR(netdev)) {
1383                 err = PTR_ERR(netdev);
1384                 xenbus_dev_fatal(dev, err, "creating netdev");
1385                 return err;
1386         }
1387
1388         info = netdev_priv(netdev);
1389         dev_set_drvdata(&dev->dev, info);
1390
1391         err = register_netdev(info->netdev);
1392         if (err) {
1393                 pr_warn("%s: register_netdev err=%d\n", __func__, err);
1394                 goto fail;
1395         }
1396
1397         err = xennet_sysfs_addif(info->netdev);
1398         if (err) {
1399                 unregister_netdev(info->netdev);
1400                 pr_warn("%s: add sysfs failed err=%d\n", __func__, err);
1401                 goto fail;
1402         }
1403
1404         return 0;
1405
1406  fail:
1407         free_netdev(netdev);
1408         dev_set_drvdata(&dev->dev, NULL);
1409         return err;
1410 }
1411
1412 static void xennet_end_access(int ref, void *page)
1413 {
1414         /* This frees the page as a side-effect */
1415         if (ref != GRANT_INVALID_REF)
1416                 gnttab_end_foreign_access(ref, 0, (unsigned long)page);
1417 }
1418
1419 static void xennet_disconnect_backend(struct netfront_info *info)
1420 {
1421         unsigned int i = 0;
1422         unsigned int num_queues = info->netdev->real_num_tx_queues;
1423
1424         netif_carrier_off(info->netdev);
1425
1426         for (i = 0; i < num_queues; ++i) {
1427                 struct netfront_queue *queue = &info->queues[i];
1428
1429                 if (queue->tx_irq && (queue->tx_irq == queue->rx_irq))
1430                         unbind_from_irqhandler(queue->tx_irq, queue);
1431                 if (queue->tx_irq && (queue->tx_irq != queue->rx_irq)) {
1432                         unbind_from_irqhandler(queue->tx_irq, queue);
1433                         unbind_from_irqhandler(queue->rx_irq, queue);
1434                 }
1435                 queue->tx_evtchn = queue->rx_evtchn = 0;
1436                 queue->tx_irq = queue->rx_irq = 0;
1437
1438                 napi_synchronize(&queue->napi);
1439
1440                 xennet_release_tx_bufs(queue);
1441                 xennet_release_rx_bufs(queue);
1442                 gnttab_free_grant_references(queue->gref_tx_head);
1443                 gnttab_free_grant_references(queue->gref_rx_head);
1444
1445                 /* End access and free the pages */
1446                 xennet_end_access(queue->tx_ring_ref, queue->tx.sring);
1447                 xennet_end_access(queue->rx_ring_ref, queue->rx.sring);
1448
1449                 queue->tx_ring_ref = GRANT_INVALID_REF;
1450                 queue->rx_ring_ref = GRANT_INVALID_REF;
1451                 queue->tx.sring = NULL;
1452                 queue->rx.sring = NULL;
1453         }
1454 }
1455
1456 /**
1457  * We are reconnecting to the backend, due to a suspend/resume, or a backend
1458  * driver restart.  We tear down our netif structure and recreate it, but
1459  * leave the device-layer structures intact so that this is transparent to the
1460  * rest of the kernel.
1461  */
1462 static int netfront_resume(struct xenbus_device *dev)
1463 {
1464         struct netfront_info *info = dev_get_drvdata(&dev->dev);
1465
1466         dev_dbg(&dev->dev, "%s\n", dev->nodename);
1467
1468         xennet_disconnect_backend(info);
1469         return 0;
1470 }
1471
1472 static int xen_net_read_mac(struct xenbus_device *dev, u8 mac[])
1473 {
1474         char *s, *e, *macstr;
1475         int i;
1476
1477         macstr = s = xenbus_read(XBT_NIL, dev->nodename, "mac", NULL);
1478         if (IS_ERR(macstr))
1479                 return PTR_ERR(macstr);
1480
1481         for (i = 0; i < ETH_ALEN; i++) {
1482                 mac[i] = simple_strtoul(s, &e, 16);
1483                 if ((s == e) || (*e != ((i == ETH_ALEN-1) ? '\0' : ':'))) {
1484                         kfree(macstr);
1485                         return -ENOENT;
1486                 }
1487                 s = e+1;
1488         }
1489
1490         kfree(macstr);
1491         return 0;
1492 }
1493
1494 static int setup_netfront_single(struct netfront_queue *queue)
1495 {
1496         int err;
1497
1498         err = xenbus_alloc_evtchn(queue->info->xbdev, &queue->tx_evtchn);
1499         if (err < 0)
1500                 goto fail;
1501
1502         err = bind_evtchn_to_irqhandler(queue->tx_evtchn,
1503                                         xennet_interrupt,
1504                                         0, queue->info->netdev->name, queue);
1505         if (err < 0)
1506                 goto bind_fail;
1507         queue->rx_evtchn = queue->tx_evtchn;
1508         queue->rx_irq = queue->tx_irq = err;
1509
1510         return 0;
1511
1512 bind_fail:
1513         xenbus_free_evtchn(queue->info->xbdev, queue->tx_evtchn);
1514         queue->tx_evtchn = 0;
1515 fail:
1516         return err;
1517 }
1518
1519 static int setup_netfront_split(struct netfront_queue *queue)
1520 {
1521         int err;
1522
1523         err = xenbus_alloc_evtchn(queue->info->xbdev, &queue->tx_evtchn);
1524         if (err < 0)
1525                 goto fail;
1526         err = xenbus_alloc_evtchn(queue->info->xbdev, &queue->rx_evtchn);
1527         if (err < 0)
1528                 goto alloc_rx_evtchn_fail;
1529
1530         snprintf(queue->tx_irq_name, sizeof(queue->tx_irq_name),
1531                  "%s-tx", queue->name);
1532         err = bind_evtchn_to_irqhandler(queue->tx_evtchn,
1533                                         xennet_tx_interrupt,
1534                                         0, queue->tx_irq_name, queue);
1535         if (err < 0)
1536                 goto bind_tx_fail;
1537         queue->tx_irq = err;
1538
1539         snprintf(queue->rx_irq_name, sizeof(queue->rx_irq_name),
1540                  "%s-rx", queue->name);
1541         err = bind_evtchn_to_irqhandler(queue->rx_evtchn,
1542                                         xennet_rx_interrupt,
1543                                         0, queue->rx_irq_name, queue);
1544         if (err < 0)
1545                 goto bind_rx_fail;
1546         queue->rx_irq = err;
1547
1548         return 0;
1549
1550 bind_rx_fail:
1551         unbind_from_irqhandler(queue->tx_irq, queue);
1552         queue->tx_irq = 0;
1553 bind_tx_fail:
1554         xenbus_free_evtchn(queue->info->xbdev, queue->rx_evtchn);
1555         queue->rx_evtchn = 0;
1556 alloc_rx_evtchn_fail:
1557         xenbus_free_evtchn(queue->info->xbdev, queue->tx_evtchn);
1558         queue->tx_evtchn = 0;
1559 fail:
1560         return err;
1561 }
1562
1563 static int setup_netfront(struct xenbus_device *dev,
1564                         struct netfront_queue *queue, unsigned int feature_split_evtchn)
1565 {
1566         struct xen_netif_tx_sring *txs;
1567         struct xen_netif_rx_sring *rxs;
1568         int err;
1569
1570         queue->tx_ring_ref = GRANT_INVALID_REF;
1571         queue->rx_ring_ref = GRANT_INVALID_REF;
1572         queue->rx.sring = NULL;
1573         queue->tx.sring = NULL;
1574
1575         txs = (struct xen_netif_tx_sring *)get_zeroed_page(GFP_NOIO | __GFP_HIGH);
1576         if (!txs) {
1577                 err = -ENOMEM;
1578                 xenbus_dev_fatal(dev, err, "allocating tx ring page");
1579                 goto fail;
1580         }
1581         SHARED_RING_INIT(txs);
1582         FRONT_RING_INIT(&queue->tx, txs, PAGE_SIZE);
1583
1584         err = xenbus_grant_ring(dev, virt_to_mfn(txs));
1585         if (err < 0)
1586                 goto grant_tx_ring_fail;
1587         queue->tx_ring_ref = err;
1588
1589         rxs = (struct xen_netif_rx_sring *)get_zeroed_page(GFP_NOIO | __GFP_HIGH);
1590         if (!rxs) {
1591                 err = -ENOMEM;
1592                 xenbus_dev_fatal(dev, err, "allocating rx ring page");
1593                 goto alloc_rx_ring_fail;
1594         }
1595         SHARED_RING_INIT(rxs);
1596         FRONT_RING_INIT(&queue->rx, rxs, PAGE_SIZE);
1597
1598         err = xenbus_grant_ring(dev, virt_to_mfn(rxs));
1599         if (err < 0)
1600                 goto grant_rx_ring_fail;
1601         queue->rx_ring_ref = err;
1602
1603         if (feature_split_evtchn)
1604                 err = setup_netfront_split(queue);
1605         /* setup single event channel if
1606          *  a) feature-split-event-channels == 0
1607          *  b) feature-split-event-channels == 1 but failed to setup
1608          */
1609         if (!feature_split_evtchn || (feature_split_evtchn && err))
1610                 err = setup_netfront_single(queue);
1611
1612         if (err)
1613                 goto alloc_evtchn_fail;
1614
1615         return 0;
1616
1617         /* If we fail to setup netfront, it is safe to just revoke access to
1618          * granted pages because backend is not accessing it at this point.
1619          */
1620 alloc_evtchn_fail:
1621         gnttab_end_foreign_access_ref(queue->rx_ring_ref, 0);
1622 grant_rx_ring_fail:
1623         free_page((unsigned long)rxs);
1624 alloc_rx_ring_fail:
1625         gnttab_end_foreign_access_ref(queue->tx_ring_ref, 0);
1626 grant_tx_ring_fail:
1627         free_page((unsigned long)txs);
1628 fail:
1629         return err;
1630 }
1631
1632 /* Queue-specific initialisation
1633  * This used to be done in xennet_create_dev() but must now
1634  * be run per-queue.
1635  */
1636 static int xennet_init_queue(struct netfront_queue *queue)
1637 {
1638         unsigned short i;
1639         int err = 0;
1640
1641         spin_lock_init(&queue->tx_lock);
1642         spin_lock_init(&queue->rx_lock);
1643
1644         skb_queue_head_init(&queue->rx_batch);
1645         queue->rx_target     = RX_DFL_MIN_TARGET;
1646         queue->rx_min_target = RX_DFL_MIN_TARGET;
1647         queue->rx_max_target = RX_MAX_TARGET;
1648
1649         init_timer(&queue->rx_refill_timer);
1650         queue->rx_refill_timer.data = (unsigned long)queue;
1651         queue->rx_refill_timer.function = rx_refill_timeout;
1652
1653         snprintf(queue->name, sizeof(queue->name), "%s-q%u",
1654                  queue->info->netdev->name, queue->id);
1655
1656         /* Initialise tx_skbs as a free chain containing every entry. */
1657         queue->tx_skb_freelist = 0;
1658         for (i = 0; i < NET_TX_RING_SIZE; i++) {
1659                 skb_entry_set_link(&queue->tx_skbs[i], i+1);
1660                 queue->grant_tx_ref[i] = GRANT_INVALID_REF;
1661                 queue->grant_tx_page[i] = NULL;
1662         }
1663
1664         /* Clear out rx_skbs */
1665         for (i = 0; i < NET_RX_RING_SIZE; i++) {
1666                 queue->rx_skbs[i] = NULL;
1667                 queue->grant_rx_ref[i] = GRANT_INVALID_REF;
1668         }
1669
1670         /* A grant for every tx ring slot */
1671         if (gnttab_alloc_grant_references(TX_MAX_TARGET,
1672                                           &queue->gref_tx_head) < 0) {
1673                 pr_alert("can't alloc tx grant refs\n");
1674                 err = -ENOMEM;
1675                 goto exit;
1676         }
1677
1678         /* A grant for every rx ring slot */
1679         if (gnttab_alloc_grant_references(RX_MAX_TARGET,
1680                                           &queue->gref_rx_head) < 0) {
1681                 pr_alert("can't alloc rx grant refs\n");
1682                 err = -ENOMEM;
1683                 goto exit_free_tx;
1684         }
1685
1686         return 0;
1687
1688  exit_free_tx:
1689         gnttab_free_grant_references(queue->gref_tx_head);
1690  exit:
1691         return err;
1692 }
1693
1694 static int write_queue_xenstore_keys(struct netfront_queue *queue,
1695                            struct xenbus_transaction *xbt, int write_hierarchical)
1696 {
1697         /* Write the queue-specific keys into XenStore in the traditional
1698          * way for a single queue, or in a queue subkeys for multiple
1699          * queues.
1700          */
1701         struct xenbus_device *dev = queue->info->xbdev;
1702         int err;
1703         const char *message;
1704         char *path;
1705         size_t pathsize;
1706
1707         /* Choose the correct place to write the keys */
1708         if (write_hierarchical) {
1709                 pathsize = strlen(dev->nodename) + 10;
1710                 path = kzalloc(pathsize, GFP_KERNEL);
1711                 if (!path) {
1712                         err = -ENOMEM;
1713                         message = "out of memory while writing ring references";
1714                         goto error;
1715                 }
1716                 snprintf(path, pathsize, "%s/queue-%u",
1717                                 dev->nodename, queue->id);
1718         } else {
1719                 path = (char *)dev->nodename;
1720         }
1721
1722         /* Write ring references */
1723         err = xenbus_printf(*xbt, path, "tx-ring-ref", "%u",
1724                         queue->tx_ring_ref);
1725         if (err) {
1726                 message = "writing tx-ring-ref";
1727                 goto error;
1728         }
1729
1730         err = xenbus_printf(*xbt, path, "rx-ring-ref", "%u",
1731                         queue->rx_ring_ref);
1732         if (err) {
1733                 message = "writing rx-ring-ref";
1734                 goto error;
1735         }
1736
1737         /* Write event channels; taking into account both shared
1738          * and split event channel scenarios.
1739          */
1740         if (queue->tx_evtchn == queue->rx_evtchn) {
1741                 /* Shared event channel */
1742                 err = xenbus_printf(*xbt, path,
1743                                 "event-channel", "%u", queue->tx_evtchn);
1744                 if (err) {
1745                         message = "writing event-channel";
1746                         goto error;
1747                 }
1748         } else {
1749                 /* Split event channels */
1750                 err = xenbus_printf(*xbt, path,
1751                                 "event-channel-tx", "%u", queue->tx_evtchn);
1752                 if (err) {
1753                         message = "writing event-channel-tx";
1754                         goto error;
1755                 }
1756
1757                 err = xenbus_printf(*xbt, path,
1758                                 "event-channel-rx", "%u", queue->rx_evtchn);
1759                 if (err) {
1760                         message = "writing event-channel-rx";
1761                         goto error;
1762                 }
1763         }
1764
1765         if (write_hierarchical)
1766                 kfree(path);
1767         return 0;
1768
1769 error:
1770         if (write_hierarchical)
1771                 kfree(path);
1772         xenbus_dev_fatal(dev, err, "%s", message);
1773         return err;
1774 }
1775
1776 static void xennet_destroy_queues(struct netfront_info *info)
1777 {
1778         unsigned int i;
1779
1780         rtnl_lock();
1781
1782         for (i = 0; i < info->netdev->real_num_tx_queues; i++) {
1783                 struct netfront_queue *queue = &info->queues[i];
1784
1785                 if (netif_running(info->netdev))
1786                         napi_disable(&queue->napi);
1787                 netif_napi_del(&queue->napi);
1788         }
1789
1790         rtnl_unlock();
1791
1792         kfree(info->queues);
1793         info->queues = NULL;
1794 }
1795
1796 static int xennet_create_queues(struct netfront_info *info,
1797                                 unsigned int num_queues)
1798 {
1799         unsigned int i;
1800         int ret;
1801
1802         info->queues = kcalloc(num_queues, sizeof(struct netfront_queue),
1803                                GFP_KERNEL);
1804         if (!info->queues)
1805                 return -ENOMEM;
1806
1807         rtnl_lock();
1808
1809         for (i = 0; i < num_queues; i++) {
1810                 struct netfront_queue *queue = &info->queues[i];
1811
1812                 queue->id = i;
1813                 queue->info = info;
1814
1815                 ret = xennet_init_queue(queue);
1816                 if (ret < 0) {
1817                         dev_warn(&info->netdev->dev,
1818                                  "only created %d queues\n", i);
1819                         num_queues = i;
1820                         break;
1821                 }
1822
1823                 netif_napi_add(queue->info->netdev, &queue->napi,
1824                                xennet_poll, 64);
1825                 if (netif_running(info->netdev))
1826                         napi_enable(&queue->napi);
1827         }
1828
1829         netif_set_real_num_tx_queues(info->netdev, num_queues);
1830
1831         rtnl_unlock();
1832
1833         if (num_queues == 0) {
1834                 dev_err(&info->netdev->dev, "no queues\n");
1835                 return -EINVAL;
1836         }
1837         return 0;
1838 }
1839
1840 /* Common code used when first setting up, and when resuming. */
1841 static int talk_to_netback(struct xenbus_device *dev,
1842                            struct netfront_info *info)
1843 {
1844         const char *message;
1845         struct xenbus_transaction xbt;
1846         int err;
1847         unsigned int feature_split_evtchn;
1848         unsigned int i = 0;
1849         unsigned int max_queues = 0;
1850         struct netfront_queue *queue = NULL;
1851         unsigned int num_queues = 1;
1852
1853         info->netdev->irq = 0;
1854
1855         /* Check if backend supports multiple queues */
1856         err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1857                            "multi-queue-max-queues", "%u", &max_queues);
1858         if (err < 0)
1859                 max_queues = 1;
1860         num_queues = min(max_queues, xennet_max_queues);
1861
1862         /* Check feature-split-event-channels */
1863         err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1864                            "feature-split-event-channels", "%u",
1865                            &feature_split_evtchn);
1866         if (err < 0)
1867                 feature_split_evtchn = 0;
1868
1869         /* Read mac addr. */
1870         err = xen_net_read_mac(dev, info->netdev->dev_addr);
1871         if (err) {
1872                 xenbus_dev_fatal(dev, err, "parsing %s/mac", dev->nodename);
1873                 goto out;
1874         }
1875
1876         if (info->queues)
1877                 xennet_destroy_queues(info);
1878
1879         err = xennet_create_queues(info, num_queues);
1880         if (err < 0)
1881                 goto destroy_ring;
1882
1883         /* Create shared ring, alloc event channel -- for each queue */
1884         for (i = 0; i < num_queues; ++i) {
1885                 queue = &info->queues[i];
1886                 err = setup_netfront(dev, queue, feature_split_evtchn);
1887                 if (err) {
1888                         /* setup_netfront() will tidy up the current
1889                          * queue on error, but we need to clean up
1890                          * those already allocated.
1891                          */
1892                         if (i > 0) {
1893                                 rtnl_lock();
1894                                 netif_set_real_num_tx_queues(info->netdev, i);
1895                                 rtnl_unlock();
1896                                 goto destroy_ring;
1897                         } else {
1898                                 goto out;
1899                         }
1900                 }
1901         }
1902
1903 again:
1904         err = xenbus_transaction_start(&xbt);
1905         if (err) {
1906                 xenbus_dev_fatal(dev, err, "starting transaction");
1907                 goto destroy_ring;
1908         }
1909
1910         if (num_queues == 1) {
1911                 err = write_queue_xenstore_keys(&info->queues[0], &xbt, 0); /* flat */
1912                 if (err)
1913                         goto abort_transaction_no_dev_fatal;
1914         } else {
1915                 /* Write the number of queues */
1916                 err = xenbus_printf(xbt, dev->nodename, "multi-queue-num-queues",
1917                                     "%u", num_queues);
1918                 if (err) {
1919                         message = "writing multi-queue-num-queues";
1920                         goto abort_transaction_no_dev_fatal;
1921                 }
1922
1923                 /* Write the keys for each queue */
1924                 for (i = 0; i < num_queues; ++i) {
1925                         queue = &info->queues[i];
1926                         err = write_queue_xenstore_keys(queue, &xbt, 1); /* hierarchical */
1927                         if (err)
1928                                 goto abort_transaction_no_dev_fatal;
1929                 }
1930         }
1931
1932         /* The remaining keys are not queue-specific */
1933         err = xenbus_printf(xbt, dev->nodename, "request-rx-copy", "%u",
1934                             1);
1935         if (err) {
1936                 message = "writing request-rx-copy";
1937                 goto abort_transaction;
1938         }
1939
1940         err = xenbus_printf(xbt, dev->nodename, "feature-rx-notify", "%d", 1);
1941         if (err) {
1942                 message = "writing feature-rx-notify";
1943                 goto abort_transaction;
1944         }
1945
1946         err = xenbus_printf(xbt, dev->nodename, "feature-sg", "%d", 1);
1947         if (err) {
1948                 message = "writing feature-sg";
1949                 goto abort_transaction;
1950         }
1951
1952         err = xenbus_printf(xbt, dev->nodename, "feature-gso-tcpv4", "%d", 1);
1953         if (err) {
1954                 message = "writing feature-gso-tcpv4";
1955                 goto abort_transaction;
1956         }
1957
1958         err = xenbus_write(xbt, dev->nodename, "feature-gso-tcpv6", "1");
1959         if (err) {
1960                 message = "writing feature-gso-tcpv6";
1961                 goto abort_transaction;
1962         }
1963
1964         err = xenbus_write(xbt, dev->nodename, "feature-ipv6-csum-offload",
1965                            "1");
1966         if (err) {
1967                 message = "writing feature-ipv6-csum-offload";
1968                 goto abort_transaction;
1969         }
1970
1971         err = xenbus_transaction_end(xbt, 0);
1972         if (err) {
1973                 if (err == -EAGAIN)
1974                         goto again;
1975                 xenbus_dev_fatal(dev, err, "completing transaction");
1976                 goto destroy_ring;
1977         }
1978
1979         return 0;
1980
1981  abort_transaction:
1982         xenbus_dev_fatal(dev, err, "%s", message);
1983 abort_transaction_no_dev_fatal:
1984         xenbus_transaction_end(xbt, 1);
1985  destroy_ring:
1986         xennet_disconnect_backend(info);
1987         kfree(info->queues);
1988         info->queues = NULL;
1989         rtnl_lock();
1990         netif_set_real_num_tx_queues(info->netdev, 0);
1991         rtnl_unlock();
1992  out:
1993         return err;
1994 }
1995
1996 static int xennet_connect(struct net_device *dev)
1997 {
1998         struct netfront_info *np = netdev_priv(dev);
1999         unsigned int num_queues = 0;
2000         int err;
2001         unsigned int feature_rx_copy;
2002         unsigned int j = 0;
2003         struct netfront_queue *queue = NULL;
2004
2005         err = xenbus_scanf(XBT_NIL, np->xbdev->otherend,
2006                            "feature-rx-copy", "%u", &feature_rx_copy);
2007         if (err != 1)
2008                 feature_rx_copy = 0;
2009
2010         if (!feature_rx_copy) {
2011                 dev_info(&dev->dev,
2012                          "backend does not support copying receive path\n");
2013                 return -ENODEV;
2014         }
2015
2016         err = talk_to_netback(np->xbdev, np);
2017         if (err)
2018                 return err;
2019
2020         /* talk_to_netback() sets the correct number of queues */
2021         num_queues = dev->real_num_tx_queues;
2022
2023         rtnl_lock();
2024         netdev_update_features(dev);
2025         rtnl_unlock();
2026
2027         /*
2028          * All public and private state should now be sane.  Get
2029          * ready to start sending and receiving packets and give the driver
2030          * domain a kick because we've probably just requeued some
2031          * packets.
2032          */
2033         netif_carrier_on(np->netdev);
2034         for (j = 0; j < num_queues; ++j) {
2035                 queue = &np->queues[j];
2036
2037                 notify_remote_via_irq(queue->tx_irq);
2038                 if (queue->tx_irq != queue->rx_irq)
2039                         notify_remote_via_irq(queue->rx_irq);
2040
2041                 spin_lock_irq(&queue->tx_lock);
2042                 xennet_tx_buf_gc(queue);
2043                 spin_unlock_irq(&queue->tx_lock);
2044
2045                 spin_lock_bh(&queue->rx_lock);
2046                 xennet_alloc_rx_buffers(queue);
2047                 spin_unlock_bh(&queue->rx_lock);
2048         }
2049
2050         return 0;
2051 }
2052
2053 /**
2054  * Callback received when the backend's state changes.
2055  */
2056 static void netback_changed(struct xenbus_device *dev,
2057                             enum xenbus_state backend_state)
2058 {
2059         struct netfront_info *np = dev_get_drvdata(&dev->dev);
2060         struct net_device *netdev = np->netdev;
2061
2062         dev_dbg(&dev->dev, "%s\n", xenbus_strstate(backend_state));
2063
2064         switch (backend_state) {
2065         case XenbusStateInitialising:
2066         case XenbusStateInitialised:
2067         case XenbusStateReconfiguring:
2068         case XenbusStateReconfigured:
2069         case XenbusStateUnknown:
2070                 break;
2071
2072         case XenbusStateInitWait:
2073                 if (dev->state != XenbusStateInitialising)
2074                         break;
2075                 if (xennet_connect(netdev) != 0)
2076                         break;
2077                 xenbus_switch_state(dev, XenbusStateConnected);
2078                 break;
2079
2080         case XenbusStateConnected:
2081                 netdev_notify_peers(netdev);
2082                 break;
2083
2084         case XenbusStateClosed:
2085                 if (dev->state == XenbusStateClosed)
2086                         break;
2087                 /* Missed the backend's CLOSING state -- fallthrough */
2088         case XenbusStateClosing:
2089                 xenbus_frontend_closed(dev);
2090                 break;
2091         }
2092 }
2093
2094 static const struct xennet_stat {
2095         char name[ETH_GSTRING_LEN];
2096         u16 offset;
2097 } xennet_stats[] = {
2098         {
2099                 "rx_gso_checksum_fixup",
2100                 offsetof(struct netfront_info, rx_gso_checksum_fixup)
2101         },
2102 };
2103
2104 static int xennet_get_sset_count(struct net_device *dev, int string_set)
2105 {
2106         switch (string_set) {
2107         case ETH_SS_STATS:
2108                 return ARRAY_SIZE(xennet_stats);
2109         default:
2110                 return -EINVAL;
2111         }
2112 }
2113
2114 static void xennet_get_ethtool_stats(struct net_device *dev,
2115                                      struct ethtool_stats *stats, u64 * data)
2116 {
2117         void *np = netdev_priv(dev);
2118         int i;
2119
2120         for (i = 0; i < ARRAY_SIZE(xennet_stats); i++)
2121                 data[i] = atomic_read((atomic_t *)(np + xennet_stats[i].offset));
2122 }
2123
2124 static void xennet_get_strings(struct net_device *dev, u32 stringset, u8 * data)
2125 {
2126         int i;
2127
2128         switch (stringset) {
2129         case ETH_SS_STATS:
2130                 for (i = 0; i < ARRAY_SIZE(xennet_stats); i++)
2131                         memcpy(data + i * ETH_GSTRING_LEN,
2132                                xennet_stats[i].name, ETH_GSTRING_LEN);
2133                 break;
2134         }
2135 }
2136
2137 static const struct ethtool_ops xennet_ethtool_ops =
2138 {
2139         .get_link = ethtool_op_get_link,
2140
2141         .get_sset_count = xennet_get_sset_count,
2142         .get_ethtool_stats = xennet_get_ethtool_stats,
2143         .get_strings = xennet_get_strings,
2144 };
2145
2146 #ifdef CONFIG_SYSFS
2147 static ssize_t show_rxbuf_min(struct device *dev,
2148                               struct device_attribute *attr, char *buf)
2149 {
2150         struct net_device *netdev = to_net_dev(dev);
2151         struct netfront_info *info = netdev_priv(netdev);
2152         unsigned int num_queues = netdev->real_num_tx_queues;
2153
2154         if (num_queues)
2155                 return sprintf(buf, "%u\n", info->queues[0].rx_min_target);
2156         else
2157                 return sprintf(buf, "%u\n", RX_MIN_TARGET);
2158 }
2159
2160 static ssize_t store_rxbuf_min(struct device *dev,
2161                                struct device_attribute *attr,
2162                                const char *buf, size_t len)
2163 {
2164         struct net_device *netdev = to_net_dev(dev);
2165         struct netfront_info *np = netdev_priv(netdev);
2166         unsigned int num_queues = netdev->real_num_tx_queues;
2167         char *endp;
2168         unsigned long target;
2169         unsigned int i;
2170         struct netfront_queue *queue;
2171
2172         if (!capable(CAP_NET_ADMIN))
2173                 return -EPERM;
2174
2175         target = simple_strtoul(buf, &endp, 0);
2176         if (endp == buf)
2177                 return -EBADMSG;
2178
2179         if (target < RX_MIN_TARGET)
2180                 target = RX_MIN_TARGET;
2181         if (target > RX_MAX_TARGET)
2182                 target = RX_MAX_TARGET;
2183
2184         for (i = 0; i < num_queues; ++i) {
2185                 queue = &np->queues[i];
2186                 spin_lock_bh(&queue->rx_lock);
2187                 if (target > queue->rx_max_target)
2188                         queue->rx_max_target = target;
2189                 queue->rx_min_target = target;
2190                 if (target > queue->rx_target)
2191                         queue->rx_target = target;
2192
2193                 xennet_alloc_rx_buffers(queue);
2194
2195                 spin_unlock_bh(&queue->rx_lock);
2196         }
2197         return len;
2198 }
2199
2200 static ssize_t show_rxbuf_max(struct device *dev,
2201                               struct device_attribute *attr, char *buf)
2202 {
2203         struct net_device *netdev = to_net_dev(dev);
2204         struct netfront_info *info = netdev_priv(netdev);
2205         unsigned int num_queues = netdev->real_num_tx_queues;
2206
2207         if (num_queues)
2208                 return sprintf(buf, "%u\n", info->queues[0].rx_max_target);
2209         else
2210                 return sprintf(buf, "%u\n", RX_MAX_TARGET);
2211 }
2212
2213 static ssize_t store_rxbuf_max(struct device *dev,
2214                                struct device_attribute *attr,
2215                                const char *buf, size_t len)
2216 {
2217         struct net_device *netdev = to_net_dev(dev);
2218         struct netfront_info *np = netdev_priv(netdev);
2219         unsigned int num_queues = netdev->real_num_tx_queues;
2220         char *endp;
2221         unsigned long target;
2222         unsigned int i = 0;
2223         struct netfront_queue *queue = NULL;
2224
2225         if (!capable(CAP_NET_ADMIN))
2226                 return -EPERM;
2227
2228         target = simple_strtoul(buf, &endp, 0);
2229         if (endp == buf)
2230                 return -EBADMSG;
2231
2232         if (target < RX_MIN_TARGET)
2233                 target = RX_MIN_TARGET;
2234         if (target > RX_MAX_TARGET)
2235                 target = RX_MAX_TARGET;
2236
2237         for (i = 0; i < num_queues; ++i) {
2238                 queue = &np->queues[i];
2239                 spin_lock_bh(&queue->rx_lock);
2240                 if (target < queue->rx_min_target)
2241                         queue->rx_min_target = target;
2242                 queue->rx_max_target = target;
2243                 if (target < queue->rx_target)
2244                         queue->rx_target = target;
2245
2246                 xennet_alloc_rx_buffers(queue);
2247
2248                 spin_unlock_bh(&queue->rx_lock);
2249         }
2250         return len;
2251 }
2252
2253 static ssize_t show_rxbuf_cur(struct device *dev,
2254                               struct device_attribute *attr, char *buf)
2255 {
2256         struct net_device *netdev = to_net_dev(dev);
2257         struct netfront_info *info = netdev_priv(netdev);
2258         unsigned int num_queues = netdev->real_num_tx_queues;
2259
2260         if (num_queues)
2261                 return sprintf(buf, "%u\n", info->queues[0].rx_target);
2262         else
2263                 return sprintf(buf, "0\n");
2264 }
2265
2266 static struct device_attribute xennet_attrs[] = {
2267         __ATTR(rxbuf_min, S_IRUGO|S_IWUSR, show_rxbuf_min, store_rxbuf_min),
2268         __ATTR(rxbuf_max, S_IRUGO|S_IWUSR, show_rxbuf_max, store_rxbuf_max),
2269         __ATTR(rxbuf_cur, S_IRUGO, show_rxbuf_cur, NULL),
2270 };
2271
2272 static int xennet_sysfs_addif(struct net_device *netdev)
2273 {
2274         int i;
2275         int err;
2276
2277         for (i = 0; i < ARRAY_SIZE(xennet_attrs); i++) {
2278                 err = device_create_file(&netdev->dev,
2279                                            &xennet_attrs[i]);
2280                 if (err)
2281                         goto fail;
2282         }
2283         return 0;
2284
2285  fail:
2286         while (--i >= 0)
2287                 device_remove_file(&netdev->dev, &xennet_attrs[i]);
2288         return err;
2289 }
2290
2291 static void xennet_sysfs_delif(struct net_device *netdev)
2292 {
2293         int i;
2294
2295         for (i = 0; i < ARRAY_SIZE(xennet_attrs); i++)
2296                 device_remove_file(&netdev->dev, &xennet_attrs[i]);
2297 }
2298
2299 #endif /* CONFIG_SYSFS */
2300
2301 static int xennet_remove(struct xenbus_device *dev)
2302 {
2303         struct netfront_info *info = dev_get_drvdata(&dev->dev);
2304         unsigned int num_queues = info->netdev->real_num_tx_queues;
2305         struct netfront_queue *queue = NULL;
2306         unsigned int i = 0;
2307
2308         dev_dbg(&dev->dev, "%s\n", dev->nodename);
2309
2310         xennet_disconnect_backend(info);
2311
2312         xennet_sysfs_delif(info->netdev);
2313
2314         unregister_netdev(info->netdev);
2315
2316         for (i = 0; i < num_queues; ++i) {
2317                 queue = &info->queues[i];
2318                 del_timer_sync(&queue->rx_refill_timer);
2319         }
2320
2321         if (num_queues) {
2322                 kfree(info->queues);
2323                 info->queues = NULL;
2324         }
2325
2326         free_percpu(info->stats);
2327
2328         free_netdev(info->netdev);
2329
2330         return 0;
2331 }
2332
2333 static const struct xenbus_device_id netfront_ids[] = {
2334         { "vif" },
2335         { "" }
2336 };
2337
2338 static struct xenbus_driver netfront_driver = {
2339         .ids = netfront_ids,
2340         .probe = netfront_probe,
2341         .remove = xennet_remove,
2342         .resume = netfront_resume,
2343         .otherend_changed = netback_changed,
2344 };
2345
2346 static int __init netif_init(void)
2347 {
2348         if (!xen_domain())
2349                 return -ENODEV;
2350
2351         if (!xen_has_pv_nic_devices())
2352                 return -ENODEV;
2353
2354         pr_info("Initialising Xen virtual ethernet driver\n");
2355
2356         /* Allow as many queues as there are CPUs, by default */
2357         xennet_max_queues = num_online_cpus();
2358
2359         return xenbus_register_frontend(&netfront_driver);
2360 }
2361 module_init(netif_init);
2362
2363
2364 static void __exit netif_exit(void)
2365 {
2366         xenbus_unregister_driver(&netfront_driver);
2367 }
2368 module_exit(netif_exit);
2369
2370 MODULE_DESCRIPTION("Xen virtual network device frontend");
2371 MODULE_LICENSE("GPL");
2372 MODULE_ALIAS("xen:vif");
2373 MODULE_ALIAS("xennet");