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