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