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