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