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