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