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