- Update Xen patches to 3.3-rc5 and c/s 1157.
[linux-flexiantxendom0-3.2.10.git] / drivers / xen / netfront / 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  * Copyright (C) 2007 Solarflare Communications, Inc.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License version 2
10  * as published by the Free Software Foundation; or, when distributed
11  * separately from the Linux kernel or incorporated into other
12  * software packages, subject to the following license:
13  *
14  * Permission is hereby granted, free of charge, to any person obtaining a copy
15  * of this source file (the "Software"), to deal in the Software without
16  * restriction, including without limitation the rights to use, copy, modify,
17  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
18  * and to permit persons to whom the Software is furnished to do so, subject to
19  * the following conditions:
20  *
21  * The above copyright notice and this permission notice shall be included in
22  * all copies or substantial portions of the Software.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
30  * IN THE SOFTWARE.
31  */
32
33 #include <linux/module.h>
34 #include <linux/version.h>
35 #include <linux/kernel.h>
36 #include <linux/sched.h>
37 #include <linux/slab.h>
38 #include <linux/string.h>
39 #include <linux/errno.h>
40 #include <linux/netdevice.h>
41 #include <linux/inetdevice.h>
42 #include <linux/etherdevice.h>
43 #include <linux/skbuff.h>
44 #include <linux/init.h>
45 #include <linux/bitops.h>
46 #include <linux/ethtool.h>
47 #include <linux/in.h>
48 #include <linux/if_ether.h>
49 #include <linux/io.h>
50 #include <linux/moduleparam.h>
51 #include <net/sock.h>
52 #include <net/pkt_sched.h>
53 #include <net/route.h>
54 #include <asm/uaccess.h>
55 #include <xen/evtchn.h>
56 #include <xen/xenbus.h>
57 #include <xen/interface/io/netif.h>
58 #include <xen/interface/memory.h>
59 #include <xen/balloon.h>
60 #include <asm/page.h>
61 #include <asm/maddr.h>
62 #include <asm/uaccess.h>
63 #include <xen/interface/grant_table.h>
64 #include <xen/gnttab.h>
65 #include <xen/net-util.h>
66
67 struct netfront_cb {
68         struct page *page;
69         unsigned offset;
70 };
71
72 #define NETFRONT_SKB_CB(skb)    ((struct netfront_cb *)((skb)->cb))
73
74 #include "netfront.h"
75
76 /*
77  * Mutually-exclusive module options to select receive data path:
78  *  rx_copy : Packets are copied by network backend into local memory
79  *  rx_flip : Page containing packet data is transferred to our ownership
80  * For fully-virtualised guests there is no option - copying must be used.
81  * For paravirtualised guests, flipping is the default.
82  */
83 #ifdef CONFIG_XEN
84 static bool MODPARM_rx_copy;
85 module_param_named(rx_copy, MODPARM_rx_copy, bool, 0);
86 MODULE_PARM_DESC(rx_copy, "Copy packets from network card (rather than flip)");
87 static bool MODPARM_rx_flip;
88 module_param_named(rx_flip, MODPARM_rx_flip, bool, 0);
89 MODULE_PARM_DESC(rx_flip, "Flip packets from network card (rather than copy)");
90 #else
91 # define MODPARM_rx_copy true
92 # define MODPARM_rx_flip false
93 #endif
94
95 #define RX_COPY_THRESHOLD 256
96
97 /* If we don't have GSO, fake things up so that we never try to use it. */
98 #if defined(NETIF_F_GSO)
99 #define HAVE_GSO                        1
100 #define HAVE_TSO                        1 /* TSO is a subset of GSO */
101 #define HAVE_CSUM_OFFLOAD               1
102 static inline void dev_disable_gso_features(struct net_device *dev)
103 {
104         /* Turn off all GSO bits except ROBUST. */
105         dev->features &= ~NETIF_F_GSO_MASK;
106         dev->features |= NETIF_F_GSO_ROBUST;
107 }
108 #elif defined(NETIF_F_TSO)
109 #define HAVE_GSO                       0
110 #define HAVE_TSO                       1
111
112 /* Some older kernels cannot cope with incorrect checksums,
113  * particularly in netfilter. I'm not sure there is 100% correlation
114  * with the presence of NETIF_F_TSO but it appears to be a good first
115  * approximiation.
116  */
117 #define HAVE_CSUM_OFFLOAD              0
118
119 #define gso_size tso_size
120 #define gso_segs tso_segs
121 static inline void dev_disable_gso_features(struct net_device *dev)
122 {
123        /* Turn off all TSO bits. */
124        dev->features &= ~NETIF_F_TSO;
125 }
126 static inline int skb_is_gso(const struct sk_buff *skb)
127 {
128         return skb_shinfo(skb)->tso_size;
129 }
130 static inline int skb_gso_ok(struct sk_buff *skb, int features)
131 {
132         return (features & NETIF_F_TSO);
133 }
134
135 #define netif_skb_features(skb) ((skb)->dev->features)
136 static inline int netif_needs_gso(struct sk_buff *skb, int features)
137 {
138         return skb_is_gso(skb) &&
139                (!skb_gso_ok(skb, features) ||
140                 unlikely(skb->ip_summed != CHECKSUM_PARTIAL));
141 }
142 #else
143 #define HAVE_GSO                        0
144 #define HAVE_TSO                        0
145 #define HAVE_CSUM_OFFLOAD               0
146 #define netif_needs_gso(skb, feat)      0
147 #define dev_disable_gso_features(dev)   ((void)0)
148 #define ethtool_op_set_tso(dev, data)   (-ENOSYS)
149 #endif
150
151 #define GRANT_INVALID_REF       0
152
153 struct netfront_rx_info {
154         struct netif_rx_response rx;
155         struct netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX - 1];
156 };
157
158 /*
159  * Implement our own carrier flag: the network stack's version causes delays
160  * when the carrier is re-enabled (in particular, dev_activate() may not
161  * immediately be called, which can cause packet loss).
162  */
163 #define netfront_carrier_on(netif)      ((netif)->carrier = 1)
164 #define netfront_carrier_off(netif)     ((netif)->carrier = 0)
165 #define netfront_carrier_ok(netif)      ((netif)->carrier)
166
167 /*
168  * Access macros for acquiring freeing slots in tx_skbs[].
169  */
170
171 static inline void add_id_to_freelist(struct sk_buff **list, unsigned short id)
172 {
173         list[id] = list[0];
174         list[0]  = (void *)(unsigned long)id;
175 }
176
177 static inline unsigned short get_id_from_freelist(struct sk_buff **list)
178 {
179         unsigned int id = (unsigned int)(unsigned long)list[0];
180         list[0] = list[id];
181         return id;
182 }
183
184 static inline int xennet_rxidx(RING_IDX idx)
185 {
186         return idx & (NET_RX_RING_SIZE - 1);
187 }
188
189 static inline struct sk_buff *xennet_get_rx_skb(struct netfront_info *np,
190                                                 RING_IDX ri)
191 {
192         int i = xennet_rxidx(ri);
193         struct sk_buff *skb = np->rx_skbs[i];
194         np->rx_skbs[i] = NULL;
195         return skb;
196 }
197
198 static inline grant_ref_t xennet_get_rx_ref(struct netfront_info *np,
199                                             RING_IDX ri)
200 {
201         int i = xennet_rxidx(ri);
202         grant_ref_t ref = np->grant_rx_ref[i];
203         np->grant_rx_ref[i] = GRANT_INVALID_REF;
204         return ref;
205 }
206
207 #define DPRINTK(fmt, args...)                           \
208         pr_debug("netfront (%s:%d) " fmt,               \
209                  __FUNCTION__, __LINE__, ##args)
210 #define IPRINTK(fmt, args...) pr_info("netfront: " fmt, ##args)
211 #define WPRINTK(fmt, args...) pr_warning("netfront: " fmt, ##args)
212
213 static int setup_device(struct xenbus_device *, struct netfront_info *);
214 static struct net_device *create_netdev(struct xenbus_device *);
215
216 static void end_access(int, void *);
217 static void netif_release_rings(struct netfront_info *);
218 static void netif_disconnect_backend(struct netfront_info *);
219
220 static int network_connect(struct net_device *);
221 static void network_tx_buf_gc(struct net_device *);
222 static void network_alloc_rx_buffers(struct net_device *);
223
224 static irqreturn_t netif_int(int irq, void *dev_id);
225
226 #ifdef CONFIG_SYSFS
227 static int xennet_sysfs_addif(struct net_device *netdev);
228 static void xennet_sysfs_delif(struct net_device *netdev);
229 #else /* !CONFIG_SYSFS */
230 #define xennet_sysfs_addif(dev) (0)
231 #define xennet_sysfs_delif(dev) do { } while(0)
232 #endif
233
234 static inline bool xennet_can_sg(struct net_device *dev)
235 {
236         return dev->features & NETIF_F_SG;
237 }
238
239 /*
240  * Work around net.ipv4.conf.*.arp_notify not being enabled by default.
241  */
242 static void __devinit netfront_enable_arp_notify(struct netfront_info *info)
243 {
244 #ifdef CONFIG_INET
245         struct in_device *in_dev;
246
247         rtnl_lock();
248         in_dev = __in_dev_get_rtnl(info->netdev);
249         if (in_dev && !IN_DEV_CONF_GET(in_dev, ARP_NOTIFY))
250                 IN_DEV_CONF_SET(in_dev, ARP_NOTIFY, 1);
251         rtnl_unlock();
252         if (!in_dev)
253                 printk(KERN_WARNING "Cannot enable ARP notification on %s\n",
254                        info->xbdev->nodename);
255 #endif
256 }
257
258 /**
259  * Entry point to this code when a new device is created.  Allocate the basic
260  * structures and the ring buffers for communication with the backend, and
261  * inform the backend of the appropriate details for those.
262  */
263 static int __devinit netfront_probe(struct xenbus_device *dev,
264                                     const struct xenbus_device_id *id)
265 {
266         int err;
267         struct net_device *netdev;
268         struct netfront_info *info;
269
270         netdev = create_netdev(dev);
271         if (IS_ERR(netdev)) {
272                 err = PTR_ERR(netdev);
273                 xenbus_dev_fatal(dev, err, "creating netdev");
274                 return err;
275         }
276
277         info = netdev_priv(netdev);
278         dev_set_drvdata(&dev->dev, info);
279
280         err = register_netdev(info->netdev);
281         if (err) {
282                 pr_warning("%s: register_netdev err=%d\n",
283                            __FUNCTION__, err);
284                 goto fail;
285         }
286
287         netfront_enable_arp_notify(info);
288
289         err = xennet_sysfs_addif(info->netdev);
290         if (err) {
291                 unregister_netdev(info->netdev);
292                 pr_warning("%s: add sysfs failed err=%d\n",
293                            __FUNCTION__, err);
294                 goto fail;
295         }
296
297         return 0;
298
299  fail:
300         free_netdev(netdev);
301         dev_set_drvdata(&dev->dev, NULL);
302         return err;
303 }
304
305 static int __devexit netfront_remove(struct xenbus_device *dev)
306 {
307         struct netfront_info *info = dev_get_drvdata(&dev->dev);
308
309         DPRINTK("%s\n", dev->nodename);
310
311         netfront_accelerator_call_remove(info, dev);
312
313         netif_disconnect_backend(info);
314
315         del_timer_sync(&info->rx_refill_timer);
316
317         xennet_sysfs_delif(info->netdev);
318
319         unregister_netdev(info->netdev);
320
321         free_percpu(info->stats);
322
323         free_netdev(info->netdev);
324
325         return 0;
326 }
327
328
329 static int netfront_suspend(struct xenbus_device *dev)
330 {
331         struct netfront_info *info = dev_get_drvdata(&dev->dev);
332         return netfront_accelerator_suspend(info, dev);
333 }
334
335
336 static int netfront_suspend_cancel(struct xenbus_device *dev)
337 {
338         struct netfront_info *info = dev_get_drvdata(&dev->dev);
339         return netfront_accelerator_suspend_cancel(info, dev);
340 }
341
342
343 /**
344  * We are reconnecting to the backend, due to a suspend/resume, or a backend
345  * driver restart.  We tear down our netif structure and recreate it, but
346  * leave the device-layer structures intact so that this is transparent to the
347  * rest of the kernel.
348  */
349 static int netfront_resume(struct xenbus_device *dev)
350 {
351         struct netfront_info *info = dev_get_drvdata(&dev->dev);
352
353         DPRINTK("%s\n", dev->nodename);
354
355         netfront_accelerator_resume(info, dev);
356
357         netif_disconnect_backend(info);
358         return 0;
359 }
360
361 static int xen_net_read_mac(struct xenbus_device *dev, u8 mac[])
362 {
363         char *s, *e, *macstr;
364         int i;
365
366         macstr = s = xenbus_read(XBT_NIL, dev->nodename, "mac", NULL);
367         if (IS_ERR(macstr))
368                 return PTR_ERR(macstr);
369
370         for (i = 0; i < ETH_ALEN; i++) {
371                 mac[i] = simple_strtoul(s, &e, 16);
372                 if ((s == e) || (*e != ((i == ETH_ALEN-1) ? '\0' : ':'))) {
373                         kfree(macstr);
374                         return -ENOENT;
375                 }
376                 s = e+1;
377         }
378
379         kfree(macstr);
380         return 0;
381 }
382
383 /* Common code used when first setting up, and when resuming. */
384 static int talk_to_backend(struct xenbus_device *dev,
385                            struct netfront_info *info)
386 {
387         const char *message;
388         struct xenbus_transaction xbt;
389         int err;
390
391         /* Read mac only in the first setup. */
392         if (!is_valid_ether_addr(info->mac)) {
393                 err = xen_net_read_mac(dev, info->mac);
394                 if (err) {
395                         xenbus_dev_fatal(dev, err, "parsing %s/mac",
396                                          dev->nodename);
397                         goto out;
398                 }
399         }
400
401         /* Create shared ring, alloc event channel. */
402         err = setup_device(dev, info);
403         if (err)
404                 goto out;
405
406         /* This will load an accelerator if one is configured when the
407          * watch fires */
408         netfront_accelerator_add_watch(info);
409
410 again:
411         err = xenbus_transaction_start(&xbt);
412         if (err) {
413                 xenbus_dev_fatal(dev, err, "starting transaction");
414                 goto destroy_ring;
415         }
416
417         err = xenbus_printf(xbt, dev->nodename, "tx-ring-ref","%u",
418                             info->tx_ring_ref);
419         if (err) {
420                 message = "writing tx ring-ref";
421                 goto abort_transaction;
422         }
423         err = xenbus_printf(xbt, dev->nodename, "rx-ring-ref","%u",
424                             info->rx_ring_ref);
425         if (err) {
426                 message = "writing rx ring-ref";
427                 goto abort_transaction;
428         }
429         err = xenbus_printf(xbt, dev->nodename,
430                             "event-channel", "%u",
431                             irq_to_evtchn_port(info->irq));
432         if (err) {
433                 message = "writing event-channel";
434                 goto abort_transaction;
435         }
436
437         err = xenbus_printf(xbt, dev->nodename, "request-rx-copy", "%u",
438                             info->copying_receiver);
439         if (err) {
440                 message = "writing request-rx-copy";
441                 goto abort_transaction;
442         }
443
444         err = xenbus_printf(xbt, dev->nodename, "feature-rx-notify", "%d", 1);
445         if (err) {
446                 message = "writing feature-rx-notify";
447                 goto abort_transaction;
448         }
449
450         err = xenbus_printf(xbt, dev->nodename, "feature-no-csum-offload",
451                             "%d", !HAVE_CSUM_OFFLOAD);
452         if (err) {
453                 message = "writing feature-no-csum-offload";
454                 goto abort_transaction;
455         }
456
457         err = xenbus_printf(xbt, dev->nodename, "feature-sg", "%d", 1);
458         if (err) {
459                 message = "writing feature-sg";
460                 goto abort_transaction;
461         }
462
463         err = xenbus_printf(xbt, dev->nodename, "feature-gso-tcpv4", "%d",
464                             HAVE_TSO);
465         if (err) {
466                 message = "writing feature-gso-tcpv4";
467                 goto abort_transaction;
468         }
469
470         err = xenbus_transaction_end(xbt, 0);
471         if (err) {
472                 if (err == -EAGAIN)
473                         goto again;
474                 xenbus_dev_fatal(dev, err, "completing transaction");
475                 goto destroy_ring;
476         }
477
478         return 0;
479
480  abort_transaction:
481         xenbus_transaction_end(xbt, 1);
482         xenbus_dev_fatal(dev, err, "%s", message);
483  destroy_ring:
484         netfront_accelerator_call_remove(info, dev);
485         netif_disconnect_backend(info);
486  out:
487         return err;
488 }
489
490 static int setup_device(struct xenbus_device *dev, struct netfront_info *info)
491 {
492         struct netif_tx_sring *txs;
493         struct netif_rx_sring *rxs;
494         int err;
495         struct net_device *netdev = info->netdev;
496
497         info->tx_ring_ref = GRANT_INVALID_REF;
498         info->rx_ring_ref = GRANT_INVALID_REF;
499         info->rx.sring = NULL;
500         info->tx.sring = NULL;
501         info->irq = 0;
502
503         txs = (struct netif_tx_sring *)get_zeroed_page(GFP_NOIO | __GFP_HIGH);
504         if (!txs) {
505                 err = -ENOMEM;
506                 xenbus_dev_fatal(dev, err, "allocating tx ring page");
507                 goto fail;
508         }
509         SHARED_RING_INIT(txs);
510         FRONT_RING_INIT(&info->tx, txs, PAGE_SIZE);
511
512         err = xenbus_grant_ring(dev, virt_to_mfn(txs));
513         if (err < 0) {
514                 free_page((unsigned long)txs);
515                 goto fail;
516         }
517         info->tx_ring_ref = err;
518
519         rxs = (struct netif_rx_sring *)get_zeroed_page(GFP_NOIO | __GFP_HIGH);
520         if (!rxs) {
521                 err = -ENOMEM;
522                 xenbus_dev_fatal(dev, err, "allocating rx ring page");
523                 goto fail;
524         }
525         SHARED_RING_INIT(rxs);
526         FRONT_RING_INIT(&info->rx, rxs, PAGE_SIZE);
527
528         err = xenbus_grant_ring(dev, virt_to_mfn(rxs));
529         if (err < 0) {
530                 free_page((unsigned long)rxs);
531                 goto fail;
532         }
533         info->rx_ring_ref = err;
534
535         memcpy(netdev->dev_addr, info->mac, ETH_ALEN);
536
537         err = bind_listening_port_to_irqhandler(
538                 dev->otherend_id, netif_int, 0, netdev->name, netdev);
539         if (err < 0)
540                 goto fail;
541         info->irq = err;
542
543         return 0;
544
545  fail:
546         netif_release_rings(info);
547         return err;
548 }
549
550 /**
551  * Callback received when the backend's state changes.
552  */
553 static void backend_changed(struct xenbus_device *dev,
554                             enum xenbus_state backend_state)
555 {
556         struct netfront_info *np = dev_get_drvdata(&dev->dev);
557         struct net_device *netdev = np->netdev;
558
559         DPRINTK("%s\n", xenbus_strstate(backend_state));
560
561         switch (backend_state) {
562         case XenbusStateInitialising:
563         case XenbusStateInitialised:
564         case XenbusStateReconfiguring:
565         case XenbusStateReconfigured:
566         case XenbusStateUnknown:
567         case XenbusStateClosed:
568                 break;
569
570         case XenbusStateInitWait:
571                 if (dev->state != XenbusStateInitialising)
572                         break;
573                 if (network_connect(netdev) != 0)
574                         break;
575                 xenbus_switch_state(dev, XenbusStateConnected);
576                 break;
577
578         case XenbusStateConnected:
579                 netif_notify_peers(netdev);
580                 break;
581
582         case XenbusStateClosing:
583                 xenbus_frontend_closed(dev);
584                 break;
585         }
586 }
587
588 static inline int netfront_tx_slot_available(struct netfront_info *np)
589 {
590         return ((np->tx.req_prod_pvt - np->tx.rsp_cons) <
591                 (TX_MAX_TARGET - MAX_SKB_FRAGS - 2));
592 }
593
594
595 static inline void network_maybe_wake_tx(struct net_device *dev)
596 {
597         struct netfront_info *np = netdev_priv(dev);
598
599         if (unlikely(netif_queue_stopped(dev)) &&
600             netfront_tx_slot_available(np) &&
601             likely(netif_running(dev)) &&
602             netfront_check_accelerator_queue_ready(dev, np))
603                 netif_wake_queue(dev);
604 }
605
606
607 int netfront_check_queue_ready(struct net_device *dev)
608 {
609         struct netfront_info *np = netdev_priv(dev);
610
611         return unlikely(netif_queue_stopped(dev)) &&
612                 netfront_tx_slot_available(np) &&
613                 likely(netif_running(dev));
614 }
615 EXPORT_SYMBOL(netfront_check_queue_ready);
616
617 static int network_open(struct net_device *dev)
618 {
619         struct netfront_info *np = netdev_priv(dev);
620
621         napi_enable(&np->napi);
622
623         spin_lock_bh(&np->rx_lock);
624         if (netfront_carrier_ok(np)) {
625                 network_alloc_rx_buffers(dev);
626                 np->rx.sring->rsp_event = np->rx.rsp_cons + 1;
627                 if (RING_HAS_UNCONSUMED_RESPONSES(&np->rx)){
628                         netfront_accelerator_call_stop_napi_irq(np, dev);
629
630                         napi_schedule(&np->napi);
631                 }
632         }
633         spin_unlock_bh(&np->rx_lock);
634
635         netif_start_queue(dev);
636
637         return 0;
638 }
639
640 static void network_tx_buf_gc(struct net_device *dev)
641 {
642         RING_IDX cons, prod;
643         unsigned short id;
644         struct netfront_info *np = netdev_priv(dev);
645         struct sk_buff *skb;
646
647         BUG_ON(!netfront_carrier_ok(np));
648
649         do {
650                 prod = np->tx.sring->rsp_prod;
651                 rmb(); /* Ensure we see responses up to 'rp'. */
652
653                 for (cons = np->tx.rsp_cons; cons != prod; cons++) {
654                         struct netif_tx_response *txrsp;
655
656                         txrsp = RING_GET_RESPONSE(&np->tx, cons);
657                         if (txrsp->status == XEN_NETIF_RSP_NULL)
658                                 continue;
659
660                         id  = txrsp->id;
661                         skb = np->tx_skbs[id];
662                         if (unlikely(gnttab_query_foreign_access(
663                                 np->grant_tx_ref[id]) != 0)) {
664                                 pr_alert("network_tx_buf_gc: grant still"
665                                          " in use by backend domain\n");
666                                 BUG();
667                         }
668                         gnttab_end_foreign_access_ref(np->grant_tx_ref[id]);
669                         gnttab_release_grant_reference(
670                                 &np->gref_tx_head, np->grant_tx_ref[id]);
671                         np->grant_tx_ref[id] = GRANT_INVALID_REF;
672                         add_id_to_freelist(np->tx_skbs, id);
673                         dev_kfree_skb_irq(skb);
674                 }
675
676                 np->tx.rsp_cons = prod;
677
678                 /*
679                  * Set a new event, then check for race with update of tx_cons.
680                  * Note that it is essential to schedule a callback, no matter
681                  * how few buffers are pending. Even if there is space in the
682                  * transmit ring, higher layers may be blocked because too much
683                  * data is outstanding: in such cases notification from Xen is
684                  * likely to be the only kick that we'll get.
685                  */
686                 np->tx.sring->rsp_event =
687                         prod + ((np->tx.sring->req_prod - prod) >> 1) + 1;
688                 mb();
689         } while ((cons == prod) && (prod != np->tx.sring->rsp_prod));
690
691         network_maybe_wake_tx(dev);
692 }
693
694 static void rx_refill_timeout(unsigned long data)
695 {
696         struct net_device *dev = (struct net_device *)data;
697         struct netfront_info *np = netdev_priv(dev);
698
699         netfront_accelerator_call_stop_napi_irq(np, dev);
700
701         napi_schedule(&np->napi);
702 }
703
704 static void network_alloc_rx_buffers(struct net_device *dev)
705 {
706         unsigned short id;
707         struct netfront_info *np = netdev_priv(dev);
708         struct sk_buff *skb;
709         struct page *page;
710         int i, batch_target, notify;
711         RING_IDX req_prod = np->rx.req_prod_pvt;
712         struct xen_memory_reservation reservation;
713         grant_ref_t ref;
714         unsigned long pfn;
715         void *vaddr;
716         int nr_flips;
717         netif_rx_request_t *req;
718
719         if (unlikely(!netfront_carrier_ok(np)))
720                 return;
721
722         /*
723          * Allocate skbuffs greedily, even though we batch updates to the
724          * receive ring. This creates a less bursty demand on the memory
725          * allocator, so should reduce the chance of failed allocation requests
726          * both for ourself and for other kernel subsystems.
727          */
728         batch_target = np->rx_target - (req_prod - np->rx.rsp_cons);
729         for (i = skb_queue_len(&np->rx_batch); i < batch_target; i++) {
730                 /*
731                  * Allocate an skb and a page. Do not use __dev_alloc_skb as
732                  * that will allocate page-sized buffers which is not
733                  * necessary here.
734                  * 16 bytes added as necessary headroom for netif_receive_skb.
735                  */
736                 skb = alloc_skb(RX_COPY_THRESHOLD + 16 + NET_IP_ALIGN,
737                                 GFP_ATOMIC | __GFP_NOWARN);
738                 if (unlikely(!skb))
739                         goto no_skb;
740
741                 page = alloc_page(GFP_ATOMIC | __GFP_NOWARN);
742                 if (!page) {
743                         kfree_skb(skb);
744 no_skb:
745                         /* Any skbuffs queued for refill? Force them out. */
746                         if (i != 0)
747                                 goto refill;
748                         /* Could not allocate any skbuffs. Try again later. */
749                         mod_timer(&np->rx_refill_timer,
750                                   jiffies + (HZ/10));
751                         break;
752                 }
753
754                 skb_reserve(skb, 16 + NET_IP_ALIGN); /* mimic dev_alloc_skb() */
755                 __skb_fill_page_desc(skb, 0, page, 0, 0);
756                 skb_shinfo(skb)->nr_frags = 1;
757                 __skb_queue_tail(&np->rx_batch, skb);
758         }
759
760         /* Is the batch large enough to be worthwhile? */
761         if (i < (np->rx_target/2)) {
762                 if (req_prod > np->rx.sring->req_prod)
763                         goto push;
764                 return;
765         }
766
767         /* Adjust our fill target if we risked running out of buffers. */
768         if (((req_prod - np->rx.sring->rsp_prod) < (np->rx_target / 4)) &&
769             ((np->rx_target *= 2) > np->rx_max_target))
770                 np->rx_target = np->rx_max_target;
771
772  refill:
773         for (nr_flips = i = 0; ; i++) {
774                 if ((skb = __skb_dequeue(&np->rx_batch)) == NULL)
775                         break;
776
777                 skb->dev = dev;
778
779                 id = xennet_rxidx(req_prod + i);
780
781                 BUG_ON(np->rx_skbs[id]);
782                 np->rx_skbs[id] = skb;
783
784                 ref = gnttab_claim_grant_reference(&np->gref_rx_head);
785                 BUG_ON((signed short)ref < 0);
786                 np->grant_rx_ref[id] = ref;
787
788                 page = skb_frag_page(skb_shinfo(skb)->frags);
789                 pfn = page_to_pfn(page);
790                 vaddr = page_address(page);
791
792                 req = RING_GET_REQUEST(&np->rx, req_prod + i);
793                 if (!np->copying_receiver) {
794                         gnttab_grant_foreign_transfer_ref(ref,
795                                                           np->xbdev->otherend_id,
796                                                           pfn);
797                         np->rx_pfn_array[nr_flips] = pfn_to_mfn(pfn);
798                         if (!xen_feature(XENFEAT_auto_translated_physmap)) {
799                                 /* Remove this page before passing
800                                  * back to Xen. */
801                                 set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
802                                 MULTI_update_va_mapping(np->rx_mcl+i,
803                                                         (unsigned long)vaddr,
804                                                         __pte(0), 0);
805                         }
806                         nr_flips++;
807                 } else {
808                         gnttab_grant_foreign_access_ref(ref,
809                                                         np->xbdev->otherend_id,
810                                                         pfn_to_mfn(pfn),
811                                                         0);
812                 }
813
814                 req->id = id;
815                 req->gref = ref;
816         }
817
818         if ( nr_flips != 0 ) {
819                 /* Tell the ballon driver what is going on. */
820                 balloon_update_driver_allowance(i);
821
822                 set_xen_guest_handle(reservation.extent_start,
823                                      np->rx_pfn_array);
824                 reservation.nr_extents   = nr_flips;
825                 reservation.extent_order = 0;
826                 reservation.address_bits = 0;
827                 reservation.domid        = DOMID_SELF;
828
829                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
830                         /* After all PTEs have been zapped, flush the TLB. */
831                         np->rx_mcl[i-1].args[MULTI_UVMFLAGS_INDEX] =
832                                 UVMF_TLB_FLUSH|UVMF_ALL;
833
834                         /* Give away a batch of pages. */
835                         np->rx_mcl[i].op = __HYPERVISOR_memory_op;
836                         np->rx_mcl[i].args[0] = XENMEM_decrease_reservation;
837                         np->rx_mcl[i].args[1] = (unsigned long)&reservation;
838
839                         /* Zap PTEs and give away pages in one big
840                          * multicall. */
841                         if (unlikely(HYPERVISOR_multicall(np->rx_mcl, i+1)))
842                                 BUG();
843
844                         /* Check return status of HYPERVISOR_memory_op(). */
845                         if (unlikely(np->rx_mcl[i].result != i))
846                                 panic("Unable to reduce memory reservation\n");
847                         while (nr_flips--)
848                                 BUG_ON(np->rx_mcl[nr_flips].result);
849                 } else {
850                         if (HYPERVISOR_memory_op(XENMEM_decrease_reservation,
851                                                  &reservation) != i)
852                                 panic("Unable to reduce memory reservation\n");
853                 }
854         } else {
855                 wmb();
856         }
857
858         /* Above is a suitable barrier to ensure backend will see requests. */
859         np->rx.req_prod_pvt = req_prod + i;
860  push:
861         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&np->rx, notify);
862         if (notify)
863                 notify_remote_via_irq(np->irq);
864 }
865
866 static void xennet_make_frags(struct sk_buff *skb, struct net_device *dev,
867                               struct netif_tx_request *tx)
868 {
869         struct netfront_info *np = netdev_priv(dev);
870         char *data = skb->data;
871         unsigned long mfn;
872         RING_IDX prod = np->tx.req_prod_pvt;
873         int frags = skb_shinfo(skb)->nr_frags;
874         unsigned int offset = offset_in_page(data);
875         unsigned int len = skb_headlen(skb);
876         unsigned int id;
877         grant_ref_t ref;
878         int i;
879
880         while (len > PAGE_SIZE - offset) {
881                 tx->size = PAGE_SIZE - offset;
882                 tx->flags |= XEN_NETTXF_more_data;
883                 len -= tx->size;
884                 data += tx->size;
885                 offset = 0;
886
887                 id = get_id_from_freelist(np->tx_skbs);
888                 np->tx_skbs[id] = skb_get(skb);
889                 tx = RING_GET_REQUEST(&np->tx, prod++);
890                 tx->id = id;
891                 ref = gnttab_claim_grant_reference(&np->gref_tx_head);
892                 BUG_ON((signed short)ref < 0);
893
894                 mfn = virt_to_mfn(data);
895                 gnttab_grant_foreign_access_ref(ref, np->xbdev->otherend_id,
896                                                 mfn, GTF_readonly);
897
898                 tx->gref = np->grant_tx_ref[id] = ref;
899                 tx->offset = offset;
900                 tx->size = len;
901                 tx->flags = 0;
902         }
903
904         for (i = 0; i < frags; i++) {
905                 skb_frag_t *frag = skb_shinfo(skb)->frags + i;
906
907                 tx->flags |= XEN_NETTXF_more_data;
908
909                 id = get_id_from_freelist(np->tx_skbs);
910                 np->tx_skbs[id] = skb_get(skb);
911                 tx = RING_GET_REQUEST(&np->tx, prod++);
912                 tx->id = id;
913                 ref = gnttab_claim_grant_reference(&np->gref_tx_head);
914                 BUG_ON((signed short)ref < 0);
915
916                 mfn = pfn_to_mfn(page_to_pfn(skb_frag_page(frag)));
917                 gnttab_grant_foreign_access_ref(ref, np->xbdev->otherend_id,
918                                                 mfn, GTF_readonly);
919
920                 tx->gref = np->grant_tx_ref[id] = ref;
921                 tx->offset = frag->page_offset;
922                 tx->size = skb_frag_size(frag);
923                 tx->flags = 0;
924         }
925
926         np->tx.req_prod_pvt = prod;
927 }
928
929 static int network_start_xmit(struct sk_buff *skb, struct net_device *dev)
930 {
931         unsigned short id;
932         struct netfront_info *np = netdev_priv(dev);
933         struct netfront_stats *stats = this_cpu_ptr(np->stats);
934         struct netif_tx_request *tx;
935         struct netif_extra_info *extra;
936         char *data = skb->data;
937         RING_IDX i;
938         grant_ref_t ref;
939         unsigned long mfn;
940         int notify;
941         int frags = skb_shinfo(skb)->nr_frags;
942         unsigned int offset = offset_in_page(data);
943         unsigned int len = skb_headlen(skb);
944
945         /* Check the fast path, if hooks are available */
946         if (np->accel_vif_state.hooks && 
947             np->accel_vif_state.hooks->start_xmit(skb, dev)) { 
948                 /* Fast path has sent this packet */ 
949                 return NETDEV_TX_OK;
950         } 
951
952         frags += DIV_ROUND_UP(offset + len, PAGE_SIZE);
953         if (unlikely(frags > MAX_SKB_FRAGS + 1)) {
954                 pr_alert("xennet: skb rides the rocket: %d frags\n", frags);
955                 dump_stack();
956                 goto drop;
957         }
958
959         spin_lock_irq(&np->tx_lock);
960
961         if (unlikely(!netfront_carrier_ok(np) ||
962                      (frags > 1 && !xennet_can_sg(dev)) ||
963                      netif_needs_gso(skb, netif_skb_features(skb)))) {
964                 spin_unlock_irq(&np->tx_lock);
965                 goto drop;
966         }
967
968         i = np->tx.req_prod_pvt;
969
970         id = get_id_from_freelist(np->tx_skbs);
971         np->tx_skbs[id] = skb;
972
973         tx = RING_GET_REQUEST(&np->tx, i);
974
975         tx->id   = id;
976         ref = gnttab_claim_grant_reference(&np->gref_tx_head);
977         BUG_ON((signed short)ref < 0);
978         mfn = virt_to_mfn(data);
979         gnttab_grant_foreign_access_ref(
980                 ref, np->xbdev->otherend_id, mfn, GTF_readonly);
981         tx->gref = np->grant_tx_ref[id] = ref;
982         tx->offset = offset;
983         tx->size = len;
984
985         tx->flags = 0;
986         extra = NULL;
987
988         if (skb->ip_summed == CHECKSUM_PARTIAL) /* local packet? */
989                 tx->flags |= XEN_NETTXF_csum_blank | XEN_NETTXF_data_validated;
990         else if (skb->ip_summed == CHECKSUM_UNNECESSARY)
991                 tx->flags |= XEN_NETTXF_data_validated;
992
993 #if HAVE_TSO
994         if (skb_shinfo(skb)->gso_size) {
995                 struct netif_extra_info *gso = (struct netif_extra_info *)
996                         RING_GET_REQUEST(&np->tx, ++i);
997
998                 if (extra)
999                         extra->flags |= XEN_NETIF_EXTRA_FLAG_MORE;
1000                 else
1001                         tx->flags |= XEN_NETTXF_extra_info;
1002
1003                 gso->u.gso.size = skb_shinfo(skb)->gso_size;
1004                 gso->u.gso.type = XEN_NETIF_GSO_TYPE_TCPV4;
1005                 gso->u.gso.pad = 0;
1006                 gso->u.gso.features = 0;
1007
1008                 gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
1009                 gso->flags = 0;
1010                 extra = gso;
1011         }
1012 #endif
1013
1014         np->tx.req_prod_pvt = i + 1;
1015
1016         xennet_make_frags(skb, dev, tx);
1017         tx->size = skb->len;
1018
1019         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&np->tx, notify);
1020         if (notify)
1021                 notify_remote_via_irq(np->irq);
1022
1023         u64_stats_update_begin(&stats->syncp);
1024         stats->tx_bytes += skb->len;
1025         stats->tx_packets++;
1026         u64_stats_update_end(&stats->syncp);
1027         dev->trans_start = jiffies;
1028
1029         /* Note: It is not safe to access skb after network_tx_buf_gc()! */
1030         network_tx_buf_gc(dev);
1031
1032         if (!netfront_tx_slot_available(np))
1033                 netif_stop_queue(dev);
1034
1035         spin_unlock_irq(&np->tx_lock);
1036
1037         return NETDEV_TX_OK;
1038
1039  drop:
1040         dev->stats.tx_dropped++;
1041         dev_kfree_skb(skb);
1042         return NETDEV_TX_OK;
1043 }
1044
1045 static irqreturn_t netif_int(int irq, void *dev_id)
1046 {
1047         struct net_device *dev = dev_id;
1048         struct netfront_info *np = netdev_priv(dev);
1049         unsigned long flags;
1050
1051         spin_lock_irqsave(&np->tx_lock, flags);
1052
1053         if (likely(netfront_carrier_ok(np))) {
1054                 network_tx_buf_gc(dev);
1055                 /* Under tx_lock: protects access to rx shared-ring indexes. */
1056                 if (RING_HAS_UNCONSUMED_RESPONSES(&np->rx)) {
1057                         netfront_accelerator_call_stop_napi_irq(np, dev);
1058
1059                         napi_schedule(&np->napi);
1060                 }
1061         }
1062
1063         spin_unlock_irqrestore(&np->tx_lock, flags);
1064
1065         return IRQ_HANDLED;
1066 }
1067
1068 static void xennet_move_rx_slot(struct netfront_info *np, struct sk_buff *skb,
1069                                 grant_ref_t ref)
1070 {
1071         int new = xennet_rxidx(np->rx.req_prod_pvt);
1072
1073         BUG_ON(np->rx_skbs[new]);
1074         np->rx_skbs[new] = skb;
1075         np->grant_rx_ref[new] = ref;
1076         RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->id = new;
1077         RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->gref = ref;
1078         np->rx.req_prod_pvt++;
1079 }
1080
1081 int xennet_get_extras(struct netfront_info *np,
1082                       struct netif_extra_info *extras, RING_IDX rp)
1083
1084 {
1085         struct netif_extra_info *extra;
1086         RING_IDX cons = np->rx.rsp_cons;
1087         int err = 0;
1088
1089         do {
1090                 struct sk_buff *skb;
1091                 grant_ref_t ref;
1092
1093                 if (unlikely(cons + 1 == rp)) {
1094                         if (net_ratelimit())
1095                                 WPRINTK("Missing extra info\n");
1096                         err = -EBADR;
1097                         break;
1098                 }
1099
1100                 extra = (struct netif_extra_info *)
1101                         RING_GET_RESPONSE(&np->rx, ++cons);
1102
1103                 if (unlikely(!extra->type ||
1104                              extra->type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
1105                         if (net_ratelimit())
1106                                 WPRINTK("Invalid extra type: %d\n",
1107                                         extra->type);
1108                         err = -EINVAL;
1109                 } else {
1110                         memcpy(&extras[extra->type - 1], extra,
1111                                sizeof(*extra));
1112                 }
1113
1114                 skb = xennet_get_rx_skb(np, cons);
1115                 ref = xennet_get_rx_ref(np, cons);
1116                 xennet_move_rx_slot(np, skb, ref);
1117         } while (extra->flags & XEN_NETIF_EXTRA_FLAG_MORE);
1118
1119         np->rx.rsp_cons = cons;
1120         return err;
1121 }
1122
1123 static int xennet_get_responses(struct netfront_info *np,
1124                                 struct netfront_rx_info *rinfo, RING_IDX rp,
1125                                 struct sk_buff_head *list,
1126                                 int *pages_flipped_p)
1127 {
1128         int pages_flipped = *pages_flipped_p;
1129         struct mmu_update *mmu;
1130         struct multicall_entry *mcl;
1131         struct netif_rx_response *rx = &rinfo->rx;
1132         struct netif_extra_info *extras = rinfo->extras;
1133         RING_IDX cons = np->rx.rsp_cons;
1134         struct sk_buff *skb = xennet_get_rx_skb(np, cons);
1135         grant_ref_t ref = xennet_get_rx_ref(np, cons);
1136         int max = MAX_SKB_FRAGS + (rx->status <= RX_COPY_THRESHOLD);
1137         int frags = 1;
1138         int err = 0;
1139         unsigned long ret;
1140
1141         if (rx->flags & XEN_NETRXF_extra_info) {
1142                 err = xennet_get_extras(np, extras, rp);
1143                 cons = np->rx.rsp_cons;
1144         }
1145
1146         for (;;) {
1147                 unsigned long mfn;
1148
1149                 if (unlikely(rx->status < 0 ||
1150                              rx->offset + rx->status > PAGE_SIZE)) {
1151                         if (net_ratelimit())
1152                                 WPRINTK("rx->offset: %x, size: %u\n",
1153                                         rx->offset, rx->status);
1154                         xennet_move_rx_slot(np, skb, ref);
1155                         err = -EINVAL;
1156                         goto next;
1157                 }
1158
1159                 /*
1160                  * This definitely indicates a bug, either in this driver or in
1161                  * the backend driver. In future this should flag the bad
1162                  * situation to the system controller to reboot the backed.
1163                  */
1164                 if (ref == GRANT_INVALID_REF) {
1165                         if (net_ratelimit())
1166                                 WPRINTK("Bad rx response id %d.\n", rx->id);
1167                         err = -EINVAL;
1168                         goto next;
1169                 }
1170
1171                 if (!np->copying_receiver) {
1172                         /* Memory pressure, insufficient buffer
1173                          * headroom, ... */
1174                         if (!(mfn = gnttab_end_foreign_transfer_ref(ref))) {
1175                                 if (net_ratelimit())
1176                                         WPRINTK("Unfulfilled rx req "
1177                                                 "(id=%d, st=%d).\n",
1178                                                 rx->id, rx->status);
1179                                 xennet_move_rx_slot(np, skb, ref);
1180                                 err = -ENOMEM;
1181                                 goto next;
1182                         }
1183
1184                         if (!xen_feature(XENFEAT_auto_translated_physmap)) {
1185                                 /* Remap the page. */
1186                                 const struct page *page =
1187                                         skb_frag_page(skb_shinfo(skb)->frags);
1188                                 unsigned long pfn = page_to_pfn(page);
1189                                 void *vaddr = page_address(page);
1190
1191                                 mcl = np->rx_mcl + pages_flipped;
1192                                 mmu = np->rx_mmu + pages_flipped;
1193
1194                                 MULTI_update_va_mapping(mcl,
1195                                                         (unsigned long)vaddr,
1196                                                         pfn_pte_ma(mfn,
1197                                                                    PAGE_KERNEL),
1198                                                         0);
1199                                 mmu->ptr = ((maddr_t)mfn << PAGE_SHIFT)
1200                                         | MMU_MACHPHYS_UPDATE;
1201                                 mmu->val = pfn;
1202
1203                                 set_phys_to_machine(pfn, mfn);
1204                         }
1205                         pages_flipped++;
1206                 } else {
1207                         ret = gnttab_end_foreign_access_ref(ref);
1208                         BUG_ON(!ret);
1209                 }
1210
1211                 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1212
1213                 __skb_queue_tail(list, skb);
1214
1215 next:
1216                 if (!(rx->flags & XEN_NETRXF_more_data))
1217                         break;
1218
1219                 if (cons + frags == rp) {
1220                         if (net_ratelimit())
1221                                 WPRINTK("Need more frags\n");
1222                         err = -ENOENT;
1223                         break;
1224                 }
1225
1226                 rx = RING_GET_RESPONSE(&np->rx, cons + frags);
1227                 skb = xennet_get_rx_skb(np, cons + frags);
1228                 ref = xennet_get_rx_ref(np, cons + frags);
1229                 frags++;
1230         }
1231
1232         if (unlikely(frags > max)) {
1233                 if (net_ratelimit())
1234                         WPRINTK("Too many frags\n");
1235                 err = -E2BIG;
1236         }
1237
1238         if (unlikely(err))
1239                 np->rx.rsp_cons = cons + frags;
1240
1241         *pages_flipped_p = pages_flipped;
1242
1243         return err;
1244 }
1245
1246 static RING_IDX xennet_fill_frags(struct netfront_info *np,
1247                                   struct sk_buff *skb,
1248                                   struct sk_buff_head *list)
1249 {
1250         struct skb_shared_info *shinfo = skb_shinfo(skb);
1251         int nr_frags = shinfo->nr_frags;
1252         RING_IDX cons = np->rx.rsp_cons;
1253         struct sk_buff *nskb;
1254
1255         while ((nskb = __skb_dequeue(list))) {
1256                 struct netif_rx_response *rx =
1257                         RING_GET_RESPONSE(&np->rx, ++cons);
1258
1259                 __skb_fill_page_desc(skb, nr_frags,
1260                                      skb_frag_page(skb_shinfo(nskb)->frags),
1261                                      rx->offset, rx->status);
1262
1263                 skb->data_len += rx->status;
1264
1265                 skb_shinfo(nskb)->nr_frags = 0;
1266                 kfree_skb(nskb);
1267
1268                 nr_frags++;
1269         }
1270
1271         shinfo->nr_frags = nr_frags;
1272         return cons;
1273 }
1274
1275 static int xennet_set_skb_gso(struct sk_buff *skb,
1276                               struct netif_extra_info *gso)
1277 {
1278         if (!gso->u.gso.size) {
1279                 if (net_ratelimit())
1280                         WPRINTK("GSO size must not be zero.\n");
1281                 return -EINVAL;
1282         }
1283
1284         /* Currently only TCPv4 S.O. is supported. */
1285         if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) {
1286                 if (net_ratelimit())
1287                         WPRINTK("Bad GSO type %d.\n", gso->u.gso.type);
1288                 return -EINVAL;
1289         }
1290
1291 #if HAVE_TSO
1292         skb_shinfo(skb)->gso_size = gso->u.gso.size;
1293 #if HAVE_GSO
1294         skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1295
1296         /* Header must be checked, and gso_segs computed. */
1297         skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1298 #endif
1299         skb_shinfo(skb)->gso_segs = 0;
1300
1301         return 0;
1302 #else
1303         if (net_ratelimit())
1304                 WPRINTK("GSO unsupported by this kernel.\n");
1305         return -EINVAL;
1306 #endif
1307 }
1308
1309 static int netif_poll(struct napi_struct *napi, int budget)
1310 {
1311         struct netfront_info *np = container_of(napi, struct netfront_info, napi);
1312         struct netfront_stats *stats = this_cpu_ptr(np->stats);
1313         struct net_device *dev = np->netdev;
1314         struct sk_buff *skb;
1315         struct netfront_rx_info rinfo;
1316         struct netif_rx_response *rx = &rinfo.rx;
1317         struct netif_extra_info *extras = rinfo.extras;
1318         RING_IDX i, rp;
1319         struct multicall_entry *mcl;
1320         int work_done, more_to_do = 1, accel_more_to_do = 1;
1321         struct sk_buff_head rxq;
1322         struct sk_buff_head errq;
1323         struct sk_buff_head tmpq;
1324         unsigned long flags;
1325         unsigned int len;
1326         int pages_flipped = 0;
1327         int err;
1328
1329         spin_lock(&np->rx_lock); /* no need for spin_lock_bh() in ->poll() */
1330
1331         if (unlikely(!netfront_carrier_ok(np))) {
1332                 spin_unlock(&np->rx_lock);
1333                 return 0;
1334         }
1335
1336         skb_queue_head_init(&rxq);
1337         skb_queue_head_init(&errq);
1338         skb_queue_head_init(&tmpq);
1339
1340         rp = np->rx.sring->rsp_prod;
1341         rmb(); /* Ensure we see queued responses up to 'rp'. */
1342
1343         i = np->rx.rsp_cons;
1344         work_done = 0;
1345         while ((i != rp) && (work_done < budget)) {
1346                 memcpy(rx, RING_GET_RESPONSE(&np->rx, i), sizeof(*rx));
1347                 memset(extras, 0, sizeof(rinfo.extras));
1348
1349                 err = xennet_get_responses(np, &rinfo, rp, &tmpq,
1350                                            &pages_flipped);
1351
1352                 if (unlikely(err)) {
1353 err:    
1354                         while ((skb = __skb_dequeue(&tmpq)))
1355                                 __skb_queue_tail(&errq, skb);
1356                         dev->stats.rx_errors++;
1357                         i = np->rx.rsp_cons;
1358                         continue;
1359                 }
1360
1361                 skb = __skb_dequeue(&tmpq);
1362
1363                 if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
1364                         struct netif_extra_info *gso;
1365                         gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
1366
1367                         if (unlikely(xennet_set_skb_gso(skb, gso))) {
1368                                 __skb_queue_head(&tmpq, skb);
1369                                 np->rx.rsp_cons += skb_queue_len(&tmpq);
1370                                 goto err;
1371                         }
1372                 }
1373
1374                 NETFRONT_SKB_CB(skb)->page =
1375                         skb_frag_page(skb_shinfo(skb)->frags);
1376                 NETFRONT_SKB_CB(skb)->offset = rx->offset;
1377
1378                 len = rx->status;
1379                 if (len > RX_COPY_THRESHOLD)
1380                         len = RX_COPY_THRESHOLD;
1381                 skb_put(skb, len);
1382
1383                 if (rx->status > len) {
1384                         skb_shinfo(skb)->frags[0].page_offset =
1385                                 rx->offset + len;
1386                         skb_frag_size_set(skb_shinfo(skb)->frags,
1387                                           rx->status - len);
1388                         skb->data_len = rx->status - len;
1389                 } else {
1390                         __skb_fill_page_desc(skb, 0, NULL, 0, 0);
1391                         skb_shinfo(skb)->nr_frags = 0;
1392                 }
1393
1394                 i = xennet_fill_frags(np, skb, &tmpq);
1395
1396                 /*
1397                  * Truesize must approximates the size of true data plus
1398                  * any supervisor overheads. Adding hypervisor overheads
1399                  * has been shown to significantly reduce achievable
1400                  * bandwidth with the default receive buffer size. It is
1401                  * therefore not wise to account for it here.
1402                  *
1403                  * After alloc_skb(RX_COPY_THRESHOLD), truesize is set to
1404                  * RX_COPY_THRESHOLD + the supervisor overheads. Here, we
1405                  * add the size of the data pulled in xennet_fill_frags().
1406                  *
1407                  * We also adjust for any unused space in the main data
1408                  * area by subtracting (RX_COPY_THRESHOLD - len). This is
1409                  * especially important with drivers which split incoming
1410                  * packets into header and data, using only 66 bytes of
1411                  * the main data area (see the e1000 driver for example.)
1412                  * On such systems, without this last adjustement, our
1413                  * achievable receive throughout using the standard receive
1414                  * buffer size was cut by 25%(!!!).
1415                  */
1416                 skb->truesize += skb->data_len - (RX_COPY_THRESHOLD - len);
1417                 skb->len += skb->data_len;
1418
1419                 if (rx->flags & XEN_NETRXF_csum_blank)
1420                         skb->ip_summed = CHECKSUM_PARTIAL;
1421                 else if (rx->flags & XEN_NETRXF_data_validated)
1422                         skb->ip_summed = CHECKSUM_UNNECESSARY;
1423                 else
1424                         skb->ip_summed = CHECKSUM_NONE;
1425
1426                 u64_stats_update_begin(&stats->syncp);
1427                 stats->rx_packets++;
1428                 stats->rx_bytes += skb->len;
1429                 u64_stats_update_end(&stats->syncp);
1430
1431                 __skb_queue_tail(&rxq, skb);
1432
1433                 np->rx.rsp_cons = ++i;
1434                 work_done++;
1435         }
1436
1437         if (pages_flipped) {
1438                 /* Some pages are no longer absent... */
1439                 balloon_update_driver_allowance(-pages_flipped);
1440
1441                 /* Do all the remapping work and M2P updates. */
1442                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
1443                         mcl = np->rx_mcl + pages_flipped;
1444                         mcl->op = __HYPERVISOR_mmu_update;
1445                         mcl->args[0] = (unsigned long)np->rx_mmu;
1446                         mcl->args[1] = pages_flipped;
1447                         mcl->args[2] = 0;
1448                         mcl->args[3] = DOMID_SELF;
1449                         err = HYPERVISOR_multicall_check(np->rx_mcl,
1450                                                          pages_flipped + 1,
1451                                                          NULL);
1452                         BUG_ON(err);
1453                 }
1454         }
1455
1456         __skb_queue_purge(&errq);
1457
1458         while ((skb = __skb_dequeue(&rxq)) != NULL) {
1459                 struct page *page = NETFRONT_SKB_CB(skb)->page;
1460                 void *vaddr = page_address(page);
1461                 unsigned offset = NETFRONT_SKB_CB(skb)->offset;
1462
1463                 memcpy(skb->data, vaddr + offset, skb_headlen(skb));
1464
1465                 if (page != skb_frag_page(skb_shinfo(skb)->frags))
1466                         __free_page(page);
1467
1468                 /* Ethernet work: Delayed to here as it peeks the header. */
1469                 skb->protocol = eth_type_trans(skb, dev);
1470
1471                 if (skb_checksum_setup(skb, &np->rx_gso_csum_fixups)) {
1472                         kfree_skb(skb);
1473                         continue;
1474                 }
1475
1476                 /* Pass it up. */
1477                 netif_receive_skb(skb);
1478         }
1479
1480         /* If we get a callback with very few responses, reduce fill target. */
1481         /* NB. Note exponential increase, linear decrease. */
1482         if (((np->rx.req_prod_pvt - np->rx.sring->rsp_prod) >
1483              ((3*np->rx_target) / 4)) &&
1484             (--np->rx_target < np->rx_min_target))
1485                 np->rx_target = np->rx_min_target;
1486
1487         network_alloc_rx_buffers(dev);
1488
1489         if (work_done < budget) {
1490                 /* there's some spare capacity, try the accelerated path */
1491                 int accel_budget = budget - work_done;
1492                 int accel_budget_start = accel_budget;
1493
1494                 if (np->accel_vif_state.hooks) { 
1495                         accel_more_to_do =  
1496                                 np->accel_vif_state.hooks->netdev_poll 
1497                                 (dev, &accel_budget); 
1498                         work_done += (accel_budget_start - accel_budget); 
1499                 } else
1500                         accel_more_to_do = 0;
1501         }
1502
1503         if (work_done < budget) {
1504                 local_irq_save(flags);
1505
1506                 RING_FINAL_CHECK_FOR_RESPONSES(&np->rx, more_to_do);
1507
1508                 if (!more_to_do && !accel_more_to_do && 
1509                     np->accel_vif_state.hooks) {
1510                         /* 
1511                          *  Slow path has nothing more to do, see if
1512                          *  fast path is likewise
1513                          */
1514                         accel_more_to_do = 
1515                                 np->accel_vif_state.hooks->start_napi_irq(dev);
1516                 }
1517
1518                 if (!more_to_do && !accel_more_to_do)
1519                         __napi_complete(napi);
1520
1521                 local_irq_restore(flags);
1522         }
1523
1524         spin_unlock(&np->rx_lock);
1525         
1526         return work_done;
1527 }
1528
1529 static void netif_release_tx_bufs(struct netfront_info *np)
1530 {
1531         struct sk_buff *skb;
1532         int i;
1533
1534         for (i = 1; i <= NET_TX_RING_SIZE; i++) {
1535                 if ((unsigned long)np->tx_skbs[i] < PAGE_OFFSET)
1536                         continue;
1537
1538                 skb = np->tx_skbs[i];
1539                 gnttab_end_foreign_access_ref(np->grant_tx_ref[i]);
1540                 gnttab_release_grant_reference(
1541                         &np->gref_tx_head, np->grant_tx_ref[i]);
1542                 np->grant_tx_ref[i] = GRANT_INVALID_REF;
1543                 add_id_to_freelist(np->tx_skbs, i);
1544                 dev_kfree_skb_irq(skb);
1545         }
1546 }
1547
1548 static void netif_release_rx_bufs_flip(struct netfront_info *np)
1549 {
1550         struct mmu_update      *mmu = np->rx_mmu;
1551         struct multicall_entry *mcl = np->rx_mcl;
1552         struct sk_buff_head free_list;
1553         struct sk_buff *skb;
1554         unsigned long mfn;
1555         int xfer = 0, noxfer = 0, unused = 0;
1556         int id, ref, rc;
1557
1558         skb_queue_head_init(&free_list);
1559
1560         spin_lock_bh(&np->rx_lock);
1561
1562         for (id = 0; id < NET_RX_RING_SIZE; id++) {
1563                 struct page *page;
1564
1565                 if ((ref = np->grant_rx_ref[id]) == GRANT_INVALID_REF) {
1566                         unused++;
1567                         continue;
1568                 }
1569
1570                 skb = np->rx_skbs[id];
1571                 mfn = gnttab_end_foreign_transfer_ref(ref);
1572                 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1573                 np->grant_rx_ref[id] = GRANT_INVALID_REF;
1574                 add_id_to_freelist(np->rx_skbs, id);
1575
1576                 page = skb_frag_page(skb_shinfo(skb)->frags);
1577
1578                 if (0 == mfn) {
1579                         balloon_release_driver_page(page);
1580                         skb_shinfo(skb)->nr_frags = 0;
1581                         dev_kfree_skb(skb);
1582                         noxfer++;
1583                         continue;
1584                 }
1585
1586                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
1587                         /* Remap the page. */
1588                         unsigned long pfn = page_to_pfn(page);
1589                         void *vaddr = page_address(page);
1590
1591                         MULTI_update_va_mapping(mcl, (unsigned long)vaddr,
1592                                                 pfn_pte_ma(mfn, PAGE_KERNEL),
1593                                                 0);
1594                         mcl++;
1595                         mmu->ptr = ((maddr_t)mfn << PAGE_SHIFT)
1596                                 | MMU_MACHPHYS_UPDATE;
1597                         mmu->val = pfn;
1598                         mmu++;
1599
1600                         set_phys_to_machine(pfn, mfn);
1601                 }
1602                 __skb_queue_tail(&free_list, skb);
1603                 xfer++;
1604         }
1605
1606         DPRINTK("%s: %d xfer, %d noxfer, %d unused\n",
1607                 __FUNCTION__, xfer, noxfer, unused);
1608
1609         if (xfer) {
1610                 /* Some pages are no longer absent... */
1611                 balloon_update_driver_allowance(-xfer);
1612
1613                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
1614                         /* Do all the remapping work and M2P updates. */
1615                         mcl->op = __HYPERVISOR_mmu_update;
1616                         mcl->args[0] = (unsigned long)np->rx_mmu;
1617                         mcl->args[1] = mmu - np->rx_mmu;
1618                         mcl->args[2] = 0;
1619                         mcl->args[3] = DOMID_SELF;
1620                         mcl++;
1621                         rc = HYPERVISOR_multicall_check(
1622                                 np->rx_mcl, mcl - np->rx_mcl, NULL);
1623                         BUG_ON(rc);
1624                 }
1625         }
1626
1627         __skb_queue_purge(&free_list);
1628
1629         spin_unlock_bh(&np->rx_lock);
1630 }
1631
1632 static void netif_release_rx_bufs_copy(struct netfront_info *np)
1633 {
1634         struct sk_buff *skb;
1635         int i, ref;
1636         int busy = 0, inuse = 0;
1637
1638         spin_lock_bh(&np->rx_lock);
1639
1640         for (i = 0; i < NET_RX_RING_SIZE; i++) {
1641                 ref = np->grant_rx_ref[i];
1642
1643                 if (ref == GRANT_INVALID_REF)
1644                         continue;
1645
1646                 inuse++;
1647
1648                 skb = np->rx_skbs[i];
1649
1650                 if (!gnttab_end_foreign_access_ref(ref))
1651                 {
1652                         busy++;
1653                         continue;
1654                 }
1655
1656                 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1657                 np->grant_rx_ref[i] = GRANT_INVALID_REF;
1658                 add_id_to_freelist(np->rx_skbs, i);
1659
1660                 dev_kfree_skb(skb);
1661         }
1662
1663         if (busy)
1664                 DPRINTK("%s: Unable to release %d of %d inuse grant references out of %ld total.\n",
1665                         __FUNCTION__, busy, inuse, NET_RX_RING_SIZE);
1666
1667         spin_unlock_bh(&np->rx_lock);
1668 }
1669
1670 static int network_close(struct net_device *dev)
1671 {
1672         struct netfront_info *np = netdev_priv(dev);
1673         netif_stop_queue(np->netdev);
1674         napi_disable(&np->napi);
1675         return 0;
1676 }
1677
1678
1679 static int xennet_set_mac_address(struct net_device *dev, void *p)
1680 {
1681         struct netfront_info *np = netdev_priv(dev);
1682         struct sockaddr *addr = p;
1683
1684         if (netif_running(dev))
1685                 return -EBUSY;
1686
1687         if (!is_valid_ether_addr(addr->sa_data))
1688                 return -EADDRNOTAVAIL;
1689
1690         memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
1691         memcpy(np->mac, addr->sa_data, ETH_ALEN);
1692
1693         return 0;
1694 }
1695
1696 static int xennet_change_mtu(struct net_device *dev, int mtu)
1697 {
1698         int max = xennet_can_sg(dev) ? 65535 - ETH_HLEN : ETH_DATA_LEN;
1699
1700         if (mtu > max)
1701                 return -EINVAL;
1702         dev->mtu = mtu;
1703         return 0;
1704 }
1705
1706 static struct rtnl_link_stats64 *xennet_get_stats64(struct net_device *dev,
1707                                                     struct rtnl_link_stats64 *tot)
1708 {
1709         struct netfront_info *np = netdev_priv(dev);
1710         int cpu;
1711
1712         netfront_accelerator_call_get_stats(np, dev);
1713
1714         for_each_possible_cpu(cpu) {
1715                 struct netfront_stats *stats = per_cpu_ptr(np->stats, cpu);
1716                 u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
1717                 unsigned int start;
1718
1719                 do {
1720                         start = u64_stats_fetch_begin_bh(&stats->syncp);
1721
1722                         rx_packets = stats->rx_packets;
1723                         tx_packets = stats->tx_packets;
1724                         rx_bytes = stats->rx_bytes;
1725                         tx_bytes = stats->tx_bytes;
1726                 } while (u64_stats_fetch_retry_bh(&stats->syncp, start));
1727
1728                 tot->rx_packets += rx_packets;
1729                 tot->tx_packets += tx_packets;
1730                 tot->rx_bytes   += rx_bytes;
1731                 tot->tx_bytes   += tx_bytes;
1732         }
1733
1734         tot->rx_errors  = dev->stats.rx_errors;
1735         tot->tx_dropped = dev->stats.tx_dropped;
1736
1737         return tot;
1738 }
1739
1740 static const struct xennet_stat {
1741         char name[ETH_GSTRING_LEN];
1742         u16 offset;
1743 } xennet_stats[] = {
1744         {
1745                 "rx_gso_csum_fixups",
1746                 offsetof(struct netfront_info, rx_gso_csum_fixups) / sizeof(long)
1747         },
1748 };
1749
1750 static int xennet_get_sset_count(struct net_device *dev, int sset)
1751 {
1752         switch (sset) {
1753         case ETH_SS_STATS:
1754                 return ARRAY_SIZE(xennet_stats);
1755         }
1756         return -EOPNOTSUPP;
1757 }
1758
1759 static void xennet_get_ethtool_stats(struct net_device *dev,
1760                                      struct ethtool_stats *stats, u64 *data)
1761 {
1762         unsigned long *np = netdev_priv(dev);
1763         unsigned int i;
1764
1765         for (i = 0; i < ARRAY_SIZE(xennet_stats); i++)
1766                 data[i] = np[xennet_stats[i].offset];
1767 }
1768
1769 static void xennet_get_strings(struct net_device *dev, u32 stringset, u8 *data)
1770 {
1771         unsigned int i;
1772
1773         switch (stringset) {
1774         case ETH_SS_STATS:
1775                 for (i = 0; i < ARRAY_SIZE(xennet_stats); i++)
1776                         memcpy(data + i * ETH_GSTRING_LEN,
1777                                xennet_stats[i].name, ETH_GSTRING_LEN);
1778                 break;
1779         }
1780 }
1781
1782 static void netfront_get_drvinfo(struct net_device *dev,
1783                                  struct ethtool_drvinfo *info)
1784 {
1785         strcpy(info->driver, "netfront");
1786         strlcpy(info->bus_info, dev_name(dev->dev.parent),
1787                 ARRAY_SIZE(info->bus_info));
1788 }
1789
1790 static int network_connect(struct net_device *dev)
1791 {
1792         struct netfront_info *np = netdev_priv(dev);
1793         int i, requeue_idx, err;
1794         struct sk_buff *skb;
1795         grant_ref_t ref;
1796         netif_rx_request_t *req;
1797         unsigned int feature_rx_copy, feature_rx_flip;
1798
1799         err = xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1800                            "feature-rx-copy", "%u", &feature_rx_copy);
1801         if (err != 1)
1802                 feature_rx_copy = 0;
1803         err = xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1804                            "feature-rx-flip", "%u", &feature_rx_flip);
1805         if (err != 1)
1806                 feature_rx_flip = 1;
1807
1808         /*
1809          * Copy packets on receive path if:
1810          *  (a) This was requested by user, and the backend supports it; or
1811          *  (b) Flipping was requested, but this is unsupported by the backend.
1812          */
1813         np->copying_receiver = ((MODPARM_rx_copy && feature_rx_copy) ||
1814                                 (MODPARM_rx_flip && !feature_rx_flip));
1815
1816         err = talk_to_backend(np->xbdev, np);
1817         if (err)
1818                 return err;
1819
1820         rtnl_lock();
1821         netdev_update_features(dev);
1822         rtnl_unlock();
1823
1824         DPRINTK("device %s has %sing receive path.\n",
1825                 dev->name, np->copying_receiver ? "copy" : "flipp");
1826
1827         spin_lock_bh(&np->rx_lock);
1828         spin_lock_irq(&np->tx_lock);
1829
1830         /*
1831          * Recovery procedure:
1832          *  NB. Freelist index entries are always going to be less than
1833          *  PAGE_OFFSET, whereas pointers to skbs will always be equal or
1834          *  greater than PAGE_OFFSET: we use this property to distinguish
1835          *  them.
1836          */
1837
1838         /* Step 1: Discard all pending TX packet fragments. */
1839         netif_release_tx_bufs(np);
1840
1841         /* Step 2: Rebuild the RX buffer freelist and the RX ring itself. */
1842         for (requeue_idx = 0, i = 0; i < NET_RX_RING_SIZE; i++) {
1843                 unsigned long pfn;
1844
1845                 if (!np->rx_skbs[i])
1846                         continue;
1847
1848                 skb = np->rx_skbs[requeue_idx] = xennet_get_rx_skb(np, i);
1849                 ref = np->grant_rx_ref[requeue_idx] = xennet_get_rx_ref(np, i);
1850                 req = RING_GET_REQUEST(&np->rx, requeue_idx);
1851                 pfn = page_to_pfn(skb_frag_page(skb_shinfo(skb)->frags));
1852
1853                 if (!np->copying_receiver) {
1854                         gnttab_grant_foreign_transfer_ref(
1855                                 ref, np->xbdev->otherend_id, pfn);
1856                 } else {
1857                         gnttab_grant_foreign_access_ref(
1858                                 ref, np->xbdev->otherend_id,
1859                                 pfn_to_mfn(pfn), 0);
1860                 }
1861                 req->gref = ref;
1862                 req->id   = requeue_idx;
1863
1864                 requeue_idx++;
1865         }
1866
1867         np->rx.req_prod_pvt = requeue_idx;
1868
1869         /*
1870          * Step 3: All public and private state should now be sane.  Get
1871          * ready to start sending and receiving packets and give the driver
1872          * domain a kick because we've probably just requeued some
1873          * packets.
1874          */
1875         netfront_carrier_on(np);
1876         notify_remote_via_irq(np->irq);
1877         network_tx_buf_gc(dev);
1878         network_alloc_rx_buffers(dev);
1879
1880         spin_unlock_irq(&np->tx_lock);
1881         spin_unlock_bh(&np->rx_lock);
1882
1883         return 0;
1884 }
1885
1886 static void netif_uninit(struct net_device *dev)
1887 {
1888         struct netfront_info *np = netdev_priv(dev);
1889         netif_release_tx_bufs(np);
1890         if (np->copying_receiver)
1891                 netif_release_rx_bufs_copy(np);
1892         else
1893                 netif_release_rx_bufs_flip(np);
1894         gnttab_free_grant_references(np->gref_tx_head);
1895         gnttab_free_grant_references(np->gref_rx_head);
1896 }
1897
1898 static const struct ethtool_ops network_ethtool_ops =
1899 {
1900         .get_drvinfo = netfront_get_drvinfo,
1901         .get_link = ethtool_op_get_link,
1902
1903         .get_sset_count = xennet_get_sset_count,
1904         .get_ethtool_stats = xennet_get_ethtool_stats,
1905         .get_strings = xennet_get_strings,
1906 };
1907
1908 #ifdef CONFIG_SYSFS
1909 static ssize_t show_rxbuf_min(struct device *dev,
1910                               struct device_attribute *attr, char *buf)
1911 {
1912         struct netfront_info *info = netdev_priv(to_net_dev(dev));
1913
1914         return sprintf(buf, "%u\n", info->rx_min_target);
1915 }
1916
1917 static ssize_t store_rxbuf_min(struct device *dev,
1918                                struct device_attribute *attr,
1919                                const char *buf, size_t len)
1920 {
1921         struct net_device *netdev = to_net_dev(dev);
1922         struct netfront_info *np = netdev_priv(netdev);
1923         char *endp;
1924         unsigned long target;
1925
1926         if (!capable(CAP_NET_ADMIN))
1927                 return -EPERM;
1928
1929         target = simple_strtoul(buf, &endp, 0);
1930         if (endp == buf)
1931                 return -EBADMSG;
1932
1933         if (target < RX_MIN_TARGET)
1934                 target = RX_MIN_TARGET;
1935         if (target > RX_MAX_TARGET)
1936                 target = RX_MAX_TARGET;
1937
1938         spin_lock_bh(&np->rx_lock);
1939         if (target > np->rx_max_target)
1940                 np->rx_max_target = target;
1941         np->rx_min_target = target;
1942         if (target > np->rx_target)
1943                 np->rx_target = target;
1944
1945         network_alloc_rx_buffers(netdev);
1946
1947         spin_unlock_bh(&np->rx_lock);
1948         return len;
1949 }
1950
1951 static ssize_t show_rxbuf_max(struct device *dev,
1952                               struct device_attribute *attr, char *buf)
1953 {
1954         struct netfront_info *info = netdev_priv(to_net_dev(dev));
1955
1956         return sprintf(buf, "%u\n", info->rx_max_target);
1957 }
1958
1959 static ssize_t store_rxbuf_max(struct device *dev,
1960                                struct device_attribute *attr,
1961                                const char *buf, size_t len)
1962 {
1963         struct net_device *netdev = to_net_dev(dev);
1964         struct netfront_info *np = netdev_priv(netdev);
1965         char *endp;
1966         unsigned long target;
1967
1968         if (!capable(CAP_NET_ADMIN))
1969                 return -EPERM;
1970
1971         target = simple_strtoul(buf, &endp, 0);
1972         if (endp == buf)
1973                 return -EBADMSG;
1974
1975         if (target < RX_MIN_TARGET)
1976                 target = RX_MIN_TARGET;
1977         if (target > RX_MAX_TARGET)
1978                 target = RX_MAX_TARGET;
1979
1980         spin_lock_bh(&np->rx_lock);
1981         if (target < np->rx_min_target)
1982                 np->rx_min_target = target;
1983         np->rx_max_target = target;
1984         if (target < np->rx_target)
1985                 np->rx_target = target;
1986
1987         network_alloc_rx_buffers(netdev);
1988
1989         spin_unlock_bh(&np->rx_lock);
1990         return len;
1991 }
1992
1993 static ssize_t show_rxbuf_cur(struct device *dev,
1994                               struct device_attribute *attr, char *buf)
1995 {
1996         struct netfront_info *info = netdev_priv(to_net_dev(dev));
1997
1998         return sprintf(buf, "%u\n", info->rx_target);
1999 }
2000
2001 static struct device_attribute xennet_attrs[] = {
2002         __ATTR(rxbuf_min, S_IRUGO|S_IWUSR, show_rxbuf_min, store_rxbuf_min),
2003         __ATTR(rxbuf_max, S_IRUGO|S_IWUSR, show_rxbuf_max, store_rxbuf_max),
2004         __ATTR(rxbuf_cur, S_IRUGO, show_rxbuf_cur, NULL),
2005 };
2006
2007 static int xennet_sysfs_addif(struct net_device *netdev)
2008 {
2009         int i;
2010         int error = 0;
2011
2012         for (i = 0; i < ARRAY_SIZE(xennet_attrs); i++) {
2013                 error = device_create_file(&netdev->dev,
2014                                            &xennet_attrs[i]);
2015                 if (error)
2016                         goto fail;
2017         }
2018         return 0;
2019
2020  fail:
2021         while (--i >= 0)
2022                 device_remove_file(&netdev->dev, &xennet_attrs[i]);
2023         return error;
2024 }
2025
2026 static void xennet_sysfs_delif(struct net_device *netdev)
2027 {
2028         int i;
2029
2030         for (i = 0; i < ARRAY_SIZE(xennet_attrs); i++)
2031                 device_remove_file(&netdev->dev, &xennet_attrs[i]);
2032 }
2033
2034 #endif /* CONFIG_SYSFS */
2035
2036
2037 /*
2038  * Nothing to do here. Virtual interface is point-to-point and the
2039  * physical interface is probably promiscuous anyway.
2040  */
2041 static void network_set_multicast_list(struct net_device *dev)
2042 {
2043 }
2044
2045 static netdev_features_t xennet_fix_features(struct net_device *dev,
2046                                              netdev_features_t features)
2047 {
2048         struct netfront_info *np = netdev_priv(dev);
2049         int val;
2050
2051         if (features & NETIF_F_SG) {
2052                 if (xenbus_scanf(XBT_NIL, np->xbdev->otherend, "feature-sg",
2053                                  "%d", &val) < 0)
2054                         val = 0;
2055
2056                 if (!val)
2057                         features &= ~NETIF_F_SG;
2058         }
2059
2060         if (features & NETIF_F_TSO) {
2061                 if (xenbus_scanf(XBT_NIL, np->xbdev->otherend,
2062                                  "feature-gso-tcpv4", "%d", &val) < 0)
2063                         val = 0;
2064
2065                 if (!val)
2066                         features &= ~NETIF_F_TSO;
2067         }
2068
2069         return features;
2070 }
2071
2072 static int xennet_set_features(struct net_device *dev,
2073                                netdev_features_t features)
2074 {
2075         if (!(features & NETIF_F_SG) && dev->mtu > ETH_DATA_LEN) {
2076                 netdev_info(dev, "Reducing MTU because no SG offload");
2077                 dev->mtu = ETH_DATA_LEN;
2078         }
2079
2080         return 0;
2081 }
2082
2083 static const struct net_device_ops xennet_netdev_ops = {
2084         .ndo_uninit             = netif_uninit,
2085         .ndo_open               = network_open,
2086         .ndo_stop               = network_close,
2087         .ndo_start_xmit         = network_start_xmit,
2088         .ndo_set_rx_mode        = network_set_multicast_list,
2089         .ndo_set_mac_address    = xennet_set_mac_address,
2090         .ndo_validate_addr      = eth_validate_addr,
2091         .ndo_fix_features       = xennet_fix_features,
2092         .ndo_set_features       = xennet_set_features,
2093         .ndo_change_mtu         = xennet_change_mtu,
2094         .ndo_get_stats64        = xennet_get_stats64,
2095 };
2096
2097 static struct net_device * __devinit create_netdev(struct xenbus_device *dev)
2098 {
2099         int i, err = 0;
2100         struct net_device *netdev = NULL;
2101         struct netfront_info *np = NULL;
2102
2103         netdev = alloc_etherdev(sizeof(struct netfront_info));
2104         if (!netdev) {
2105                 pr_warning("%s: alloc_etherdev failed\n", __FUNCTION__);
2106                 return ERR_PTR(-ENOMEM);
2107         }
2108
2109         np                   = netdev_priv(netdev);
2110         np->xbdev            = dev;
2111
2112         spin_lock_init(&np->tx_lock);
2113         spin_lock_init(&np->rx_lock);
2114
2115         init_accelerator_vif(np, dev);
2116
2117         skb_queue_head_init(&np->rx_batch);
2118         np->rx_target     = RX_DFL_MIN_TARGET;
2119         np->rx_min_target = RX_DFL_MIN_TARGET;
2120         np->rx_max_target = RX_MAX_TARGET;
2121
2122         init_timer(&np->rx_refill_timer);
2123         np->rx_refill_timer.data = (unsigned long)netdev;
2124         np->rx_refill_timer.function = rx_refill_timeout;
2125
2126         err = -ENOMEM;
2127         np->stats = alloc_percpu(struct netfront_stats);
2128         if (np->stats == NULL)
2129                 goto exit;
2130
2131         /* Initialise {tx,rx}_skbs as a free chain containing every entry. */
2132         for (i = 0; i <= NET_TX_RING_SIZE; i++) {
2133                 np->tx_skbs[i] = (void *)((unsigned long) i+1);
2134                 np->grant_tx_ref[i] = GRANT_INVALID_REF;
2135         }
2136
2137         for (i = 0; i < NET_RX_RING_SIZE; i++) {
2138                 np->rx_skbs[i] = NULL;
2139                 np->grant_rx_ref[i] = GRANT_INVALID_REF;
2140         }
2141
2142         /* A grant for every tx ring slot */
2143         if (gnttab_alloc_grant_references(TX_MAX_TARGET,
2144                                           &np->gref_tx_head) < 0) {
2145                 pr_alert("#### netfront can't alloc tx grant refs\n");
2146                 err = -ENOMEM;
2147                 goto exit_free_stats;
2148         }
2149         /* A grant for every rx ring slot */
2150         if (gnttab_alloc_grant_references(RX_MAX_TARGET,
2151                                           &np->gref_rx_head) < 0) {
2152                 pr_alert("#### netfront can't alloc rx grant refs\n");
2153                 err = -ENOMEM;
2154                 goto exit_free_tx;
2155         }
2156
2157         netdev->netdev_ops      = &xennet_netdev_ops;
2158         netif_napi_add(netdev, &np->napi, netif_poll, 64);
2159         netdev->features        = NETIF_F_IP_CSUM | NETIF_F_RXCSUM |
2160                                   NETIF_F_GSO_ROBUST;
2161         netdev->hw_features     = NETIF_F_IP_CSUM | NETIF_F_SG | NETIF_F_TSO;
2162
2163         /*
2164          * Assume that all hw features are available for now. This set
2165          * will be adjusted by the call to netdev_update_features() in
2166          * xennet_connect() which is the earliest point where we can
2167          * negotiate with the backend regarding supported features.
2168          */
2169         netdev->features |= netdev->hw_features;
2170
2171         SET_ETHTOOL_OPS(netdev, &network_ethtool_ops);
2172         SET_NETDEV_DEV(netdev, &dev->dev);
2173
2174         np->netdev = netdev;
2175
2176         netfront_carrier_off(np);
2177
2178         return netdev;
2179
2180  exit_free_tx:
2181         gnttab_free_grant_references(np->gref_tx_head);
2182  exit_free_stats:
2183         free_percpu(np->stats);
2184  exit:
2185         free_netdev(netdev);
2186         return ERR_PTR(err);
2187 }
2188
2189 static void netif_release_rings(struct netfront_info *info)
2190 {
2191         end_access(info->tx_ring_ref, info->tx.sring);
2192         end_access(info->rx_ring_ref, info->rx.sring);
2193         info->tx_ring_ref = GRANT_INVALID_REF;
2194         info->rx_ring_ref = GRANT_INVALID_REF;
2195         info->tx.sring = NULL;
2196         info->rx.sring = NULL;
2197 }
2198
2199 static void netif_disconnect_backend(struct netfront_info *info)
2200 {
2201         /* Stop old i/f to prevent errors whilst we rebuild the state. */
2202         spin_lock_bh(&info->rx_lock);
2203         spin_lock_irq(&info->tx_lock);
2204         netfront_carrier_off(info);
2205         spin_unlock_irq(&info->tx_lock);
2206         spin_unlock_bh(&info->rx_lock);
2207
2208         if (info->irq)
2209                 unbind_from_irqhandler(info->irq, info->netdev);
2210         info->irq = 0;
2211
2212         netif_release_rings(info);
2213 }
2214
2215
2216 static void end_access(int ref, void *page)
2217 {
2218         if (ref != GRANT_INVALID_REF)
2219                 gnttab_end_foreign_access(ref, (unsigned long)page);
2220 }
2221
2222
2223 /* ** Driver registration ** */
2224
2225
2226 static const struct xenbus_device_id netfront_ids[] = {
2227         { "vif" },
2228         { "" }
2229 };
2230 MODULE_ALIAS("xen:vif");
2231
2232 static DEFINE_XENBUS_DRIVER(netfront, ,
2233         .probe = netfront_probe,
2234         .remove = __devexit_p(netfront_remove),
2235         .suspend = netfront_suspend,
2236         .suspend_cancel = netfront_suspend_cancel,
2237         .resume = netfront_resume,
2238         .otherend_changed = backend_changed,
2239 );
2240
2241
2242 static int __init netif_init(void)
2243 {
2244         if (!is_running_on_xen())
2245                 return -ENODEV;
2246
2247 #ifdef CONFIG_XEN
2248         if (MODPARM_rx_flip && MODPARM_rx_copy) {
2249                 WPRINTK("Cannot specify both rx_copy and rx_flip.\n");
2250                 return -EINVAL;
2251         }
2252
2253         if (!MODPARM_rx_flip && !MODPARM_rx_copy)
2254                 MODPARM_rx_copy = true; /* Default is to copy. */
2255 #endif
2256
2257         netif_init_accel();
2258
2259         IPRINTK("Initialising virtual ethernet driver.\n");
2260
2261         return xenbus_register_frontend(&netfront_driver);
2262 }
2263 module_init(netif_init);
2264
2265
2266 static void __exit netif_exit(void)
2267 {
2268         xenbus_unregister_driver(&netfront_driver);
2269
2270         netif_exit_accel();
2271 }
2272 module_exit(netif_exit);
2273
2274 MODULE_LICENSE("Dual BSD/GPL");