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