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