- patches.rt/0001-sched-count-of-queued-RT-tasks.patch: Delete.
[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/arp.h>
54 #include <net/route.h>
55 #include <asm/uaccess.h>
56 #include <xen/evtchn.h>
57 #include <xen/xenbus.h>
58 #include <xen/interface/io/netif.h>
59 #include <xen/interface/memory.h>
60 #include <xen/balloon.h>
61 #include <asm/page.h>
62 #include <asm/maddr.h>
63 #include <asm/uaccess.h>
64 #include <xen/interface/grant_table.h>
65 #include <xen/gnttab.h>
66 #include <xen/hypercall.h>
67
68 struct netfront_cb {
69         struct page *page;
70         unsigned offset;
71 };
72
73 #define NETFRONT_SKB_CB(skb)    ((struct netfront_cb *)((skb)->cb))
74
75 #include "netfront.h"
76
77 /*
78  * Mutually-exclusive module options to select receive data path:
79  *  rx_copy : Packets are copied by network backend into local memory
80  *  rx_flip : Page containing packet data is transferred to our ownership
81  * For fully-virtualised guests there is no option - copying must be used.
82  * For paravirtualised guests, flipping is the default.
83  */
84 #ifdef CONFIG_XEN
85 static int MODPARM_rx_copy = 0;
86 module_param_named(rx_copy, MODPARM_rx_copy, bool, 0);
87 MODULE_PARM_DESC(rx_copy, "Copy packets from network card (rather than flip)");
88 static int MODPARM_rx_flip = 0;
89 module_param_named(rx_flip, MODPARM_rx_flip, bool, 0);
90 MODULE_PARM_DESC(rx_flip, "Flip packets from network card (rather than copy)");
91 #else
92 static const int MODPARM_rx_copy = 1;
93 static const int MODPARM_rx_flip = 0;
94 #endif
95
96 #define RX_COPY_THRESHOLD 256
97
98 /* If we don't have GSO, fake things up so that we never try to use it. */
99 #if defined(NETIF_F_GSO)
100 #define HAVE_GSO                        1
101 #define HAVE_TSO                        1 /* TSO is a subset of GSO */
102 #define HAVE_CSUM_OFFLOAD               1
103 static inline void dev_disable_gso_features(struct net_device *dev)
104 {
105         /* Turn off all GSO bits except ROBUST. */
106         dev->features &= (1 << NETIF_F_GSO_SHIFT) - 1;
107         dev->features |= NETIF_F_GSO_ROBUST;
108 }
109 #elif defined(NETIF_F_TSO)
110 #define HAVE_GSO                       0
111 #define HAVE_TSO                       1
112
113 /* Some older kernels cannot cope with incorrect checksums,
114  * particularly in netfilter. I'm not sure there is 100% correlation
115  * with the presence of NETIF_F_TSO but it appears to be a good first
116  * approximiation.
117  */
118 #define HAVE_CSUM_OFFLOAD              0
119
120 #define gso_size tso_size
121 #define gso_segs tso_segs
122 static inline void dev_disable_gso_features(struct net_device *dev)
123 {
124        /* Turn off all TSO bits. */
125        dev->features &= ~NETIF_F_TSO;
126 }
127 static inline int skb_is_gso(const struct sk_buff *skb)
128 {
129         return skb_shinfo(skb)->tso_size;
130 }
131 static inline int skb_gso_ok(struct sk_buff *skb, int features)
132 {
133         return (features & NETIF_F_TSO);
134 }
135
136 static inline int netif_needs_gso(struct net_device *dev, struct sk_buff *skb)
137 {
138         return skb_is_gso(skb) &&
139                (!skb_gso_ok(skb, dev->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(dev, skb)       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...)                           \
211         printk(KERN_INFO "netfront: " fmt, ##args)
212 #define WPRINTK(fmt, args...)                           \
213         printk(KERN_WARNING "netfront: " fmt, ##args)
214
215 static int setup_device(struct xenbus_device *, struct netfront_info *);
216 static struct net_device *create_netdev(struct xenbus_device *);
217
218 static void end_access(int, void *);
219 static void netif_disconnect_backend(struct netfront_info *);
220
221 static int network_connect(struct net_device *);
222 static void network_tx_buf_gc(struct net_device *);
223 static void network_alloc_rx_buffers(struct net_device *);
224 static void send_fake_arp(struct net_device *);
225
226 static irqreturn_t netif_int(int irq, void *dev_id);
227
228 #ifdef CONFIG_SYSFS
229 static int xennet_sysfs_addif(struct net_device *netdev);
230 static void xennet_sysfs_delif(struct net_device *netdev);
231 #else /* !CONFIG_SYSFS */
232 #define xennet_sysfs_addif(dev) (0)
233 #define xennet_sysfs_delif(dev) do { } while(0)
234 #endif
235
236 static inline int xennet_can_sg(struct net_device *dev)
237 {
238         return dev->features & NETIF_F_SG;
239 }
240
241 /**
242  * Entry point to this code when a new device is created.  Allocate the basic
243  * structures and the ring buffers for communication with the backend, and
244  * inform the backend of the appropriate details for those.
245  */
246 static int __devinit netfront_probe(struct xenbus_device *dev,
247                                     const struct xenbus_device_id *id)
248 {
249         int err;
250         struct net_device *netdev;
251         struct netfront_info *info;
252
253         netdev = create_netdev(dev);
254         if (IS_ERR(netdev)) {
255                 err = PTR_ERR(netdev);
256                 xenbus_dev_fatal(dev, err, "creating netdev");
257                 return err;
258         }
259
260         info = netdev_priv(netdev);
261         dev->dev.driver_data = info;
262
263         err = register_netdev(info->netdev);
264         if (err) {
265                 printk(KERN_WARNING "%s: register_netdev err=%d\n",
266                        __FUNCTION__, err);
267                 goto fail;
268         }
269
270         err = xennet_sysfs_addif(info->netdev);
271         if (err) {
272                 unregister_netdev(info->netdev);
273                 printk(KERN_WARNING "%s: add sysfs failed err=%d\n",
274                        __FUNCTION__, err);
275                 goto fail;
276         }
277
278         return 0;
279
280  fail:
281         free_netdev(netdev);
282         dev->dev.driver_data = NULL;
283         return err;
284 }
285
286 static int __devexit netfront_remove(struct xenbus_device *dev)
287 {
288         struct netfront_info *info = dev->dev.driver_data;
289
290         DPRINTK("%s\n", dev->nodename);
291
292         netfront_accelerator_call_remove(info, dev);
293
294         netif_disconnect_backend(info);
295
296         del_timer_sync(&info->rx_refill_timer);
297
298         xennet_sysfs_delif(info->netdev);
299
300         unregister_netdev(info->netdev);
301
302         free_netdev(info->netdev);
303
304         return 0;
305 }
306
307
308 static int netfront_suspend(struct xenbus_device *dev)
309 {
310         struct netfront_info *info = dev->dev.driver_data;
311         return netfront_accelerator_suspend(info, dev);
312 }
313
314
315 static int netfront_suspend_cancel(struct xenbus_device *dev)
316 {
317         struct netfront_info *info = dev->dev.driver_data;
318         return netfront_accelerator_suspend_cancel(info, dev);
319 }
320
321
322 /**
323  * We are reconnecting to the backend, due to a suspend/resume, or a backend
324  * driver restart.  We tear down our netif structure and recreate it, but
325  * leave the device-layer structures intact so that this is transparent to the
326  * rest of the kernel.
327  */
328 static int netfront_resume(struct xenbus_device *dev)
329 {
330         struct netfront_info *info = dev->dev.driver_data;
331
332         DPRINTK("%s\n", dev->nodename);
333
334         netfront_accelerator_resume(info, dev);
335
336         netif_disconnect_backend(info);
337         return 0;
338 }
339
340 static int xen_net_read_mac(struct xenbus_device *dev, u8 mac[])
341 {
342         char *s, *e, *macstr;
343         int i;
344
345         macstr = s = xenbus_read(XBT_NIL, dev->nodename, "mac", NULL);
346         if (IS_ERR(macstr))
347                 return PTR_ERR(macstr);
348
349         for (i = 0; i < ETH_ALEN; i++) {
350                 mac[i] = simple_strtoul(s, &e, 16);
351                 if ((s == e) || (*e != ((i == ETH_ALEN-1) ? '\0' : ':'))) {
352                         kfree(macstr);
353                         return -ENOENT;
354                 }
355                 s = e+1;
356         }
357
358         kfree(macstr);
359         return 0;
360 }
361
362 /* Common code used when first setting up, and when resuming. */
363 static int talk_to_backend(struct xenbus_device *dev,
364                            struct netfront_info *info)
365 {
366         const char *message;
367         struct xenbus_transaction xbt;
368         int err;
369
370         err = xen_net_read_mac(dev, info->mac);
371         if (err) {
372                 xenbus_dev_fatal(dev, err, "parsing %s/mac", dev->nodename);
373                 goto out;
374         }
375
376         /* Create shared ring, alloc event channel. */
377         err = setup_device(dev, info);
378         if (err)
379                 goto out;
380
381         /* This will load an accelerator if one is configured when the
382          * watch fires */
383         netfront_accelerator_add_watch(info);
384
385 again:
386         err = xenbus_transaction_start(&xbt);
387         if (err) {
388                 xenbus_dev_fatal(dev, err, "starting transaction");
389                 goto destroy_ring;
390         }
391
392         err = xenbus_printf(xbt, dev->nodename, "tx-ring-ref","%u",
393                             info->tx_ring_ref);
394         if (err) {
395                 message = "writing tx ring-ref";
396                 goto abort_transaction;
397         }
398         err = xenbus_printf(xbt, dev->nodename, "rx-ring-ref","%u",
399                             info->rx_ring_ref);
400         if (err) {
401                 message = "writing rx ring-ref";
402                 goto abort_transaction;
403         }
404         err = xenbus_printf(xbt, dev->nodename,
405                             "event-channel", "%u",
406                             irq_to_evtchn_port(info->irq));
407         if (err) {
408                 message = "writing event-channel";
409                 goto abort_transaction;
410         }
411
412         err = xenbus_printf(xbt, dev->nodename, "request-rx-copy", "%u",
413                             info->copying_receiver);
414         if (err) {
415                 message = "writing request-rx-copy";
416                 goto abort_transaction;
417         }
418
419         err = xenbus_printf(xbt, dev->nodename, "feature-rx-notify", "%d", 1);
420         if (err) {
421                 message = "writing feature-rx-notify";
422                 goto abort_transaction;
423         }
424
425         err = xenbus_printf(xbt, dev->nodename, "feature-no-csum-offload",
426                             "%d", !HAVE_CSUM_OFFLOAD);
427         if (err) {
428                 message = "writing feature-no-csum-offload";
429                 goto abort_transaction;
430         }
431
432         err = xenbus_printf(xbt, dev->nodename, "feature-sg", "%d", 1);
433         if (err) {
434                 message = "writing feature-sg";
435                 goto abort_transaction;
436         }
437
438         err = xenbus_printf(xbt, dev->nodename, "feature-gso-tcpv4", "%d",
439                             HAVE_TSO);
440         if (err) {
441                 message = "writing feature-gso-tcpv4";
442                 goto abort_transaction;
443         }
444
445         err = xenbus_transaction_end(xbt, 0);
446         if (err) {
447                 if (err == -EAGAIN)
448                         goto again;
449                 xenbus_dev_fatal(dev, err, "completing transaction");
450                 goto destroy_ring;
451         }
452
453         return 0;
454
455  abort_transaction:
456         xenbus_transaction_end(xbt, 1);
457         xenbus_dev_fatal(dev, err, "%s", message);
458  destroy_ring:
459         netfront_accelerator_call_remove(info, dev);
460         netif_disconnect_backend(info);
461  out:
462         return err;
463 }
464
465 static int setup_device(struct xenbus_device *dev, struct netfront_info *info)
466 {
467         struct netif_tx_sring *txs;
468         struct netif_rx_sring *rxs;
469         int err;
470         struct net_device *netdev = info->netdev;
471
472         info->tx_ring_ref = GRANT_INVALID_REF;
473         info->rx_ring_ref = GRANT_INVALID_REF;
474         info->rx.sring = NULL;
475         info->tx.sring = NULL;
476         info->irq = 0;
477
478         txs = (struct netif_tx_sring *)get_zeroed_page(GFP_KERNEL|__GFP_HIGH);
479         if (!txs) {
480                 err = -ENOMEM;
481                 xenbus_dev_fatal(dev, err, "allocating tx ring page");
482                 goto fail;
483         }
484         SHARED_RING_INIT(txs);
485         FRONT_RING_INIT(&info->tx, txs, PAGE_SIZE);
486
487         err = xenbus_grant_ring(dev, virt_to_mfn(txs));
488         if (err < 0) {
489                 free_page((unsigned long)txs);
490                 goto fail;
491         }
492         info->tx_ring_ref = err;
493
494         rxs = (struct netif_rx_sring *)get_zeroed_page(GFP_KERNEL|__GFP_HIGH);
495         if (!rxs) {
496                 err = -ENOMEM;
497                 xenbus_dev_fatal(dev, err, "allocating rx ring page");
498                 goto fail;
499         }
500         SHARED_RING_INIT(rxs);
501         FRONT_RING_INIT(&info->rx, rxs, PAGE_SIZE);
502
503         err = xenbus_grant_ring(dev, virt_to_mfn(rxs));
504         if (err < 0) {
505                 free_page((unsigned long)rxs);
506                 goto fail;
507         }
508         info->rx_ring_ref = err;
509
510         memcpy(netdev->dev_addr, info->mac, ETH_ALEN);
511
512         err = bind_listening_port_to_irqhandler(
513                 dev->otherend_id, netif_int, IRQF_SAMPLE_RANDOM, netdev->name,
514                 netdev);
515         if (err < 0)
516                 goto fail;
517         info->irq = err;
518
519         return 0;
520
521  fail:
522         return err;
523 }
524
525 /**
526  * Callback received when the backend's state changes.
527  */
528 static void backend_changed(struct xenbus_device *dev,
529                             enum xenbus_state backend_state)
530 {
531         struct netfront_info *np = dev->dev.driver_data;
532         struct net_device *netdev = np->netdev;
533
534         DPRINTK("%s\n", xenbus_strstate(backend_state));
535
536         switch (backend_state) {
537         case XenbusStateInitialising:
538         case XenbusStateInitialised:
539         case XenbusStateConnected:
540         case XenbusStateUnknown:
541         case XenbusStateClosed:
542                 break;
543
544         case XenbusStateInitWait:
545                 if (dev->state != XenbusStateInitialising)
546                         break;
547                 if (network_connect(netdev) != 0)
548                         break;
549                 xenbus_switch_state(dev, XenbusStateConnected);
550                 send_fake_arp(netdev);
551                 break;
552
553         case XenbusStateClosing:
554                 xenbus_frontend_closed(dev);
555                 break;
556         }
557 }
558
559 /** Send a packet on a net device to encourage switches to learn the
560  * MAC. We send a fake ARP request.
561  *
562  * @param dev device
563  * @return 0 on success, error code otherwise
564  */
565 static void send_fake_arp(struct net_device *dev)
566 {
567 #ifdef CONFIG_INET
568         struct sk_buff *skb;
569         u32             src_ip, dst_ip;
570
571         dst_ip = INADDR_BROADCAST;
572         src_ip = inet_select_addr(dev, dst_ip, RT_SCOPE_LINK);
573
574         /* No IP? Then nothing to do. */
575         if (src_ip == 0)
576                 return;
577
578         skb = arp_create(ARPOP_REPLY, ETH_P_ARP,
579                          dst_ip, dev, src_ip,
580                          /*dst_hw*/ NULL, /*src_hw*/ NULL,
581                          /*target_hw*/ dev->dev_addr);
582         if (skb == NULL)
583                 return;
584
585         dev_queue_xmit(skb);
586 #endif
587 }
588
589 static inline int netfront_tx_slot_available(struct netfront_info *np)
590 {
591         return ((np->tx.req_prod_pvt - np->tx.rsp_cons) <
592                 (TX_MAX_TARGET - MAX_SKB_FRAGS - 2));
593 }
594
595
596 static inline void network_maybe_wake_tx(struct net_device *dev)
597 {
598         struct netfront_info *np = netdev_priv(dev);
599
600         if (unlikely(netif_queue_stopped(dev)) &&
601             netfront_tx_slot_available(np) &&
602             likely(netif_running(dev)) &&
603             netfront_check_accelerator_queue_ready(dev, np))
604                 netif_wake_queue(dev);
605 }
606
607
608 int netfront_check_queue_ready(struct net_device *dev)
609 {
610         struct netfront_info *np = netdev_priv(dev);
611
612         return unlikely(netif_queue_stopped(dev)) &&
613                 netfront_tx_slot_available(np) &&
614                 likely(netif_running(dev));
615 }
616 EXPORT_SYMBOL(netfront_check_queue_ready);
617
618
619 static int network_open(struct net_device *dev)
620 {
621         struct netfront_info *np = netdev_priv(dev);
622
623         memset(&np->stats, 0, sizeof(np->stats));
624
625         spin_lock_bh(&np->rx_lock);
626         if (netfront_carrier_ok(np)) {
627                 network_alloc_rx_buffers(dev);
628                 np->rx.sring->rsp_event = np->rx.rsp_cons + 1;
629                 if (RING_HAS_UNCONSUMED_RESPONSES(&np->rx)){
630                         netfront_accelerator_call_stop_napi_irq(np, dev);
631
632                         netif_rx_schedule(dev, &np->napi);
633                 }
634         }
635         spin_unlock_bh(&np->rx_lock);
636
637         network_maybe_wake_tx(dev);
638
639         return 0;
640 }
641
642 static void network_tx_buf_gc(struct net_device *dev)
643 {
644         RING_IDX cons, prod;
645         unsigned short id;
646         struct netfront_info *np = netdev_priv(dev);
647         struct sk_buff *skb;
648
649         BUG_ON(!netfront_carrier_ok(np));
650
651         do {
652                 prod = np->tx.sring->rsp_prod;
653                 rmb(); /* Ensure we see responses up to 'rp'. */
654
655                 for (cons = np->tx.rsp_cons; cons != prod; cons++) {
656                         struct netif_tx_response *txrsp;
657
658                         txrsp = RING_GET_RESPONSE(&np->tx, cons);
659                         if (txrsp->status == NETIF_RSP_NULL)
660                                 continue;
661
662                         id  = txrsp->id;
663                         skb = np->tx_skbs[id];
664                         if (unlikely(gnttab_query_foreign_access(
665                                 np->grant_tx_ref[id]) != 0)) {
666                                 printk(KERN_ALERT "network_tx_buf_gc: warning "
667                                        "-- grant still in use by backend "
668                                        "domain.\n");
669                                 BUG();
670                         }
671                         gnttab_end_foreign_access_ref(np->grant_tx_ref[id]);
672                         gnttab_release_grant_reference(
673                                 &np->gref_tx_head, np->grant_tx_ref[id]);
674                         np->grant_tx_ref[id] = GRANT_INVALID_REF;
675                         add_id_to_freelist(np->tx_skbs, id);
676                         dev_kfree_skb_irq(skb);
677                 }
678
679                 np->tx.rsp_cons = prod;
680
681                 /*
682                  * Set a new event, then check for race with update of tx_cons.
683                  * Note that it is essential to schedule a callback, no matter
684                  * how few buffers are pending. Even if there is space in the
685                  * transmit ring, higher layers may be blocked because too much
686                  * data is outstanding: in such cases notification from Xen is
687                  * likely to be the only kick that we'll get.
688                  */
689                 np->tx.sring->rsp_event =
690                         prod + ((np->tx.sring->req_prod - prod) >> 1) + 1;
691                 mb();
692         } while ((cons == prod) && (prod != np->tx.sring->rsp_prod));
693
694         network_maybe_wake_tx(dev);
695 }
696
697 static void rx_refill_timeout(unsigned long data)
698 {
699         struct net_device *dev = (struct net_device *)data;
700         struct netfront_info *np = netdev_priv(dev);
701
702         netfront_accelerator_call_stop_napi_irq(np, dev);
703
704         netif_rx_schedule(dev, &np->napi);
705 }
706
707 static void network_alloc_rx_buffers(struct net_device *dev)
708 {
709         unsigned short id;
710         struct netfront_info *np = netdev_priv(dev);
711         struct sk_buff *skb;
712         struct page *page;
713         int i, batch_target, notify;
714         RING_IDX req_prod = np->rx.req_prod_pvt;
715         struct xen_memory_reservation reservation;
716         grant_ref_t ref;
717         unsigned long pfn;
718         void *vaddr;
719         int nr_flips;
720         netif_rx_request_t *req;
721
722         if (unlikely(!netfront_carrier_ok(np)))
723                 return;
724
725         /*
726          * Allocate skbuffs greedily, even though we batch updates to the
727          * receive ring. This creates a less bursty demand on the memory
728          * allocator, so should reduce the chance of failed allocation requests
729          * both for ourself and for other kernel subsystems.
730          */
731         batch_target = np->rx_target - (req_prod - np->rx.rsp_cons);
732         for (i = skb_queue_len(&np->rx_batch); i < batch_target; i++) {
733                 /*
734                  * Allocate an skb and a page. Do not use __dev_alloc_skb as
735                  * that will allocate page-sized buffers which is not
736                  * necessary here.
737                  * 16 bytes added as necessary headroom for netif_receive_skb.
738                  */
739                 skb = alloc_skb(RX_COPY_THRESHOLD + 16 + NET_IP_ALIGN,
740                                 GFP_ATOMIC | __GFP_NOWARN);
741                 if (unlikely(!skb))
742                         goto no_skb;
743
744                 page = alloc_page(GFP_ATOMIC | __GFP_NOWARN);
745                 if (!page) {
746                         kfree_skb(skb);
747 no_skb:
748                         /* Any skbuffs queued for refill? Force them out. */
749                         if (i != 0)
750                                 goto refill;
751                         /* Could not allocate any skbuffs. Try again later. */
752                         mod_timer(&np->rx_refill_timer,
753                                   jiffies + (HZ/10));
754                         break;
755                 }
756
757                 skb_reserve(skb, 16 + NET_IP_ALIGN); /* mimic dev_alloc_skb() */
758                 skb_shinfo(skb)->frags[0].page = page;
759                 skb_shinfo(skb)->nr_frags = 1;
760                 __skb_queue_tail(&np->rx_batch, skb);
761         }
762
763         /* Is the batch large enough to be worthwhile? */
764         if (i < (np->rx_target/2)) {
765                 if (req_prod > np->rx.sring->req_prod)
766                         goto push;
767                 return;
768         }
769
770         /* Adjust our fill target if we risked running out of buffers. */
771         if (((req_prod - np->rx.sring->rsp_prod) < (np->rx_target / 4)) &&
772             ((np->rx_target *= 2) > np->rx_max_target))
773                 np->rx_target = np->rx_max_target;
774
775  refill:
776         for (nr_flips = i = 0; ; i++) {
777                 if ((skb = __skb_dequeue(&np->rx_batch)) == NULL)
778                         break;
779
780                 skb->dev = dev;
781
782                 id = xennet_rxidx(req_prod + i);
783
784                 BUG_ON(np->rx_skbs[id]);
785                 np->rx_skbs[id] = skb;
786
787                 ref = gnttab_claim_grant_reference(&np->gref_rx_head);
788                 BUG_ON((signed short)ref < 0);
789                 np->grant_rx_ref[id] = ref;
790
791                 pfn = page_to_pfn(skb_shinfo(skb)->frags[0].page);
792                 vaddr = page_address(skb_shinfo(skb)->frags[0].page);
793
794                 req = RING_GET_REQUEST(&np->rx, req_prod + i);
795                 if (!np->copying_receiver) {
796                         gnttab_grant_foreign_transfer_ref(ref,
797                                                           np->xbdev->otherend_id,
798                                                           pfn);
799                         np->rx_pfn_array[nr_flips] = pfn_to_mfn(pfn);
800                         if (!xen_feature(XENFEAT_auto_translated_physmap)) {
801                                 /* Remove this page before passing
802                                  * back to Xen. */
803                                 set_phys_to_machine(pfn, INVALID_P2M_ENTRY);
804                                 MULTI_update_va_mapping(np->rx_mcl+i,
805                                                         (unsigned long)vaddr,
806                                                         __pte(0), 0);
807                         }
808                         nr_flips++;
809                 } else {
810                         gnttab_grant_foreign_access_ref(ref,
811                                                         np->xbdev->otherend_id,
812                                                         pfn_to_mfn(pfn),
813                                                         0);
814                 }
815
816                 req->id = id;
817                 req->gref = ref;
818         }
819
820         if ( nr_flips != 0 ) {
821                 /* Tell the ballon driver what is going on. */
822                 balloon_update_driver_allowance(i);
823
824                 set_xen_guest_handle(reservation.extent_start,
825                                      np->rx_pfn_array);
826                 reservation.nr_extents   = nr_flips;
827                 reservation.extent_order = 0;
828                 reservation.address_bits = 0;
829                 reservation.domid        = DOMID_SELF;
830
831                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
832                         /* After all PTEs have been zapped, flush the TLB. */
833                         np->rx_mcl[i-1].args[MULTI_UVMFLAGS_INDEX] =
834                                 UVMF_TLB_FLUSH|UVMF_ALL;
835
836                         /* Give away a batch of pages. */
837                         np->rx_mcl[i].op = __HYPERVISOR_memory_op;
838                         np->rx_mcl[i].args[0] = XENMEM_decrease_reservation;
839                         np->rx_mcl[i].args[1] = (unsigned long)&reservation;
840
841                         /* Zap PTEs and give away pages in one big
842                          * multicall. */
843                         if (unlikely(HYPERVISOR_multicall(np->rx_mcl, i+1)))
844                                 BUG();
845
846                         /* Check return status of HYPERVISOR_memory_op(). */
847                         if (unlikely(np->rx_mcl[i].result != i))
848                                 panic("Unable to reduce memory reservation\n");
849                         while (i--)
850                                 BUG_ON(np->rx_mcl[i].result);
851                 } else {
852                         if (HYPERVISOR_memory_op(XENMEM_decrease_reservation,
853                                                  &reservation) != i)
854                                 panic("Unable to reduce memory reservation\n");
855                 }
856         } else {
857                 wmb();
858         }
859
860         /* Above is a suitable barrier to ensure backend will see requests. */
861         np->rx.req_prod_pvt = req_prod + i;
862  push:
863         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&np->rx, notify);
864         if (notify)
865                 notify_remote_via_irq(np->irq);
866 }
867
868 static void xennet_make_frags(struct sk_buff *skb, struct net_device *dev,
869                               struct netif_tx_request *tx)
870 {
871         struct netfront_info *np = netdev_priv(dev);
872         char *data = skb->data;
873         unsigned long mfn;
874         RING_IDX prod = np->tx.req_prod_pvt;
875         int frags = skb_shinfo(skb)->nr_frags;
876         unsigned int offset = offset_in_page(data);
877         unsigned int len = skb_headlen(skb);
878         unsigned int id;
879         grant_ref_t ref;
880         int i;
881
882         while (len > PAGE_SIZE - offset) {
883                 tx->size = PAGE_SIZE - offset;
884                 tx->flags |= NETTXF_more_data;
885                 len -= tx->size;
886                 data += tx->size;
887                 offset = 0;
888
889                 id = get_id_from_freelist(np->tx_skbs);
890                 np->tx_skbs[id] = skb_get(skb);
891                 tx = RING_GET_REQUEST(&np->tx, prod++);
892                 tx->id = id;
893                 ref = gnttab_claim_grant_reference(&np->gref_tx_head);
894                 BUG_ON((signed short)ref < 0);
895
896                 mfn = virt_to_mfn(data);
897                 gnttab_grant_foreign_access_ref(ref, np->xbdev->otherend_id,
898                                                 mfn, GTF_readonly);
899
900                 tx->gref = np->grant_tx_ref[id] = ref;
901                 tx->offset = offset;
902                 tx->size = len;
903                 tx->flags = 0;
904         }
905
906         for (i = 0; i < frags; i++) {
907                 skb_frag_t *frag = skb_shinfo(skb)->frags + i;
908
909                 tx->flags |= NETTXF_more_data;
910
911                 id = get_id_from_freelist(np->tx_skbs);
912                 np->tx_skbs[id] = skb_get(skb);
913                 tx = RING_GET_REQUEST(&np->tx, prod++);
914                 tx->id = id;
915                 ref = gnttab_claim_grant_reference(&np->gref_tx_head);
916                 BUG_ON((signed short)ref < 0);
917
918                 mfn = pfn_to_mfn(page_to_pfn(frag->page));
919                 gnttab_grant_foreign_access_ref(ref, np->xbdev->otherend_id,
920                                                 mfn, GTF_readonly);
921
922                 tx->gref = np->grant_tx_ref[id] = ref;
923                 tx->offset = frag->page_offset;
924                 tx->size = frag->size;
925                 tx->flags = 0;
926         }
927
928         np->tx.req_prod_pvt = prod;
929 }
930
931 static int network_start_xmit(struct sk_buff *skb, struct net_device *dev)
932 {
933         unsigned short id;
934         struct netfront_info *np = netdev_priv(dev);
935         struct netif_tx_request *tx;
936         struct netif_extra_info *extra;
937         char *data = skb->data;
938         RING_IDX i;
939         grant_ref_t ref;
940         unsigned long mfn;
941         int notify;
942         int frags = skb_shinfo(skb)->nr_frags;
943         unsigned int offset = offset_in_page(data);
944         unsigned int len = skb_headlen(skb);
945
946         /* Check the fast path, if hooks are available */
947         if (np->accel_vif_state.hooks && 
948             np->accel_vif_state.hooks->start_xmit(skb, dev)) { 
949                 /* Fast path has sent this packet */ 
950                 return 0; 
951         } 
952
953         frags += (offset + len + PAGE_SIZE - 1) / PAGE_SIZE;
954         if (unlikely(frags > MAX_SKB_FRAGS + 1)) {
955                 printk(KERN_ALERT "xennet: skb rides the rocket: %d frags\n",
956                        frags);
957                 dump_stack();
958                 goto drop;
959         }
960
961         spin_lock_irq(&np->tx_lock);
962
963         if (unlikely(!netfront_carrier_ok(np) ||
964                      (frags > 1 && !xennet_can_sg(dev)) ||
965                      netif_needs_gso(dev, skb))) {
966                 spin_unlock_irq(&np->tx_lock);
967                 goto drop;
968         }
969
970         i = np->tx.req_prod_pvt;
971
972         id = get_id_from_freelist(np->tx_skbs);
973         np->tx_skbs[id] = skb;
974
975         tx = RING_GET_REQUEST(&np->tx, i);
976
977         tx->id   = id;
978         ref = gnttab_claim_grant_reference(&np->gref_tx_head);
979         BUG_ON((signed short)ref < 0);
980         mfn = virt_to_mfn(data);
981         gnttab_grant_foreign_access_ref(
982                 ref, np->xbdev->otherend_id, mfn, GTF_readonly);
983         tx->gref = np->grant_tx_ref[id] = ref;
984         tx->offset = offset;
985         tx->size = len;
986
987         tx->flags = 0;
988         extra = NULL;
989
990         if (skb->ip_summed == CHECKSUM_PARTIAL) /* local packet? */
991                 tx->flags |= NETTXF_csum_blank | NETTXF_data_validated;
992 #ifdef CONFIG_XEN
993         if (skb->proto_data_valid) /* remote but checksummed? */
994                 tx->flags |= NETTXF_data_validated;
995 #endif
996
997 #if HAVE_TSO
998         if (skb_shinfo(skb)->gso_size) {
999                 struct netif_extra_info *gso = (struct netif_extra_info *)
1000                         RING_GET_REQUEST(&np->tx, ++i);
1001
1002                 if (extra)
1003                         extra->flags |= XEN_NETIF_EXTRA_FLAG_MORE;
1004                 else
1005                         tx->flags |= NETTXF_extra_info;
1006
1007                 gso->u.gso.size = skb_shinfo(skb)->gso_size;
1008                 gso->u.gso.type = XEN_NETIF_GSO_TYPE_TCPV4;
1009                 gso->u.gso.pad = 0;
1010                 gso->u.gso.features = 0;
1011
1012                 gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
1013                 gso->flags = 0;
1014                 extra = gso;
1015         }
1016 #endif
1017
1018         np->tx.req_prod_pvt = i + 1;
1019
1020         xennet_make_frags(skb, dev, tx);
1021         tx->size = skb->len;
1022
1023         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&np->tx, notify);
1024         if (notify)
1025                 notify_remote_via_irq(np->irq);
1026
1027         np->stats.tx_bytes += skb->len;
1028         np->stats.tx_packets++;
1029
1030         /* Note: It is not safe to access skb after network_tx_buf_gc()! */
1031         network_tx_buf_gc(dev);
1032
1033         if (!netfront_tx_slot_available(np))
1034                 netif_stop_queue(dev);
1035
1036         spin_unlock_irq(&np->tx_lock);
1037
1038         return 0;
1039
1040  drop:
1041         np->stats.tx_dropped++;
1042         dev_kfree_skb(skb);
1043         return 0;
1044 }
1045
1046 static irqreturn_t netif_int(int irq, void *dev_id)
1047 {
1048         struct net_device *dev = dev_id;
1049         struct netfront_info *np = netdev_priv(dev);
1050         unsigned long flags;
1051
1052         spin_lock_irqsave(&np->tx_lock, flags);
1053
1054         if (likely(netfront_carrier_ok(np))) {
1055                 network_tx_buf_gc(dev);
1056                 /* Under tx_lock: protects access to rx shared-ring indexes. */
1057                 if (RING_HAS_UNCONSUMED_RESPONSES(&np->rx)) {
1058                         netfront_accelerator_call_stop_napi_irq(np, dev);
1059
1060                         netif_rx_schedule(dev, &np->napi);
1061                 }
1062         }
1063
1064         spin_unlock_irqrestore(&np->tx_lock, flags);
1065
1066         return IRQ_HANDLED;
1067 }
1068
1069 static void xennet_move_rx_slot(struct netfront_info *np, struct sk_buff *skb,
1070                                 grant_ref_t ref)
1071 {
1072         int new = xennet_rxidx(np->rx.req_prod_pvt);
1073
1074         BUG_ON(np->rx_skbs[new]);
1075         np->rx_skbs[new] = skb;
1076         np->grant_rx_ref[new] = ref;
1077         RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->id = new;
1078         RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->gref = ref;
1079         np->rx.req_prod_pvt++;
1080 }
1081
1082 int xennet_get_extras(struct netfront_info *np,
1083                       struct netif_extra_info *extras, RING_IDX rp)
1084
1085 {
1086         struct netif_extra_info *extra;
1087         RING_IDX cons = np->rx.rsp_cons;
1088         int err = 0;
1089
1090         do {
1091                 struct sk_buff *skb;
1092                 grant_ref_t ref;
1093
1094                 if (unlikely(cons + 1 == rp)) {
1095                         if (net_ratelimit())
1096                                 WPRINTK("Missing extra info\n");
1097                         err = -EBADR;
1098                         break;
1099                 }
1100
1101                 extra = (struct netif_extra_info *)
1102                         RING_GET_RESPONSE(&np->rx, ++cons);
1103
1104                 if (unlikely(!extra->type ||
1105                              extra->type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
1106                         if (net_ratelimit())
1107                                 WPRINTK("Invalid extra type: %d\n",
1108                                         extra->type);
1109                         err = -EINVAL;
1110                 } else {
1111                         memcpy(&extras[extra->type - 1], extra,
1112                                sizeof(*extra));
1113                 }
1114
1115                 skb = xennet_get_rx_skb(np, cons);
1116                 ref = xennet_get_rx_ref(np, cons);
1117                 xennet_move_rx_slot(np, skb, ref);
1118         } while (extra->flags & XEN_NETIF_EXTRA_FLAG_MORE);
1119
1120         np->rx.rsp_cons = cons;
1121         return err;
1122 }
1123
1124 static int xennet_get_responses(struct netfront_info *np,
1125                                 struct netfront_rx_info *rinfo, RING_IDX rp,
1126                                 struct sk_buff_head *list,
1127                                 int *pages_flipped_p)
1128 {
1129         int pages_flipped = *pages_flipped_p;
1130         struct mmu_update *mmu;
1131         struct multicall_entry *mcl;
1132         struct netif_rx_response *rx = &rinfo->rx;
1133         struct netif_extra_info *extras = rinfo->extras;
1134         RING_IDX cons = np->rx.rsp_cons;
1135         struct sk_buff *skb = xennet_get_rx_skb(np, cons);
1136         grant_ref_t ref = xennet_get_rx_ref(np, cons);
1137         int max = MAX_SKB_FRAGS + (rx->status <= RX_COPY_THRESHOLD);
1138         int frags = 1;
1139         int err = 0;
1140         unsigned long ret;
1141
1142         if (rx->flags & NETRXF_extra_info) {
1143                 err = xennet_get_extras(np, extras, rp);
1144                 cons = np->rx.rsp_cons;
1145         }
1146
1147         for (;;) {
1148                 unsigned long mfn;
1149
1150                 if (unlikely(rx->status < 0 ||
1151                              rx->offset + rx->status > PAGE_SIZE)) {
1152                         if (net_ratelimit())
1153                                 WPRINTK("rx->offset: %x, size: %u\n",
1154                                         rx->offset, rx->status);
1155                         xennet_move_rx_slot(np, skb, ref);
1156                         err = -EINVAL;
1157                         goto next;
1158                 }
1159
1160                 /*
1161                  * This definitely indicates a bug, either in this driver or in
1162                  * the backend driver. In future this should flag the bad
1163                  * situation to the system controller to reboot the backed.
1164                  */
1165                 if (ref == GRANT_INVALID_REF) {
1166                         if (net_ratelimit())
1167                                 WPRINTK("Bad rx response id %d.\n", rx->id);
1168                         err = -EINVAL;
1169                         goto next;
1170                 }
1171
1172                 if (!np->copying_receiver) {
1173                         /* Memory pressure, insufficient buffer
1174                          * headroom, ... */
1175                         if (!(mfn = gnttab_end_foreign_transfer_ref(ref))) {
1176                                 if (net_ratelimit())
1177                                         WPRINTK("Unfulfilled rx req "
1178                                                 "(id=%d, st=%d).\n",
1179                                                 rx->id, rx->status);
1180                                 xennet_move_rx_slot(np, skb, ref);
1181                                 err = -ENOMEM;
1182                                 goto next;
1183                         }
1184
1185                         if (!xen_feature(XENFEAT_auto_translated_physmap)) {
1186                                 /* Remap the page. */
1187                                 struct page *page =
1188                                         skb_shinfo(skb)->frags[0].page;
1189                                 unsigned long pfn = page_to_pfn(page);
1190                                 void *vaddr = page_address(page);
1191
1192                                 mcl = np->rx_mcl + pages_flipped;
1193                                 mmu = np->rx_mmu + pages_flipped;
1194
1195                                 MULTI_update_va_mapping(mcl,
1196                                                         (unsigned long)vaddr,
1197                                                         pfn_pte_ma(mfn,
1198                                                                    PAGE_KERNEL),
1199                                                         0);
1200                                 mmu->ptr = ((maddr_t)mfn << PAGE_SHIFT)
1201                                         | MMU_MACHPHYS_UPDATE;
1202                                 mmu->val = pfn;
1203
1204                                 set_phys_to_machine(pfn, mfn);
1205                         }
1206                         pages_flipped++;
1207                 } else {
1208                         ret = gnttab_end_foreign_access_ref(ref);
1209                         BUG_ON(!ret);
1210                 }
1211
1212                 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1213
1214                 __skb_queue_tail(list, skb);
1215
1216 next:
1217                 if (!(rx->flags & NETRXF_more_data))
1218                         break;
1219
1220                 if (cons + frags == rp) {
1221                         if (net_ratelimit())
1222                                 WPRINTK("Need more frags\n");
1223                         err = -ENOENT;
1224                         break;
1225                 }
1226
1227                 rx = RING_GET_RESPONSE(&np->rx, cons + frags);
1228                 skb = xennet_get_rx_skb(np, cons + frags);
1229                 ref = xennet_get_rx_ref(np, cons + frags);
1230                 frags++;
1231         }
1232
1233         if (unlikely(frags > max)) {
1234                 if (net_ratelimit())
1235                         WPRINTK("Too many frags\n");
1236                 err = -E2BIG;
1237         }
1238
1239         if (unlikely(err))
1240                 np->rx.rsp_cons = cons + frags;
1241
1242         *pages_flipped_p = pages_flipped;
1243
1244         return err;
1245 }
1246
1247 static RING_IDX xennet_fill_frags(struct netfront_info *np,
1248                                   struct sk_buff *skb,
1249                                   struct sk_buff_head *list)
1250 {
1251         struct skb_shared_info *shinfo = skb_shinfo(skb);
1252         int nr_frags = shinfo->nr_frags;
1253         RING_IDX cons = np->rx.rsp_cons;
1254         skb_frag_t *frag = shinfo->frags + nr_frags;
1255         struct sk_buff *nskb;
1256
1257         while ((nskb = __skb_dequeue(list))) {
1258                 struct netif_rx_response *rx =
1259                         RING_GET_RESPONSE(&np->rx, ++cons);
1260
1261                 frag->page = skb_shinfo(nskb)->frags[0].page;
1262                 frag->page_offset = rx->offset;
1263                 frag->size = rx->status;
1264
1265                 skb->data_len += rx->status;
1266
1267                 skb_shinfo(nskb)->nr_frags = 0;
1268                 kfree_skb(nskb);
1269
1270                 frag++;
1271                 nr_frags++;
1272         }
1273
1274         shinfo->nr_frags = nr_frags;
1275         return cons;
1276 }
1277
1278 static int xennet_set_skb_gso(struct sk_buff *skb,
1279                               struct netif_extra_info *gso)
1280 {
1281         if (!gso->u.gso.size) {
1282                 if (net_ratelimit())
1283                         WPRINTK("GSO size must not be zero.\n");
1284                 return -EINVAL;
1285         }
1286
1287         /* Currently only TCPv4 S.O. is supported. */
1288         if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) {
1289                 if (net_ratelimit())
1290                         WPRINTK("Bad GSO type %d.\n", gso->u.gso.type);
1291                 return -EINVAL;
1292         }
1293
1294 #if HAVE_TSO
1295         skb_shinfo(skb)->gso_size = gso->u.gso.size;
1296 #if HAVE_GSO
1297         skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1298
1299         /* Header must be checked, and gso_segs computed. */
1300         skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1301 #endif
1302         skb_shinfo(skb)->gso_segs = 0;
1303
1304         return 0;
1305 #else
1306         if (net_ratelimit())
1307                 WPRINTK("GSO unsupported by this kernel.\n");
1308         return -EINVAL;
1309 #endif
1310 }
1311
1312 static int netif_poll(struct napi_struct *napi, int budget)
1313 {
1314         struct netfront_info *np = container_of(napi, struct netfront_info, napi);
1315         struct net_device *dev = np->netdev;
1316         struct sk_buff *skb;
1317         struct netfront_rx_info rinfo;
1318         struct netif_rx_response *rx = &rinfo.rx;
1319         struct netif_extra_info *extras = rinfo.extras;
1320         RING_IDX i, rp;
1321         struct multicall_entry *mcl;
1322         int work_done, more_to_do = 1, accel_more_to_do = 1;
1323         struct sk_buff_head rxq;
1324         struct sk_buff_head errq;
1325         struct sk_buff_head tmpq;
1326         unsigned long flags;
1327         unsigned int len;
1328         int pages_flipped = 0;
1329         int err;
1330
1331         spin_lock(&np->rx_lock); /* no need for spin_lock_bh() in ->poll() */
1332
1333         if (unlikely(!netfront_carrier_ok(np))) {
1334                 spin_unlock(&np->rx_lock);
1335                 return 0;
1336         }
1337
1338         skb_queue_head_init(&rxq);
1339         skb_queue_head_init(&errq);
1340         skb_queue_head_init(&tmpq);
1341
1342         rp = np->rx.sring->rsp_prod;
1343         rmb(); /* Ensure we see queued responses up to 'rp'. */
1344
1345         i = np->rx.rsp_cons;
1346         work_done = 0;
1347         while ((i != rp) && (work_done < budget)) {
1348                 memcpy(rx, RING_GET_RESPONSE(&np->rx, i), sizeof(*rx));
1349                 memset(extras, 0, sizeof(rinfo.extras));
1350
1351                 err = xennet_get_responses(np, &rinfo, rp, &tmpq,
1352                                            &pages_flipped);
1353
1354                 if (unlikely(err)) {
1355 err:    
1356                         while ((skb = __skb_dequeue(&tmpq)))
1357                                 __skb_queue_tail(&errq, skb);
1358                         np->stats.rx_errors++;
1359                         i = np->rx.rsp_cons;
1360                         continue;
1361                 }
1362
1363                 skb = __skb_dequeue(&tmpq);
1364
1365                 if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
1366                         struct netif_extra_info *gso;
1367                         gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
1368
1369                         if (unlikely(xennet_set_skb_gso(skb, gso))) {
1370                                 __skb_queue_head(&tmpq, skb);
1371                                 np->rx.rsp_cons += skb_queue_len(&tmpq);
1372                                 goto err;
1373                         }
1374                 }
1375
1376                 NETFRONT_SKB_CB(skb)->page = skb_shinfo(skb)->frags[0].page;
1377                 NETFRONT_SKB_CB(skb)->offset = rx->offset;
1378
1379                 len = rx->status;
1380                 if (len > RX_COPY_THRESHOLD)
1381                         len = RX_COPY_THRESHOLD;
1382                 skb_put(skb, len);
1383
1384                 if (rx->status > len) {
1385                         skb_shinfo(skb)->frags[0].page_offset =
1386                                 rx->offset + len;
1387                         skb_shinfo(skb)->frags[0].size = rx->status - len;
1388                         skb->data_len = rx->status - len;
1389                 } else {
1390                         skb_shinfo(skb)->frags[0].page = NULL;
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                 /*
1420                  * Old backends do not assert data_validated but we
1421                  * can infer it from csum_blank so test both flags.
1422                  */
1423                 if (rx->flags & (NETRXF_data_validated|NETRXF_csum_blank))
1424                         skb->ip_summed = CHECKSUM_UNNECESSARY;
1425                 else
1426                         skb->ip_summed = CHECKSUM_NONE;
1427 #ifdef CONFIG_XEN
1428                 skb->proto_data_valid = (skb->ip_summed != CHECKSUM_NONE);
1429                 skb->proto_csum_blank = !!(rx->flags & NETRXF_csum_blank);
1430 #endif
1431                 np->stats.rx_packets++;
1432                 np->stats.rx_bytes += skb->len;
1433
1434                 __skb_queue_tail(&rxq, skb);
1435
1436                 np->rx.rsp_cons = ++i;
1437                 work_done++;
1438         }
1439
1440         if (pages_flipped) {
1441                 /* Some pages are no longer absent... */
1442                 balloon_update_driver_allowance(-pages_flipped);
1443
1444                 /* Do all the remapping work and M2P updates. */
1445                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
1446                         mcl = np->rx_mcl + pages_flipped;
1447                         mcl->op = __HYPERVISOR_mmu_update;
1448                         mcl->args[0] = (unsigned long)np->rx_mmu;
1449                         mcl->args[1] = pages_flipped;
1450                         mcl->args[2] = 0;
1451                         mcl->args[3] = DOMID_SELF;
1452                         err = HYPERVISOR_multicall_check(np->rx_mcl,
1453                                                          pages_flipped + 1,
1454                                                          NULL);
1455                         BUG_ON(err);
1456                 }
1457         }
1458
1459         while ((skb = __skb_dequeue(&errq)))
1460                 kfree_skb(skb);
1461
1462         while ((skb = __skb_dequeue(&rxq)) != NULL) {
1463                 struct page *page = NETFRONT_SKB_CB(skb)->page;
1464                 void *vaddr = page_address(page);
1465                 unsigned offset = NETFRONT_SKB_CB(skb)->offset;
1466
1467                 memcpy(skb->data, vaddr + offset, skb_headlen(skb));
1468
1469                 if (page != skb_shinfo(skb)->frags[0].page)
1470                         __free_page(page);
1471
1472                 /* Ethernet work: Delayed to here as it peeks the header. */
1473                 skb->protocol = eth_type_trans(skb, dev);
1474
1475                 /* Pass it up. */
1476                 netif_receive_skb(skb);
1477                 dev->last_rx = jiffies;
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                         __netif_rx_complete(dev, 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                 if ((ref = np->grant_rx_ref[id]) == GRANT_INVALID_REF) {
1564                         unused++;
1565                         continue;
1566                 }
1567
1568                 skb = np->rx_skbs[id];
1569                 mfn = gnttab_end_foreign_transfer_ref(ref);
1570                 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1571                 np->grant_rx_ref[id] = GRANT_INVALID_REF;
1572                 add_id_to_freelist(np->rx_skbs, id);
1573
1574                 if (0 == mfn) {
1575                         struct page *page = skb_shinfo(skb)->frags[0].page;
1576                         balloon_release_driver_page(page);
1577                         skb_shinfo(skb)->nr_frags = 0;
1578                         dev_kfree_skb(skb);
1579                         noxfer++;
1580                         continue;
1581                 }
1582
1583                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
1584                         /* Remap the page. */
1585                         struct page *page = skb_shinfo(skb)->frags[0].page;
1586                         unsigned long pfn = page_to_pfn(page);
1587                         void *vaddr = page_address(page);
1588
1589                         MULTI_update_va_mapping(mcl, (unsigned long)vaddr,
1590                                                 pfn_pte_ma(mfn, PAGE_KERNEL),
1591                                                 0);
1592                         mcl++;
1593                         mmu->ptr = ((maddr_t)mfn << PAGE_SHIFT)
1594                                 | MMU_MACHPHYS_UPDATE;
1595                         mmu->val = pfn;
1596                         mmu++;
1597
1598                         set_phys_to_machine(pfn, mfn);
1599                 }
1600                 __skb_queue_tail(&free_list, skb);
1601                 xfer++;
1602         }
1603
1604         DPRINTK("%s: %d xfer, %d noxfer, %d unused\n",
1605                 __FUNCTION__, xfer, noxfer, unused);
1606
1607         if (xfer) {
1608                 /* Some pages are no longer absent... */
1609                 balloon_update_driver_allowance(-xfer);
1610
1611                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
1612                         /* Do all the remapping work and M2P updates. */
1613                         mcl->op = __HYPERVISOR_mmu_update;
1614                         mcl->args[0] = (unsigned long)np->rx_mmu;
1615                         mcl->args[1] = mmu - np->rx_mmu;
1616                         mcl->args[2] = 0;
1617                         mcl->args[3] = DOMID_SELF;
1618                         mcl++;
1619                         rc = HYPERVISOR_multicall_check(
1620                                 np->rx_mcl, mcl - np->rx_mcl, NULL);
1621                         BUG_ON(rc);
1622                 }
1623         }
1624
1625         while ((skb = __skb_dequeue(&free_list)) != NULL)
1626                 dev_kfree_skb(skb);
1627
1628         spin_unlock_bh(&np->rx_lock);
1629 }
1630
1631 static void netif_release_rx_bufs_copy(struct netfront_info *np)
1632 {
1633         struct sk_buff *skb;
1634         int i, ref;
1635         int busy = 0, inuse = 0;
1636
1637         spin_lock_bh(&np->rx_lock);
1638
1639         for (i = 0; i < NET_RX_RING_SIZE; i++) {
1640                 ref = np->grant_rx_ref[i];
1641
1642                 if (ref == GRANT_INVALID_REF)
1643                         continue;
1644
1645                 inuse++;
1646
1647                 skb = np->rx_skbs[i];
1648
1649                 if (!gnttab_end_foreign_access_ref(ref))
1650                 {
1651                         busy++;
1652                         continue;
1653                 }
1654
1655                 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1656                 np->grant_rx_ref[i] = GRANT_INVALID_REF;
1657                 add_id_to_freelist(np->rx_skbs, i);
1658
1659                 skb_shinfo(skb)->nr_frags = 0;
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         return 0;
1675 }
1676
1677
1678 static struct net_device_stats *network_get_stats(struct net_device *dev)
1679 {
1680         struct netfront_info *np = netdev_priv(dev);
1681
1682         netfront_accelerator_call_get_stats(np, dev);
1683         return &np->stats;
1684 }
1685
1686 static int xennet_change_mtu(struct net_device *dev, int mtu)
1687 {
1688         int max = xennet_can_sg(dev) ? 65535 - ETH_HLEN : ETH_DATA_LEN;
1689
1690         if (mtu > max)
1691                 return -EINVAL;
1692         dev->mtu = mtu;
1693         return 0;
1694 }
1695
1696 static int xennet_set_sg(struct net_device *dev, u32 data)
1697 {
1698         if (data) {
1699                 struct netfront_info *np = netdev_priv(dev);
1700                 int val;
1701
1702                 if (xenbus_scanf(XBT_NIL, np->xbdev->otherend, "feature-sg",
1703                                  "%d", &val) < 0)
1704                         val = 0;
1705                 if (!val)
1706                         return -ENOSYS;
1707         } else if (dev->mtu > ETH_DATA_LEN)
1708                 dev->mtu = ETH_DATA_LEN;
1709
1710         return ethtool_op_set_sg(dev, data);
1711 }
1712
1713 static int xennet_set_tso(struct net_device *dev, u32 data)
1714 {
1715         if (data) {
1716                 struct netfront_info *np = netdev_priv(dev);
1717                 int val;
1718
1719                 if (xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1720                                  "feature-gso-tcpv4", "%d", &val) < 0)
1721                         val = 0;
1722                 if (!val)
1723                         return -ENOSYS;
1724         }
1725
1726         return ethtool_op_set_tso(dev, data);
1727 }
1728
1729 static void xennet_set_features(struct net_device *dev)
1730 {
1731         dev_disable_gso_features(dev);
1732         xennet_set_sg(dev, 0);
1733
1734         /* We need checksum offload to enable scatter/gather and TSO. */
1735         if (!(dev->features & NETIF_F_IP_CSUM))
1736                 return;
1737
1738         if (xennet_set_sg(dev, 1))
1739                 return;
1740
1741         /* Before 2.6.9 TSO seems to be unreliable so do not enable it
1742          * on older kernels.
1743          */
1744         if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,9))
1745                 xennet_set_tso(dev, 1);
1746 }
1747
1748 static int network_connect(struct net_device *dev)
1749 {
1750         struct netfront_info *np = netdev_priv(dev);
1751         int i, requeue_idx, err;
1752         struct sk_buff *skb;
1753         grant_ref_t ref;
1754         netif_rx_request_t *req;
1755         unsigned int feature_rx_copy, feature_rx_flip;
1756
1757         err = xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1758                            "feature-rx-copy", "%u", &feature_rx_copy);
1759         if (err != 1)
1760                 feature_rx_copy = 0;
1761         err = xenbus_scanf(XBT_NIL, np->xbdev->otherend,
1762                            "feature-rx-flip", "%u", &feature_rx_flip);
1763         if (err != 1)
1764                 feature_rx_flip = 1;
1765
1766         /*
1767          * Copy packets on receive path if:
1768          *  (a) This was requested by user, and the backend supports it; or
1769          *  (b) Flipping was requested, but this is unsupported by the backend.
1770          */
1771         np->copying_receiver = ((MODPARM_rx_copy && feature_rx_copy) ||
1772                                 (MODPARM_rx_flip && !feature_rx_flip));
1773
1774         err = talk_to_backend(np->xbdev, np);
1775         if (err)
1776                 return err;
1777
1778         xennet_set_features(dev);
1779
1780         DPRINTK("device %s has %sing receive path.\n",
1781                 dev->name, np->copying_receiver ? "copy" : "flipp");
1782
1783         spin_lock_bh(&np->rx_lock);
1784         spin_lock_irq(&np->tx_lock);
1785
1786         /*
1787          * Recovery procedure:
1788          *  NB. Freelist index entries are always going to be less than
1789          *  PAGE_OFFSET, whereas pointers to skbs will always be equal or
1790          *  greater than PAGE_OFFSET: we use this property to distinguish
1791          *  them.
1792          */
1793
1794         /* Step 1: Discard all pending TX packet fragments. */
1795         netif_release_tx_bufs(np);
1796
1797         /* Step 2: Rebuild the RX buffer freelist and the RX ring itself. */
1798         for (requeue_idx = 0, i = 0; i < NET_RX_RING_SIZE; i++) {
1799                 if (!np->rx_skbs[i])
1800                         continue;
1801
1802                 skb = np->rx_skbs[requeue_idx] = xennet_get_rx_skb(np, i);
1803                 ref = np->grant_rx_ref[requeue_idx] = xennet_get_rx_ref(np, i);
1804                 req = RING_GET_REQUEST(&np->rx, requeue_idx);
1805
1806                 if (!np->copying_receiver) {
1807                         gnttab_grant_foreign_transfer_ref(
1808                                 ref, np->xbdev->otherend_id,
1809                                 page_to_pfn(skb_shinfo(skb)->frags->page));
1810                 } else {
1811                         gnttab_grant_foreign_access_ref(
1812                                 ref, np->xbdev->otherend_id,
1813                                 pfn_to_mfn(page_to_pfn(skb_shinfo(skb)->
1814                                                        frags->page)),
1815                                 0);
1816                 }
1817                 req->gref = ref;
1818                 req->id   = requeue_idx;
1819
1820                 requeue_idx++;
1821         }
1822
1823         np->rx.req_prod_pvt = requeue_idx;
1824
1825         /*
1826          * Step 3: All public and private state should now be sane.  Get
1827          * ready to start sending and receiving packets and give the driver
1828          * domain a kick because we've probably just requeued some
1829          * packets.
1830          */
1831         netfront_carrier_on(np);
1832         notify_remote_via_irq(np->irq);
1833         network_tx_buf_gc(dev);
1834         network_alloc_rx_buffers(dev);
1835
1836         spin_unlock_irq(&np->tx_lock);
1837         spin_unlock_bh(&np->rx_lock);
1838
1839         return 0;
1840 }
1841
1842 static void netif_uninit(struct net_device *dev)
1843 {
1844         struct netfront_info *np = netdev_priv(dev);
1845         netif_release_tx_bufs(np);
1846         if (np->copying_receiver)
1847                 netif_release_rx_bufs_copy(np);
1848         else
1849                 netif_release_rx_bufs_flip(np);
1850         gnttab_free_grant_references(np->gref_tx_head);
1851         gnttab_free_grant_references(np->gref_rx_head);
1852 }
1853
1854 static struct ethtool_ops network_ethtool_ops =
1855 {
1856         .get_tx_csum = ethtool_op_get_tx_csum,
1857         .set_tx_csum = ethtool_op_set_tx_csum,
1858         .get_sg = ethtool_op_get_sg,
1859         .set_sg = xennet_set_sg,
1860 #if HAVE_TSO
1861         .get_tso = ethtool_op_get_tso,
1862         .set_tso = xennet_set_tso,
1863 #endif
1864         .get_link = ethtool_op_get_link,
1865 };
1866
1867 #ifdef CONFIG_SYSFS
1868 static ssize_t show_rxbuf_min(struct device *dev,
1869                               struct device_attribute *attr, char *buf)
1870 {
1871         struct netfront_info *info = netdev_priv(to_net_dev(dev));
1872
1873         return sprintf(buf, "%u\n", info->rx_min_target);
1874 }
1875
1876 static ssize_t store_rxbuf_min(struct device *dev,
1877                                struct device_attribute *attr,
1878                                const char *buf, size_t len)
1879 {
1880         struct net_device *netdev = to_net_dev(dev);
1881         struct netfront_info *np = netdev_priv(netdev);
1882         char *endp;
1883         unsigned long target;
1884
1885         if (!capable(CAP_NET_ADMIN))
1886                 return -EPERM;
1887
1888         target = simple_strtoul(buf, &endp, 0);
1889         if (endp == buf)
1890                 return -EBADMSG;
1891
1892         if (target < RX_MIN_TARGET)
1893                 target = RX_MIN_TARGET;
1894         if (target > RX_MAX_TARGET)
1895                 target = RX_MAX_TARGET;
1896
1897         spin_lock_bh(&np->rx_lock);
1898         if (target > np->rx_max_target)
1899                 np->rx_max_target = target;
1900         np->rx_min_target = target;
1901         if (target > np->rx_target)
1902                 np->rx_target = target;
1903
1904         network_alloc_rx_buffers(netdev);
1905
1906         spin_unlock_bh(&np->rx_lock);
1907         return len;
1908 }
1909
1910 static ssize_t show_rxbuf_max(struct device *dev,
1911                               struct device_attribute *attr, char *buf)
1912 {
1913         struct netfront_info *info = netdev_priv(to_net_dev(dev));
1914
1915         return sprintf(buf, "%u\n", info->rx_max_target);
1916 }
1917
1918 static ssize_t store_rxbuf_max(struct device *dev,
1919                                struct device_attribute *attr,
1920                                const char *buf, size_t len)
1921 {
1922         struct net_device *netdev = to_net_dev(dev);
1923         struct netfront_info *np = netdev_priv(netdev);
1924         char *endp;
1925         unsigned long target;
1926
1927         if (!capable(CAP_NET_ADMIN))
1928                 return -EPERM;
1929
1930         target = simple_strtoul(buf, &endp, 0);
1931         if (endp == buf)
1932                 return -EBADMSG;
1933
1934         if (target < RX_MIN_TARGET)
1935                 target = RX_MIN_TARGET;
1936         if (target > RX_MAX_TARGET)
1937                 target = RX_MAX_TARGET;
1938
1939         spin_lock_bh(&np->rx_lock);
1940         if (target < np->rx_min_target)
1941                 np->rx_min_target = target;
1942         np->rx_max_target = target;
1943         if (target < np->rx_target)
1944                 np->rx_target = target;
1945
1946         network_alloc_rx_buffers(netdev);
1947
1948         spin_unlock_bh(&np->rx_lock);
1949         return len;
1950 }
1951
1952 static ssize_t show_rxbuf_cur(struct device *dev,
1953                               struct device_attribute *attr, char *buf)
1954 {
1955         struct netfront_info *info = netdev_priv(to_net_dev(dev));
1956
1957         return sprintf(buf, "%u\n", info->rx_target);
1958 }
1959
1960 static struct device_attribute xennet_attrs[] = {
1961         __ATTR(rxbuf_min, S_IRUGO|S_IWUSR, show_rxbuf_min, store_rxbuf_min),
1962         __ATTR(rxbuf_max, S_IRUGO|S_IWUSR, show_rxbuf_max, store_rxbuf_max),
1963         __ATTR(rxbuf_cur, S_IRUGO, show_rxbuf_cur, NULL),
1964 };
1965
1966 static int xennet_sysfs_addif(struct net_device *netdev)
1967 {
1968         int i;
1969         int error = 0;
1970
1971         for (i = 0; i < ARRAY_SIZE(xennet_attrs); i++) {
1972                 error = device_create_file(&netdev->dev,
1973                                            &xennet_attrs[i]);
1974                 if (error)
1975                         goto fail;
1976         }
1977         return 0;
1978
1979  fail:
1980         while (--i >= 0)
1981                 device_remove_file(&netdev->dev, &xennet_attrs[i]);
1982         return error;
1983 }
1984
1985 static void xennet_sysfs_delif(struct net_device *netdev)
1986 {
1987         int i;
1988
1989         for (i = 0; i < ARRAY_SIZE(xennet_attrs); i++)
1990                 device_remove_file(&netdev->dev, &xennet_attrs[i]);
1991 }
1992
1993 #endif /* CONFIG_SYSFS */
1994
1995
1996 /*
1997  * Nothing to do here. Virtual interface is point-to-point and the
1998  * physical interface is probably promiscuous anyway.
1999  */
2000 static void network_set_multicast_list(struct net_device *dev)
2001 {
2002 }
2003
2004 static struct net_device * __devinit create_netdev(struct xenbus_device *dev)
2005 {
2006         int i, err = 0;
2007         struct net_device *netdev = NULL;
2008         struct netfront_info *np = NULL;
2009
2010         netdev = alloc_etherdev(sizeof(struct netfront_info));
2011         if (!netdev) {
2012                 printk(KERN_WARNING "%s> alloc_etherdev failed.\n",
2013                        __FUNCTION__);
2014                 return ERR_PTR(-ENOMEM);
2015         }
2016
2017         np                   = netdev_priv(netdev);
2018         np->xbdev            = dev;
2019
2020         spin_lock_init(&np->tx_lock);
2021         spin_lock_init(&np->rx_lock);
2022
2023         init_accelerator_vif(np, dev);
2024
2025         skb_queue_head_init(&np->rx_batch);
2026         np->rx_target     = RX_DFL_MIN_TARGET;
2027         np->rx_min_target = RX_DFL_MIN_TARGET;
2028         np->rx_max_target = RX_MAX_TARGET;
2029
2030         init_timer(&np->rx_refill_timer);
2031         np->rx_refill_timer.data = (unsigned long)netdev;
2032         np->rx_refill_timer.function = rx_refill_timeout;
2033
2034         /* Initialise {tx,rx}_skbs as a free chain containing every entry. */
2035         for (i = 0; i <= NET_TX_RING_SIZE; i++) {
2036                 np->tx_skbs[i] = (void *)((unsigned long) i+1);
2037                 np->grant_tx_ref[i] = GRANT_INVALID_REF;
2038         }
2039
2040         for (i = 0; i < NET_RX_RING_SIZE; i++) {
2041                 np->rx_skbs[i] = NULL;
2042                 np->grant_rx_ref[i] = GRANT_INVALID_REF;
2043         }
2044
2045         /* A grant for every tx ring slot */
2046         if (gnttab_alloc_grant_references(TX_MAX_TARGET,
2047                                           &np->gref_tx_head) < 0) {
2048                 printk(KERN_ALERT "#### netfront can't alloc tx grant refs\n");
2049                 err = -ENOMEM;
2050                 goto exit;
2051         }
2052         /* A grant for every rx ring slot */
2053         if (gnttab_alloc_grant_references(RX_MAX_TARGET,
2054                                           &np->gref_rx_head) < 0) {
2055                 printk(KERN_ALERT "#### netfront can't alloc rx grant refs\n");
2056                 err = -ENOMEM;
2057                 goto exit_free_tx;
2058         }
2059
2060         netdev->open            = network_open;
2061         netdev->hard_start_xmit = network_start_xmit;
2062         netdev->stop            = network_close;
2063         netdev->get_stats       = network_get_stats;
2064         netif_napi_add(netdev, &np->napi, netif_poll, 64);
2065         netdev->set_multicast_list = network_set_multicast_list;
2066         netdev->uninit          = netif_uninit;
2067         netdev->change_mtu      = xennet_change_mtu;
2068         netdev->features        = NETIF_F_IP_CSUM;
2069
2070         SET_ETHTOOL_OPS(netdev, &network_ethtool_ops);
2071         SET_NETDEV_DEV(netdev, &dev->dev);
2072
2073         np->netdev = netdev;
2074
2075         netfront_carrier_off(np);
2076
2077         return netdev;
2078
2079  exit_free_tx:
2080         gnttab_free_grant_references(np->gref_tx_head);
2081  exit:
2082         free_netdev(netdev);
2083         return ERR_PTR(err);
2084 }
2085
2086 #ifdef CONFIG_INET
2087 /*
2088  * We use this notifier to send out a fake ARP reply to reset switches and
2089  * router ARP caches when an IP interface is brought up on a VIF.
2090  */
2091 static int
2092 inetdev_notify(struct notifier_block *this, unsigned long event, void *ptr)
2093 {
2094         struct in_ifaddr  *ifa = (struct in_ifaddr *)ptr;
2095         struct net_device *dev = ifa->ifa_dev->dev;
2096
2097         /* UP event and is it one of our devices? */
2098         if (event == NETDEV_UP && dev->open == network_open)
2099                 send_fake_arp(dev);
2100
2101         return NOTIFY_DONE;
2102 }
2103
2104 static struct notifier_block notifier_inetdev = {
2105         .notifier_call  = inetdev_notify,
2106         .next           = NULL,
2107         .priority       = 0
2108 };
2109 #endif
2110
2111
2112 static void netif_disconnect_backend(struct netfront_info *info)
2113 {
2114         /* Stop old i/f to prevent errors whilst we rebuild the state. */
2115         spin_lock_bh(&info->rx_lock);
2116         spin_lock_irq(&info->tx_lock);
2117         netfront_carrier_off(info);
2118         spin_unlock_irq(&info->tx_lock);
2119         spin_unlock_bh(&info->rx_lock);
2120
2121         if (info->irq)
2122                 unbind_from_irqhandler(info->irq, info->netdev);
2123         info->irq = 0;
2124
2125         end_access(info->tx_ring_ref, info->tx.sring);
2126         end_access(info->rx_ring_ref, info->rx.sring);
2127         info->tx_ring_ref = GRANT_INVALID_REF;
2128         info->rx_ring_ref = GRANT_INVALID_REF;
2129         info->tx.sring = NULL;
2130         info->rx.sring = NULL;
2131 }
2132
2133
2134 static void end_access(int ref, void *page)
2135 {
2136         if (ref != GRANT_INVALID_REF)
2137                 gnttab_end_foreign_access(ref, (unsigned long)page);
2138 }
2139
2140
2141 /* ** Driver registration ** */
2142
2143
2144 static struct xenbus_device_id netfront_ids[] = {
2145         { "vif" },
2146         { "" }
2147 };
2148 MODULE_ALIAS("xen:vif");
2149
2150
2151 static struct xenbus_driver netfront = {
2152         .name = "vif",
2153         .ids = netfront_ids,
2154         .probe = netfront_probe,
2155         .remove = __devexit_p(netfront_remove),
2156         .suspend = netfront_suspend,
2157         .suspend_cancel = netfront_suspend_cancel,
2158         .resume = netfront_resume,
2159         .otherend_changed = backend_changed,
2160 };
2161
2162
2163 static int __init netif_init(void)
2164 {
2165         if (!is_running_on_xen())
2166                 return -ENODEV;
2167
2168 #ifdef CONFIG_XEN
2169         if (MODPARM_rx_flip && MODPARM_rx_copy) {
2170                 WPRINTK("Cannot specify both rx_copy and rx_flip.\n");
2171                 return -EINVAL;
2172         }
2173
2174         if (!MODPARM_rx_flip && !MODPARM_rx_copy)
2175                 MODPARM_rx_flip = 1; /* Default is to flip. */
2176 #endif
2177
2178         if (is_initial_xendomain())
2179                 return 0;
2180
2181         netif_init_accel();
2182
2183         IPRINTK("Initialising virtual ethernet driver.\n");
2184
2185 #ifdef CONFIG_INET
2186         (void)register_inetaddr_notifier(&notifier_inetdev);
2187 #endif
2188
2189         return xenbus_register_frontend(&netfront);
2190 }
2191 module_init(netif_init);
2192
2193
2194 static void __exit netif_exit(void)
2195 {
2196         if (is_initial_xendomain())
2197                 return;
2198
2199 #ifdef CONFIG_INET
2200         unregister_inetaddr_notifier(&notifier_inetdev);
2201 #endif
2202
2203         netif_exit_accel();
2204
2205         return xenbus_unregister_driver(&netfront);
2206 }
2207 module_exit(netif_exit);
2208
2209 MODULE_LICENSE("Dual BSD/GPL");