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