]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/xen/netfront/netfront.c
Merge llvm trunk r238337 from ^/vendor/llvm/dist, resolve conflicts, and
[FreeBSD/FreeBSD.git] / sys / dev / xen / netfront / netfront.c
1 /*-
2  * Copyright (c) 2004-2006 Kip Macy
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include "opt_inet.h"
31 #include "opt_inet6.h"
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/sockio.h>
36 #include <sys/limits.h>
37 #include <sys/mbuf.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/kernel.h>
41 #include <sys/socket.h>
42 #include <sys/sysctl.h>
43 #include <sys/queue.h>
44 #include <sys/lock.h>
45 #include <sys/sx.h>
46
47 #include <net/if.h>
48 #include <net/if_var.h>
49 #include <net/if_arp.h>
50 #include <net/ethernet.h>
51 #include <net/if_dl.h>
52 #include <net/if_media.h>
53
54 #include <net/bpf.h>
55
56 #include <net/if_types.h>
57
58 #include <netinet/in_systm.h>
59 #include <netinet/in.h>
60 #include <netinet/ip.h>
61 #include <netinet/if_ether.h>
62 #if __FreeBSD_version >= 700000
63 #include <netinet/tcp.h>
64 #include <netinet/tcp_lro.h>
65 #endif
66
67 #include <vm/vm.h>
68 #include <vm/pmap.h>
69
70 #include <machine/clock.h>      /* for DELAY */
71 #include <machine/bus.h>
72 #include <machine/resource.h>
73 #include <machine/frame.h>
74 #include <machine/vmparam.h>
75
76 #include <sys/bus.h>
77 #include <sys/rman.h>
78
79 #include <machine/intr_machdep.h>
80
81 #include <xen/xen-os.h>
82 #include <xen/hypervisor.h>
83 #include <xen/xen_intr.h>
84 #include <xen/gnttab.h>
85 #include <xen/interface/memory.h>
86 #include <xen/interface/io/netif.h>
87 #include <xen/xenbus/xenbusvar.h>
88
89 #include <machine/xen/xenvar.h>
90
91 #include "xenbus_if.h"
92
93 /* Features supported by all backends.  TSO and LRO can be negotiated */
94 #define XN_CSUM_FEATURES        (CSUM_TCP | CSUM_UDP)
95
96 #define NET_TX_RING_SIZE __RING_SIZE((netif_tx_sring_t *)0, PAGE_SIZE)
97 #define NET_RX_RING_SIZE __RING_SIZE((netif_rx_sring_t *)0, PAGE_SIZE)
98
99 #if __FreeBSD_version >= 700000
100 /*
101  * Should the driver do LRO on the RX end
102  *  this can be toggled on the fly, but the
103  *  interface must be reset (down/up) for it
104  *  to take effect.
105  */
106 static int xn_enable_lro = 1;
107 TUNABLE_INT("hw.xn.enable_lro", &xn_enable_lro);
108 #else
109
110 #define IFCAP_TSO4      0
111 #define CSUM_TSO        0
112
113 #endif
114
115 #ifdef CONFIG_XEN
116 static int MODPARM_rx_copy = 0;
117 module_param_named(rx_copy, MODPARM_rx_copy, bool, 0);
118 MODULE_PARM_DESC(rx_copy, "Copy packets from network card (rather than flip)");
119 static int MODPARM_rx_flip = 0;
120 module_param_named(rx_flip, MODPARM_rx_flip, bool, 0);
121 MODULE_PARM_DESC(rx_flip, "Flip packets from network card (rather than copy)");
122 #else
123 static const int MODPARM_rx_copy = 1;
124 static const int MODPARM_rx_flip = 0;
125 #endif
126
127 /**
128  * \brief The maximum allowed data fragments in a single transmit
129  *        request.
130  *
131  * This limit is imposed by the backend driver.  We assume here that
132  * we are dealing with a Linux driver domain and have set our limit
133  * to mirror the Linux MAX_SKB_FRAGS constant.
134  */
135 #define MAX_TX_REQ_FRAGS (65536 / PAGE_SIZE + 2)
136
137 #define RX_COPY_THRESHOLD 256
138
139 #define net_ratelimit() 0
140
141 struct netfront_info;
142 struct netfront_rx_info;
143
144 static void xn_txeof(struct netfront_info *);
145 static void xn_rxeof(struct netfront_info *);
146 static void network_alloc_rx_buffers(struct netfront_info *);
147
148 static void xn_tick_locked(struct netfront_info *);
149 static void xn_tick(void *);
150
151 static void xn_intr(void *);
152 static inline int xn_count_frags(struct mbuf *m);
153 static int  xn_assemble_tx_request(struct netfront_info *sc,
154                                    struct mbuf *m_head);
155 static void xn_start_locked(struct ifnet *);
156 static void xn_start(struct ifnet *);
157 static int  xn_ioctl(struct ifnet *, u_long, caddr_t);
158 static void xn_ifinit_locked(struct netfront_info *);
159 static void xn_ifinit(void *);
160 static void xn_stop(struct netfront_info *);
161 static void xn_query_features(struct netfront_info *np);
162 static int  xn_configure_features(struct netfront_info *np);
163 #ifdef notyet
164 static void xn_watchdog(struct ifnet *);
165 #endif
166
167 #ifdef notyet
168 static void netfront_closing(device_t dev);
169 #endif
170 static void netif_free(struct netfront_info *info);
171 static int netfront_detach(device_t dev);
172
173 static int talk_to_backend(device_t dev, struct netfront_info *info);
174 static int create_netdev(device_t dev);
175 static void netif_disconnect_backend(struct netfront_info *info);
176 static int setup_device(device_t dev, struct netfront_info *info);
177 static void free_ring(int *ref, void *ring_ptr_ref);
178
179 static int  xn_ifmedia_upd(struct ifnet *ifp);
180 static void xn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr);
181
182 /* Xenolinux helper functions */
183 int network_connect(struct netfront_info *);
184
185 static void xn_free_rx_ring(struct netfront_info *);
186
187 static void xn_free_tx_ring(struct netfront_info *);
188
189 static int xennet_get_responses(struct netfront_info *np,
190         struct netfront_rx_info *rinfo, RING_IDX rp, RING_IDX *cons,
191         struct mbuf **list, int *pages_flipped_p);
192
193 #define virt_to_mfn(x) (vtomach(x) >> PAGE_SHIFT)
194
195 #define INVALID_P2M_ENTRY (~0UL)
196
197 /*
198  * Mbuf pointers. We need these to keep track of the virtual addresses
199  * of our mbuf chains since we can only convert from virtual to physical,
200  * not the other way around.  The size must track the free index arrays.
201  */
202 struct xn_chain_data {
203         struct mbuf    *xn_tx_chain[NET_TX_RING_SIZE+1];
204         int             xn_tx_chain_cnt;
205         struct mbuf    *xn_rx_chain[NET_RX_RING_SIZE+1];
206 };
207
208 struct net_device_stats
209 {
210         u_long  rx_packets;             /* total packets received       */
211         u_long  tx_packets;             /* total packets transmitted    */
212         u_long  rx_bytes;               /* total bytes received         */
213         u_long  tx_bytes;               /* total bytes transmitted      */
214         u_long  rx_errors;              /* bad packets received         */
215         u_long  tx_errors;              /* packet transmit problems     */
216         u_long  rx_dropped;             /* no space in linux buffers    */
217         u_long  tx_dropped;             /* no space available in linux  */
218         u_long  multicast;              /* multicast packets received   */
219         u_long  collisions;
220
221         /* detailed rx_errors: */
222         u_long  rx_length_errors;
223         u_long  rx_over_errors;         /* receiver ring buff overflow  */
224         u_long  rx_crc_errors;          /* recved pkt with crc error    */
225         u_long  rx_frame_errors;        /* recv'd frame alignment error */
226         u_long  rx_fifo_errors;         /* recv'r fifo overrun          */
227         u_long  rx_missed_errors;       /* receiver missed packet       */
228
229         /* detailed tx_errors */
230         u_long  tx_aborted_errors;
231         u_long  tx_carrier_errors;
232         u_long  tx_fifo_errors;
233         u_long  tx_heartbeat_errors;
234         u_long  tx_window_errors;
235         
236         /* for cslip etc */
237         u_long  rx_compressed;
238         u_long  tx_compressed;
239 };
240
241 struct netfront_info {
242         struct ifnet *xn_ifp;
243 #if __FreeBSD_version >= 700000
244         struct lro_ctrl xn_lro;
245 #endif
246
247         struct net_device_stats stats;
248         u_int tx_full;
249
250         netif_tx_front_ring_t tx;
251         netif_rx_front_ring_t rx;
252
253         struct mtx   tx_lock;
254         struct mtx   rx_lock;
255         struct mtx   sc_lock;
256
257         xen_intr_handle_t xen_intr_handle;
258         u_int copying_receiver;
259         u_int carrier;
260         u_int maxfrags;
261                 
262         /* Receive-ring batched refills. */
263 #define RX_MIN_TARGET 32
264 #define RX_MAX_TARGET NET_RX_RING_SIZE
265         int rx_min_target;
266         int rx_max_target;
267         int rx_target;
268
269         grant_ref_t gref_tx_head;
270         grant_ref_t grant_tx_ref[NET_TX_RING_SIZE + 1]; 
271         grant_ref_t gref_rx_head;
272         grant_ref_t grant_rx_ref[NET_TX_RING_SIZE + 1]; 
273
274         device_t                xbdev;
275         int                     tx_ring_ref;
276         int                     rx_ring_ref;
277         uint8_t                 mac[ETHER_ADDR_LEN];
278         struct xn_chain_data    xn_cdata;       /* mbufs */
279         struct mbufq            xn_rx_batch;    /* batch queue */
280
281         int                     xn_if_flags;
282         struct callout          xn_stat_ch;
283
284         u_long                  rx_pfn_array[NET_RX_RING_SIZE];
285         multicall_entry_t       rx_mcl[NET_RX_RING_SIZE+1];
286         mmu_update_t            rx_mmu[NET_RX_RING_SIZE];
287         struct ifmedia          sc_media;
288 };
289
290 #define rx_mbufs xn_cdata.xn_rx_chain
291 #define tx_mbufs xn_cdata.xn_tx_chain
292
293 #define XN_LOCK_INIT(_sc, _name) \
294         mtx_init(&(_sc)->tx_lock, #_name"_tx", "network transmit lock", MTX_DEF); \
295         mtx_init(&(_sc)->rx_lock, #_name"_rx", "network receive lock", MTX_DEF);  \
296         mtx_init(&(_sc)->sc_lock, #_name"_sc", "netfront softc lock", MTX_DEF)
297
298 #define XN_RX_LOCK(_sc)           mtx_lock(&(_sc)->rx_lock)
299 #define XN_RX_UNLOCK(_sc)         mtx_unlock(&(_sc)->rx_lock)
300
301 #define XN_TX_LOCK(_sc)           mtx_lock(&(_sc)->tx_lock)
302 #define XN_TX_UNLOCK(_sc)         mtx_unlock(&(_sc)->tx_lock)
303
304 #define XN_LOCK(_sc)           mtx_lock(&(_sc)->sc_lock); 
305 #define XN_UNLOCK(_sc)         mtx_unlock(&(_sc)->sc_lock); 
306
307 #define XN_LOCK_ASSERT(_sc)    mtx_assert(&(_sc)->sc_lock, MA_OWNED); 
308 #define XN_RX_LOCK_ASSERT(_sc)    mtx_assert(&(_sc)->rx_lock, MA_OWNED); 
309 #define XN_TX_LOCK_ASSERT(_sc)    mtx_assert(&(_sc)->tx_lock, MA_OWNED); 
310 #define XN_LOCK_DESTROY(_sc)   mtx_destroy(&(_sc)->rx_lock); \
311                                mtx_destroy(&(_sc)->tx_lock); \
312                                mtx_destroy(&(_sc)->sc_lock);
313
314 struct netfront_rx_info {
315         struct netif_rx_response rx;
316         struct netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX - 1];
317 };
318
319 #define netfront_carrier_on(netif)      ((netif)->carrier = 1)
320 #define netfront_carrier_off(netif)     ((netif)->carrier = 0)
321 #define netfront_carrier_ok(netif)      ((netif)->carrier)
322
323 /* Access macros for acquiring freeing slots in xn_free_{tx,rx}_idxs[]. */
324
325 static inline void
326 add_id_to_freelist(struct mbuf **list, uintptr_t id)
327 {
328         KASSERT(id != 0,
329                 ("%s: the head item (0) must always be free.", __func__));
330         list[id] = list[0];
331         list[0]  = (struct mbuf *)id;
332 }
333
334 static inline unsigned short
335 get_id_from_freelist(struct mbuf **list)
336 {
337         uintptr_t id;
338
339         id = (uintptr_t)list[0];
340         KASSERT(id != 0,
341                 ("%s: the head item (0) must always remain free.", __func__));
342         list[0] = list[id];
343         return (id);
344 }
345
346 static inline int
347 xennet_rxidx(RING_IDX idx)
348 {
349         return idx & (NET_RX_RING_SIZE - 1);
350 }
351
352 static inline struct mbuf *
353 xennet_get_rx_mbuf(struct netfront_info *np, RING_IDX ri)
354 {
355         int i = xennet_rxidx(ri);
356         struct mbuf *m;
357
358         m = np->rx_mbufs[i];
359         np->rx_mbufs[i] = NULL;
360         return (m);
361 }
362
363 static inline grant_ref_t
364 xennet_get_rx_ref(struct netfront_info *np, RING_IDX ri)
365 {
366         int i = xennet_rxidx(ri);
367         grant_ref_t ref = np->grant_rx_ref[i];
368         KASSERT(ref != GRANT_REF_INVALID, ("Invalid grant reference!\n"));
369         np->grant_rx_ref[i] = GRANT_REF_INVALID;
370         return ref;
371 }
372
373 #define IPRINTK(fmt, args...) \
374     printf("[XEN] " fmt, ##args)
375 #ifdef INVARIANTS
376 #define WPRINTK(fmt, args...) \
377     printf("[XEN] " fmt, ##args)
378 #else
379 #define WPRINTK(fmt, args...)
380 #endif
381 #ifdef DEBUG
382 #define DPRINTK(fmt, args...) \
383     printf("[XEN] %s: " fmt, __func__, ##args)
384 #else
385 #define DPRINTK(fmt, args...)
386 #endif
387
388 /**
389  * Read the 'mac' node at the given device's node in the store, and parse that
390  * as colon-separated octets, placing result the given mac array.  mac must be
391  * a preallocated array of length ETH_ALEN (as declared in linux/if_ether.h).
392  * Return 0 on success, or errno on error.
393  */
394 static int 
395 xen_net_read_mac(device_t dev, uint8_t mac[])
396 {
397         int error, i;
398         char *s, *e, *macstr;
399         const char *path;
400
401         path = xenbus_get_node(dev);
402         error = xs_read(XST_NIL, path, "mac", NULL, (void **) &macstr);
403         if (error == ENOENT) {
404                 /*
405                  * Deal with missing mac XenStore nodes on devices with
406                  * HVM emulation (the 'ioemu' configuration attribute)
407                  * enabled.
408                  *
409                  * The HVM emulator may execute in a stub device model
410                  * domain which lacks the permission, only given to Dom0,
411                  * to update the guest's XenStore tree.  For this reason,
412                  * the HVM emulator doesn't even attempt to write the
413                  * front-side mac node, even when operating in Dom0.
414                  * However, there should always be a mac listed in the
415                  * backend tree.  Fallback to this version if our query
416                  * of the front side XenStore location doesn't find
417                  * anything.
418                  */
419                 path = xenbus_get_otherend_path(dev);
420                 error = xs_read(XST_NIL, path, "mac", NULL, (void **) &macstr);
421         }
422         if (error != 0) {
423                 xenbus_dev_fatal(dev, error, "parsing %s/mac", path);
424                 return (error);
425         }
426
427         s = macstr;
428         for (i = 0; i < ETHER_ADDR_LEN; i++) {
429                 mac[i] = strtoul(s, &e, 16);
430                 if (s == e || (e[0] != ':' && e[0] != 0)) {
431                         free(macstr, M_XENBUS);
432                         return (ENOENT);
433                 }
434                 s = &e[1];
435         }
436         free(macstr, M_XENBUS);
437         return (0);
438 }
439
440 /**
441  * Entry point to this code when a new device is created.  Allocate the basic
442  * structures and the ring buffers for communication with the backend, and
443  * inform the backend of the appropriate details for those.  Switch to
444  * Connected state.
445  */
446 static int 
447 netfront_probe(device_t dev)
448 {
449
450         if (!strcmp(xenbus_get_type(dev), "vif")) {
451                 device_set_desc(dev, "Virtual Network Interface");
452                 return (0);
453         }
454
455         return (ENXIO);
456 }
457
458 static int
459 netfront_attach(device_t dev)
460 {       
461         int err;
462
463         err = create_netdev(dev);
464         if (err) {
465                 xenbus_dev_fatal(dev, err, "creating netdev");
466                 return (err);
467         }
468
469 #if __FreeBSD_version >= 700000
470         SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
471             SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
472             OID_AUTO, "enable_lro", CTLFLAG_RW,
473             &xn_enable_lro, 0, "Large Receive Offload");
474 #endif
475
476         return (0);
477 }
478
479 static int
480 netfront_suspend(device_t dev)
481 {
482         struct netfront_info *info = device_get_softc(dev);
483
484         XN_RX_LOCK(info);
485         XN_TX_LOCK(info);
486         netfront_carrier_off(info);
487         XN_TX_UNLOCK(info);
488         XN_RX_UNLOCK(info);
489         return (0);
490 }
491
492 /**
493  * We are reconnecting to the backend, due to a suspend/resume, or a backend
494  * driver restart.  We tear down our netif structure and recreate it, but
495  * leave the device-layer structures intact so that this is transparent to the
496  * rest of the kernel.
497  */
498 static int
499 netfront_resume(device_t dev)
500 {
501         struct netfront_info *info = device_get_softc(dev);
502
503         netif_disconnect_backend(info);
504         return (0);
505 }
506
507 /* Common code used when first setting up, and when resuming. */
508 static int 
509 talk_to_backend(device_t dev, struct netfront_info *info)
510 {
511         const char *message;
512         struct xs_transaction xst;
513         const char *node = xenbus_get_node(dev);
514         int err;
515
516         err = xen_net_read_mac(dev, info->mac);
517         if (err) {
518                 xenbus_dev_fatal(dev, err, "parsing %s/mac", node);
519                 goto out;
520         }
521
522         /* Create shared ring, alloc event channel. */
523         err = setup_device(dev, info);
524         if (err)
525                 goto out;
526         
527  again:
528         err = xs_transaction_start(&xst);
529         if (err) {
530                 xenbus_dev_fatal(dev, err, "starting transaction");
531                 goto destroy_ring;
532         }
533         err = xs_printf(xst, node, "tx-ring-ref","%u",
534                         info->tx_ring_ref);
535         if (err) {
536                 message = "writing tx ring-ref";
537                 goto abort_transaction;
538         }
539         err = xs_printf(xst, node, "rx-ring-ref","%u",
540                         info->rx_ring_ref);
541         if (err) {
542                 message = "writing rx ring-ref";
543                 goto abort_transaction;
544         }
545         err = xs_printf(xst, node,
546                         "event-channel", "%u",
547                         xen_intr_port(info->xen_intr_handle));
548         if (err) {
549                 message = "writing event-channel";
550                 goto abort_transaction;
551         }
552         err = xs_printf(xst, node, "request-rx-copy", "%u",
553                         info->copying_receiver);
554         if (err) {
555                 message = "writing request-rx-copy";
556                 goto abort_transaction;
557         }
558         err = xs_printf(xst, node, "feature-rx-notify", "%d", 1);
559         if (err) {
560                 message = "writing feature-rx-notify";
561                 goto abort_transaction;
562         }
563         err = xs_printf(xst, node, "feature-sg", "%d", 1);
564         if (err) {
565                 message = "writing feature-sg";
566                 goto abort_transaction;
567         }
568 #if __FreeBSD_version >= 700000
569         err = xs_printf(xst, node, "feature-gso-tcpv4", "%d", 1);
570         if (err) {
571                 message = "writing feature-gso-tcpv4";
572                 goto abort_transaction;
573         }
574 #endif
575
576         err = xs_transaction_end(xst, 0);
577         if (err) {
578                 if (err == EAGAIN)
579                         goto again;
580                 xenbus_dev_fatal(dev, err, "completing transaction");
581                 goto destroy_ring;
582         }
583         
584         return 0;
585         
586  abort_transaction:
587         xs_transaction_end(xst, 1);
588         xenbus_dev_fatal(dev, err, "%s", message);
589  destroy_ring:
590         netif_free(info);
591  out:
592         return err;
593 }
594
595 static int 
596 setup_device(device_t dev, struct netfront_info *info)
597 {
598         netif_tx_sring_t *txs;
599         netif_rx_sring_t *rxs;
600         int error;
601         struct ifnet *ifp;
602         
603         ifp = info->xn_ifp;
604
605         info->tx_ring_ref = GRANT_REF_INVALID;
606         info->rx_ring_ref = GRANT_REF_INVALID;
607         info->rx.sring = NULL;
608         info->tx.sring = NULL;
609
610         txs = (netif_tx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT|M_ZERO);
611         if (!txs) {
612                 error = ENOMEM;
613                 xenbus_dev_fatal(dev, error, "allocating tx ring page");
614                 goto fail;
615         }
616         SHARED_RING_INIT(txs);
617         FRONT_RING_INIT(&info->tx, txs, PAGE_SIZE);
618         error = xenbus_grant_ring(dev, virt_to_mfn(txs), &info->tx_ring_ref);
619         if (error)
620                 goto fail;
621
622         rxs = (netif_rx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF, M_NOWAIT|M_ZERO);
623         if (!rxs) {
624                 error = ENOMEM;
625                 xenbus_dev_fatal(dev, error, "allocating rx ring page");
626                 goto fail;
627         }
628         SHARED_RING_INIT(rxs);
629         FRONT_RING_INIT(&info->rx, rxs, PAGE_SIZE);
630
631         error = xenbus_grant_ring(dev, virt_to_mfn(rxs), &info->rx_ring_ref);
632         if (error)
633                 goto fail;
634
635         error = xen_intr_alloc_and_bind_local_port(dev,
636             xenbus_get_otherend_id(dev), /*filter*/NULL, xn_intr, info,
637             INTR_TYPE_NET | INTR_MPSAFE | INTR_ENTROPY, &info->xen_intr_handle);
638
639         if (error) {
640                 xenbus_dev_fatal(dev, error,
641                                  "xen_intr_alloc_and_bind_local_port failed");
642                 goto fail;
643         }
644
645         return (0);
646         
647  fail:
648         netif_free(info);
649         return (error);
650 }
651
652 #ifdef INET
653 /**
654  * If this interface has an ipv4 address, send an arp for it. This
655  * helps to get the network going again after migrating hosts.
656  */
657 static void
658 netfront_send_fake_arp(device_t dev, struct netfront_info *info)
659 {
660         struct ifnet *ifp;
661         struct ifaddr *ifa;
662         
663         ifp = info->xn_ifp;
664         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
665                 if (ifa->ifa_addr->sa_family == AF_INET) {
666                         arp_ifinit(ifp, ifa);
667                 }
668         }
669 }
670 #endif
671
672 /**
673  * Callback received when the backend's state changes.
674  */
675 static void
676 netfront_backend_changed(device_t dev, XenbusState newstate)
677 {
678         struct netfront_info *sc = device_get_softc(dev);
679                 
680         DPRINTK("newstate=%d\n", newstate);
681
682         switch (newstate) {
683         case XenbusStateInitialising:
684         case XenbusStateInitialised:
685         case XenbusStateUnknown:
686         case XenbusStateClosed:
687         case XenbusStateReconfigured:
688         case XenbusStateReconfiguring:
689                 break;
690         case XenbusStateInitWait:
691                 if (xenbus_get_state(dev) != XenbusStateInitialising)
692                         break;
693                 if (network_connect(sc) != 0)
694                         break;
695                 xenbus_set_state(dev, XenbusStateConnected);
696                 break;
697         case XenbusStateClosing:
698                 xenbus_set_state(dev, XenbusStateClosed);
699                 break;
700         case XenbusStateConnected:
701 #ifdef INET
702                 netfront_send_fake_arp(dev, sc);
703 #endif
704                 break;
705         }
706 }
707
708 static void
709 xn_free_rx_ring(struct netfront_info *sc)
710 {
711 #if 0
712         int i;
713         
714         for (i = 0; i < NET_RX_RING_SIZE; i++) {
715                 if (sc->xn_cdata.rx_mbufs[i] != NULL) {
716                         m_freem(sc->rx_mbufs[i]);
717                         sc->rx_mbufs[i] = NULL;
718                 }
719         }
720         
721         sc->rx.rsp_cons = 0;
722         sc->xn_rx_if->req_prod = 0;
723         sc->xn_rx_if->event = sc->rx.rsp_cons ;
724 #endif
725 }
726
727 static void
728 xn_free_tx_ring(struct netfront_info *sc)
729 {
730 #if 0
731         int i;
732         
733         for (i = 0; i < NET_TX_RING_SIZE; i++) {
734                 if (sc->tx_mbufs[i] != NULL) {
735                         m_freem(sc->tx_mbufs[i]);
736                         sc->xn_cdata.xn_tx_chain[i] = NULL;
737                 }
738         }
739         
740         return;
741 #endif
742 }
743
744 /**
745  * \brief Verify that there is sufficient space in the Tx ring
746  *        buffer for a maximally sized request to be enqueued.
747  *
748  * A transmit request requires a transmit descriptor for each packet
749  * fragment, plus up to 2 entries for "options" (e.g. TSO).
750  */
751 static inline int
752 xn_tx_slot_available(struct netfront_info *np)
753 {
754         return (RING_FREE_REQUESTS(&np->tx) > (MAX_TX_REQ_FRAGS + 2));
755 }
756
757 static void
758 netif_release_tx_bufs(struct netfront_info *np)
759 {
760         int i;
761
762         for (i = 1; i <= NET_TX_RING_SIZE; i++) {
763                 struct mbuf *m;
764
765                 m = np->tx_mbufs[i];
766
767                 /*
768                  * We assume that no kernel addresses are
769                  * less than NET_TX_RING_SIZE.  Any entry
770                  * in the table that is below this number
771                  * must be an index from free-list tracking.
772                  */
773                 if (((uintptr_t)m) <= NET_TX_RING_SIZE)
774                         continue;
775                 gnttab_end_foreign_access_ref(np->grant_tx_ref[i]);
776                 gnttab_release_grant_reference(&np->gref_tx_head,
777                     np->grant_tx_ref[i]);
778                 np->grant_tx_ref[i] = GRANT_REF_INVALID;
779                 add_id_to_freelist(np->tx_mbufs, i);
780                 np->xn_cdata.xn_tx_chain_cnt--;
781                 if (np->xn_cdata.xn_tx_chain_cnt < 0) {
782                         panic("%s: tx_chain_cnt must be >= 0", __func__);
783                 }
784                 m_free(m);
785         }
786 }
787
788 static void
789 network_alloc_rx_buffers(struct netfront_info *sc)
790 {
791         int otherend_id = xenbus_get_otherend_id(sc->xbdev);
792         unsigned short id;
793         struct mbuf *m_new;
794         int i, batch_target, notify;
795         RING_IDX req_prod;
796         struct xen_memory_reservation reservation;
797         grant_ref_t ref;
798         int nr_flips;
799         netif_rx_request_t *req;
800         vm_offset_t vaddr;
801         u_long pfn;
802         
803         req_prod = sc->rx.req_prod_pvt;
804
805         if (__predict_false(sc->carrier == 0))
806                 return;
807         
808         /*
809          * Allocate mbufs greedily, even though we batch updates to the
810          * receive ring. This creates a less bursty demand on the memory
811          * allocator, and so should reduce the chance of failed allocation
812          * requests both for ourself and for other kernel subsystems.
813          *
814          * Here we attempt to maintain rx_target buffers in flight, counting
815          * buffers that we have yet to process in the receive ring.
816          */
817         batch_target = sc->rx_target - (req_prod - sc->rx.rsp_cons);
818         for (i = mbufq_len(&sc->xn_rx_batch); i < batch_target; i++) {
819                 m_new = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
820                 if (m_new == NULL) {
821                         if (i != 0)
822                                 goto refill;
823                         /*
824                          * XXX set timer
825                          */
826                         break;
827                 }
828                 m_new->m_len = m_new->m_pkthdr.len = MJUMPAGESIZE;
829                 
830                 /* queue the mbufs allocated */
831                 (void )mbufq_enqueue(&sc->xn_rx_batch, m_new);
832         }
833         
834         /*
835          * If we've allocated at least half of our target number of entries,
836          * submit them to the backend - we have enough to make the overhead
837          * of submission worthwhile.  Otherwise wait for more mbufs and
838          * request entries to become available.
839          */
840         if (i < (sc->rx_target/2)) {
841                 if (req_prod >sc->rx.sring->req_prod)
842                         goto push;
843                 return;
844         }
845
846         /*
847          * Double floating fill target if we risked having the backend
848          * run out of empty buffers for receive traffic.  We define "running
849          * low" as having less than a fourth of our target buffers free
850          * at the time we refilled the queue. 
851          */
852         if ((req_prod - sc->rx.sring->rsp_prod) < (sc->rx_target / 4)) {
853                 sc->rx_target *= 2;
854                 if (sc->rx_target > sc->rx_max_target)
855                         sc->rx_target = sc->rx_max_target;
856         }
857
858 refill:
859         for (nr_flips = i = 0; ; i++) {
860                 if ((m_new = mbufq_dequeue(&sc->xn_rx_batch)) == NULL)
861                         break;
862
863                 m_new->m_ext.ext_arg1 = (vm_paddr_t *)(uintptr_t)(
864                                 vtophys(m_new->m_ext.ext_buf) >> PAGE_SHIFT);
865
866                 id = xennet_rxidx(req_prod + i);
867
868                 KASSERT(sc->rx_mbufs[id] == NULL, ("non-NULL xm_rx_chain"));
869                 sc->rx_mbufs[id] = m_new;
870
871                 ref = gnttab_claim_grant_reference(&sc->gref_rx_head);
872                 KASSERT(ref != GNTTAB_LIST_END,
873                         ("reserved grant references exhuasted"));
874                 sc->grant_rx_ref[id] = ref;
875
876                 vaddr = mtod(m_new, vm_offset_t);
877                 pfn = vtophys(vaddr) >> PAGE_SHIFT;
878                 req = RING_GET_REQUEST(&sc->rx, req_prod + i);
879
880                 if (sc->copying_receiver == 0) {
881                         gnttab_grant_foreign_transfer_ref(ref,
882                             otherend_id, pfn);
883                         sc->rx_pfn_array[nr_flips] = pfn;
884                         if (!xen_feature(XENFEAT_auto_translated_physmap)) {
885                                 /* Remove this page before passing
886                                  * back to Xen.
887                                  */
888                                 MULTI_update_va_mapping(&sc->rx_mcl[i],
889                                     vaddr, 0, 0);
890                         }
891                         nr_flips++;
892                 } else {
893                         gnttab_grant_foreign_access_ref(ref,
894                             otherend_id,
895                             pfn, 0);
896                 }
897                 req->id = id;
898                 req->gref = ref;
899                 
900                 sc->rx_pfn_array[i] =
901                     vtomach(mtod(m_new,vm_offset_t)) >> PAGE_SHIFT;
902         } 
903         
904         KASSERT(i, ("no mbufs processed")); /* should have returned earlier */
905         KASSERT(mbufq_len(&sc->xn_rx_batch) == 0, ("not all mbufs processed"));
906         /*
907          * We may have allocated buffers which have entries outstanding
908          * in the page * update queue -- make sure we flush those first!
909          */
910         if (nr_flips != 0) {
911 #ifdef notyet
912                 /* Tell the ballon driver what is going on. */
913                 balloon_update_driver_allowance(i);
914 #endif
915                 set_xen_guest_handle(reservation.extent_start, sc->rx_pfn_array);
916                 reservation.nr_extents   = i;
917                 reservation.extent_order = 0;
918                 reservation.address_bits = 0;
919                 reservation.domid        = DOMID_SELF;
920
921                 if (!xen_feature(XENFEAT_auto_translated_physmap)) {
922                         /* After all PTEs have been zapped, flush the TLB. */
923                         sc->rx_mcl[i-1].args[MULTI_UVMFLAGS_INDEX] =
924                             UVMF_TLB_FLUSH|UVMF_ALL;
925         
926                         /* Give away a batch of pages. */
927                         sc->rx_mcl[i].op = __HYPERVISOR_memory_op;
928                         sc->rx_mcl[i].args[0] = XENMEM_decrease_reservation;
929                         sc->rx_mcl[i].args[1] =  (u_long)&reservation;
930                         /* Zap PTEs and give away pages in one big multicall. */
931                         (void)HYPERVISOR_multicall(sc->rx_mcl, i+1);
932
933                         if (__predict_false(sc->rx_mcl[i].result != i ||
934                             HYPERVISOR_memory_op(XENMEM_decrease_reservation,
935                             &reservation) != i))
936                                 panic("%s: unable to reduce memory "
937                                     "reservation\n", __func__);
938                 }
939         } else {
940                 wmb();
941         }
942                         
943         /* Above is a suitable barrier to ensure backend will see requests. */
944         sc->rx.req_prod_pvt = req_prod + i;
945 push:
946         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->rx, notify);
947         if (notify)
948                 xen_intr_signal(sc->xen_intr_handle);
949 }
950
951 static void
952 xn_rxeof(struct netfront_info *np)
953 {
954         struct ifnet *ifp;
955 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
956         struct lro_ctrl *lro = &np->xn_lro;
957         struct lro_entry *queued;
958 #endif
959         struct netfront_rx_info rinfo;
960         struct netif_rx_response *rx = &rinfo.rx;
961         struct netif_extra_info *extras = rinfo.extras;
962         RING_IDX i, rp;
963         multicall_entry_t *mcl;
964         struct mbuf *m;
965         struct mbufq rxq, errq;
966         int err, pages_flipped = 0, work_to_do;
967
968         do {
969                 XN_RX_LOCK_ASSERT(np);
970                 if (!netfront_carrier_ok(np))
971                         return;
972
973                 /* XXX: there should be some sane limit. */
974                 mbufq_init(&errq, INT_MAX);
975                 mbufq_init(&rxq, INT_MAX);
976
977                 ifp = np->xn_ifp;
978         
979                 rp = np->rx.sring->rsp_prod;
980                 rmb();  /* Ensure we see queued responses up to 'rp'. */
981
982                 i = np->rx.rsp_cons;
983                 while ((i != rp)) {
984                         memcpy(rx, RING_GET_RESPONSE(&np->rx, i), sizeof(*rx));
985                         memset(extras, 0, sizeof(rinfo.extras));
986
987                         m = NULL;
988                         err = xennet_get_responses(np, &rinfo, rp, &i, &m,
989                             &pages_flipped);
990
991                         if (__predict_false(err)) {
992                                 if (m)
993                                         (void )mbufq_enqueue(&errq, m);
994                                 np->stats.rx_errors++;
995                                 continue;
996                         }
997
998                         m->m_pkthdr.rcvif = ifp;
999                         if ( rx->flags & NETRXF_data_validated ) {
1000                                 /* Tell the stack the checksums are okay */
1001                                 /*
1002                                  * XXX this isn't necessarily the case - need to add
1003                                  * check
1004                                  */
1005                                 
1006                                 m->m_pkthdr.csum_flags |=
1007                                         (CSUM_IP_CHECKED | CSUM_IP_VALID | CSUM_DATA_VALID
1008                                             | CSUM_PSEUDO_HDR);
1009                                 m->m_pkthdr.csum_data = 0xffff;
1010                         }
1011
1012                         np->stats.rx_packets++;
1013                         np->stats.rx_bytes += m->m_pkthdr.len;
1014
1015                         (void )mbufq_enqueue(&rxq, m);
1016                         np->rx.rsp_cons = i;
1017                 }
1018
1019                 if (pages_flipped) {
1020                         /* Some pages are no longer absent... */
1021 #ifdef notyet
1022                         balloon_update_driver_allowance(-pages_flipped);
1023 #endif
1024                         /* Do all the remapping work, and M->P updates, in one big
1025                          * hypercall.
1026                          */
1027                         if (!!xen_feature(XENFEAT_auto_translated_physmap)) {
1028                                 mcl = np->rx_mcl + pages_flipped;
1029                                 mcl->op = __HYPERVISOR_mmu_update;
1030                                 mcl->args[0] = (u_long)np->rx_mmu;
1031                                 mcl->args[1] = pages_flipped;
1032                                 mcl->args[2] = 0;
1033                                 mcl->args[3] = DOMID_SELF;
1034                                 (void)HYPERVISOR_multicall(np->rx_mcl,
1035                                     pages_flipped + 1);
1036                         }
1037                 }
1038         
1039                 mbufq_drain(&errq);
1040
1041                 /* 
1042                  * Process all the mbufs after the remapping is complete.
1043                  * Break the mbuf chain first though.
1044                  */
1045                 while ((m = mbufq_dequeue(&rxq)) != NULL) {
1046                         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1047                         
1048                         /*
1049                          * Do we really need to drop the rx lock?
1050                          */
1051                         XN_RX_UNLOCK(np);
1052 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
1053                         /* Use LRO if possible */
1054                         if ((ifp->if_capenable & IFCAP_LRO) == 0 ||
1055                             lro->lro_cnt == 0 || tcp_lro_rx(lro, m, 0)) {
1056                                 /*
1057                                  * If LRO fails, pass up to the stack
1058                                  * directly.
1059                                  */
1060                                 (*ifp->if_input)(ifp, m);
1061                         }
1062 #else
1063                         (*ifp->if_input)(ifp, m);
1064 #endif
1065                         XN_RX_LOCK(np);
1066                 }
1067         
1068                 np->rx.rsp_cons = i;
1069
1070 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
1071                 /*
1072                  * Flush any outstanding LRO work
1073                  */
1074                 while (!SLIST_EMPTY(&lro->lro_active)) {
1075                         queued = SLIST_FIRST(&lro->lro_active);
1076                         SLIST_REMOVE_HEAD(&lro->lro_active, next);
1077                         tcp_lro_flush(lro, queued);
1078                 }
1079 #endif
1080
1081 #if 0
1082                 /* If we get a callback with very few responses, reduce fill target. */
1083                 /* NB. Note exponential increase, linear decrease. */
1084                 if (((np->rx.req_prod_pvt - np->rx.sring->rsp_prod) > 
1085                         ((3*np->rx_target) / 4)) && (--np->rx_target < np->rx_min_target))
1086                         np->rx_target = np->rx_min_target;
1087 #endif
1088         
1089                 network_alloc_rx_buffers(np);
1090
1091                 RING_FINAL_CHECK_FOR_RESPONSES(&np->rx, work_to_do);
1092         } while (work_to_do);
1093 }
1094
1095 static void 
1096 xn_txeof(struct netfront_info *np)
1097 {
1098         RING_IDX i, prod;
1099         unsigned short id;
1100         struct ifnet *ifp;
1101         netif_tx_response_t *txr;
1102         struct mbuf *m;
1103         
1104         XN_TX_LOCK_ASSERT(np);
1105         
1106         if (!netfront_carrier_ok(np))
1107                 return;
1108         
1109         ifp = np->xn_ifp;
1110         
1111         do {
1112                 prod = np->tx.sring->rsp_prod;
1113                 rmb(); /* Ensure we see responses up to 'rp'. */
1114                 
1115                 for (i = np->tx.rsp_cons; i != prod; i++) {
1116                         txr = RING_GET_RESPONSE(&np->tx, i);
1117                         if (txr->status == NETIF_RSP_NULL)
1118                                 continue;
1119
1120                         if (txr->status != NETIF_RSP_OKAY) {
1121                                 printf("%s: WARNING: response is %d!\n",
1122                                        __func__, txr->status);
1123                         }
1124                         id = txr->id;
1125                         m = np->tx_mbufs[id]; 
1126                         KASSERT(m != NULL, ("mbuf not found in xn_tx_chain"));
1127                         KASSERT((uintptr_t)m > NET_TX_RING_SIZE,
1128                                 ("mbuf already on the free list, but we're "
1129                                 "trying to free it again!"));
1130                         M_ASSERTVALID(m);
1131                         
1132                         /*
1133                          * Increment packet count if this is the last
1134                          * mbuf of the chain.
1135                          */
1136                         if (!m->m_next)
1137                                 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1138                         if (__predict_false(gnttab_query_foreign_access(
1139                             np->grant_tx_ref[id]) != 0)) {
1140                                 panic("%s: grant id %u still in use by the "
1141                                     "backend", __func__, id);
1142                         }
1143                         gnttab_end_foreign_access_ref(
1144                                 np->grant_tx_ref[id]);
1145                         gnttab_release_grant_reference(
1146                                 &np->gref_tx_head, np->grant_tx_ref[id]);
1147                         np->grant_tx_ref[id] = GRANT_REF_INVALID;
1148                         
1149                         np->tx_mbufs[id] = NULL;
1150                         add_id_to_freelist(np->tx_mbufs, id);
1151                         np->xn_cdata.xn_tx_chain_cnt--;
1152                         m_free(m);
1153                         /* Only mark the queue active if we've freed up at least one slot to try */
1154                         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1155                 }
1156                 np->tx.rsp_cons = prod;
1157                 
1158                 /*
1159                  * Set a new event, then check for race with update of
1160                  * tx_cons. Note that it is essential to schedule a
1161                  * callback, no matter how few buffers are pending. Even if
1162                  * there is space in the transmit ring, higher layers may
1163                  * be blocked because too much data is outstanding: in such
1164                  * cases notification from Xen is likely to be the only kick
1165                  * that we'll get.
1166                  */
1167                 np->tx.sring->rsp_event =
1168                     prod + ((np->tx.sring->req_prod - prod) >> 1) + 1;
1169
1170                 mb();
1171         } while (prod != np->tx.sring->rsp_prod);
1172         
1173         if (np->tx_full &&
1174             ((np->tx.sring->req_prod - prod) < NET_TX_RING_SIZE)) {
1175                 np->tx_full = 0;
1176 #if 0
1177                 if (np->user_state == UST_OPEN)
1178                         netif_wake_queue(dev);
1179 #endif
1180         }
1181 }
1182
1183 static void
1184 xn_intr(void *xsc)
1185 {
1186         struct netfront_info *np = xsc;
1187         struct ifnet *ifp = np->xn_ifp;
1188
1189 #if 0
1190         if (!(np->rx.rsp_cons != np->rx.sring->rsp_prod &&
1191             likely(netfront_carrier_ok(np)) &&
1192             ifp->if_drv_flags & IFF_DRV_RUNNING))
1193                 return;
1194 #endif
1195         if (RING_HAS_UNCONSUMED_RESPONSES(&np->tx)) {
1196                 XN_TX_LOCK(np);
1197                 xn_txeof(np);
1198                 XN_TX_UNLOCK(np);                       
1199         }       
1200
1201         XN_RX_LOCK(np);
1202         xn_rxeof(np);
1203         XN_RX_UNLOCK(np);
1204
1205         if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1206             !IFQ_DRV_IS_EMPTY(&ifp->if_snd))
1207                 xn_start(ifp);
1208 }
1209
1210 static void
1211 xennet_move_rx_slot(struct netfront_info *np, struct mbuf *m,
1212         grant_ref_t ref)
1213 {
1214         int new = xennet_rxidx(np->rx.req_prod_pvt);
1215
1216         KASSERT(np->rx_mbufs[new] == NULL, ("rx_mbufs != NULL"));
1217         np->rx_mbufs[new] = m;
1218         np->grant_rx_ref[new] = ref;
1219         RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->id = new;
1220         RING_GET_REQUEST(&np->rx, np->rx.req_prod_pvt)->gref = ref;
1221         np->rx.req_prod_pvt++;
1222 }
1223
1224 static int
1225 xennet_get_extras(struct netfront_info *np,
1226     struct netif_extra_info *extras, RING_IDX rp, RING_IDX *cons)
1227 {
1228         struct netif_extra_info *extra;
1229
1230         int err = 0;
1231
1232         do {
1233                 struct mbuf *m;
1234                 grant_ref_t ref;
1235
1236                 if (__predict_false(*cons + 1 == rp)) {
1237 #if 0                   
1238                         if (net_ratelimit())
1239                                 WPRINTK("Missing extra info\n");
1240 #endif                  
1241                         err = EINVAL;
1242                         break;
1243                 }
1244
1245                 extra = (struct netif_extra_info *)
1246                 RING_GET_RESPONSE(&np->rx, ++(*cons));
1247
1248                 if (__predict_false(!extra->type ||
1249                         extra->type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
1250 #if 0                           
1251                         if (net_ratelimit())
1252                                 WPRINTK("Invalid extra type: %d\n",
1253                                         extra->type);
1254 #endif                  
1255                         err = EINVAL;
1256                 } else {
1257                         memcpy(&extras[extra->type - 1], extra, sizeof(*extra));
1258                 }
1259
1260                 m = xennet_get_rx_mbuf(np, *cons);
1261                 ref = xennet_get_rx_ref(np, *cons);
1262                 xennet_move_rx_slot(np, m, ref);
1263         } while (extra->flags & XEN_NETIF_EXTRA_FLAG_MORE);
1264
1265         return err;
1266 }
1267
1268 static int
1269 xennet_get_responses(struct netfront_info *np,
1270         struct netfront_rx_info *rinfo, RING_IDX rp, RING_IDX *cons,
1271         struct mbuf  **list,
1272         int *pages_flipped_p)
1273 {
1274         int pages_flipped = *pages_flipped_p;
1275         struct mmu_update *mmu;
1276         struct multicall_entry *mcl;
1277         struct netif_rx_response *rx = &rinfo->rx;
1278         struct netif_extra_info *extras = rinfo->extras;
1279         struct mbuf *m, *m0, *m_prev;
1280         grant_ref_t ref = xennet_get_rx_ref(np, *cons);
1281         RING_IDX ref_cons = *cons;
1282         int frags = 1;
1283         int err = 0;
1284         u_long ret;
1285
1286         m0 = m = m_prev = xennet_get_rx_mbuf(np, *cons);
1287
1288         if (rx->flags & NETRXF_extra_info) {
1289                 err = xennet_get_extras(np, extras, rp, cons);
1290         }
1291
1292         if (m0 != NULL) {
1293                 m0->m_pkthdr.len = 0;
1294                 m0->m_next = NULL;
1295         }
1296
1297         for (;;) {
1298                 u_long mfn;
1299
1300 #if 0           
1301                 DPRINTK("rx->status=%hd rx->offset=%hu frags=%u\n",
1302                         rx->status, rx->offset, frags);
1303 #endif
1304                 if (__predict_false(rx->status < 0 ||
1305                         rx->offset + rx->status > PAGE_SIZE)) {
1306
1307 #if 0                                           
1308                         if (net_ratelimit())
1309                                 WPRINTK("rx->offset: %x, size: %u\n",
1310                                         rx->offset, rx->status);
1311 #endif                                          
1312                         xennet_move_rx_slot(np, m, ref);
1313                         if (m0 == m)
1314                                 m0 = NULL;
1315                         m = NULL;
1316                         err = EINVAL;
1317                         goto next_skip_queue;
1318                 }
1319                 
1320                 /*
1321                  * This definitely indicates a bug, either in this driver or in
1322                  * the backend driver. In future this should flag the bad
1323                  * situation to the system controller to reboot the backed.
1324                  */
1325                 if (ref == GRANT_REF_INVALID) {
1326
1327 #if 0                           
1328                         if (net_ratelimit())
1329                                 WPRINTK("Bad rx response id %d.\n", rx->id);
1330 #endif                  
1331                         printf("%s: Bad rx response id %d.\n", __func__,rx->id);
1332                         err = EINVAL;
1333                         goto next;
1334                 }
1335
1336                 if (!np->copying_receiver) {
1337                         /* Memory pressure, insufficient buffer
1338                          * headroom, ...
1339                          */
1340                         if (!(mfn = gnttab_end_foreign_transfer_ref(ref))) {
1341                                 WPRINTK("Unfulfilled rx req (id=%d, st=%d).\n",
1342                                         rx->id, rx->status);
1343                                 xennet_move_rx_slot(np, m, ref);
1344                                 err = ENOMEM;
1345                                 goto next;
1346                         }
1347
1348                         if (!xen_feature( XENFEAT_auto_translated_physmap)) {
1349                                 /* Remap the page. */
1350                                 void *vaddr = mtod(m, void *);
1351                                 uint32_t pfn;
1352
1353                                 mcl = np->rx_mcl + pages_flipped;
1354                                 mmu = np->rx_mmu + pages_flipped;
1355
1356                                 MULTI_update_va_mapping(mcl, (u_long)vaddr,
1357                                     (((vm_paddr_t)mfn) << PAGE_SHIFT) | PG_RW |
1358                                     PG_V | PG_M | PG_A, 0);
1359                                 pfn = (uintptr_t)m->m_ext.ext_arg1;
1360                                 mmu->ptr = ((vm_paddr_t)mfn << PAGE_SHIFT) |
1361                                     MMU_MACHPHYS_UPDATE;
1362                                 mmu->val = pfn;
1363                         }
1364                         pages_flipped++;
1365                 } else {
1366                         ret = gnttab_end_foreign_access_ref(ref);
1367                         KASSERT(ret, ("ret != 0"));
1368                 }
1369
1370                 gnttab_release_grant_reference(&np->gref_rx_head, ref);
1371
1372 next:
1373                 if (m == NULL)
1374                         break;
1375
1376                 m->m_len = rx->status;
1377                 m->m_data += rx->offset;
1378                 m0->m_pkthdr.len += rx->status;
1379                 
1380 next_skip_queue:
1381                 if (!(rx->flags & NETRXF_more_data))
1382                         break;
1383
1384                 if (*cons + frags == rp) {
1385                         if (net_ratelimit())
1386                                 WPRINTK("Need more frags\n");
1387                         err = ENOENT;
1388                         printf("%s: cons %u frags %u rp %u, not enough frags\n",
1389                                __func__, *cons, frags, rp);
1390                         break;
1391                 }
1392                 /*
1393                  * Note that m can be NULL, if rx->status < 0 or if
1394                  * rx->offset + rx->status > PAGE_SIZE above.  
1395                  */
1396                 m_prev = m;
1397                 
1398                 rx = RING_GET_RESPONSE(&np->rx, *cons + frags);
1399                 m = xennet_get_rx_mbuf(np, *cons + frags);
1400
1401                 /*
1402                  * m_prev == NULL can happen if rx->status < 0 or if
1403                  * rx->offset + * rx->status > PAGE_SIZE above.  
1404                  */
1405                 if (m_prev != NULL)
1406                         m_prev->m_next = m;
1407
1408                 /*
1409                  * m0 can be NULL if rx->status < 0 or if * rx->offset +
1410                  * rx->status > PAGE_SIZE above.  
1411                  */
1412                 if (m0 == NULL)
1413                         m0 = m;
1414                 m->m_next = NULL;
1415                 ref = xennet_get_rx_ref(np, *cons + frags);
1416                 ref_cons = *cons + frags;
1417                 frags++;
1418         }
1419         *list = m0;
1420         *cons += frags;
1421         *pages_flipped_p = pages_flipped;
1422
1423         return (err);
1424 }
1425
1426 static void
1427 xn_tick_locked(struct netfront_info *sc) 
1428 {
1429         XN_RX_LOCK_ASSERT(sc);
1430         callout_reset(&sc->xn_stat_ch, hz, xn_tick, sc);
1431
1432         /* XXX placeholder for printing debug information */
1433 }
1434
1435 static void
1436 xn_tick(void *xsc) 
1437 {
1438         struct netfront_info *sc;
1439     
1440         sc = xsc;
1441         XN_RX_LOCK(sc);
1442         xn_tick_locked(sc);
1443         XN_RX_UNLOCK(sc);
1444 }
1445
1446 /**
1447  * \brief Count the number of fragments in an mbuf chain.
1448  *
1449  * Surprisingly, there isn't an M* macro for this.
1450  */
1451 static inline int
1452 xn_count_frags(struct mbuf *m)
1453 {
1454         int nfrags;
1455
1456         for (nfrags = 0; m != NULL; m = m->m_next)
1457                 nfrags++;
1458
1459         return (nfrags);
1460 }
1461
1462 /**
1463  * Given an mbuf chain, make sure we have enough room and then push
1464  * it onto the transmit ring.
1465  */
1466 static int
1467 xn_assemble_tx_request(struct netfront_info *sc, struct mbuf *m_head)
1468 {
1469         struct ifnet *ifp;
1470         struct mbuf *m;
1471         u_int nfrags;
1472         int otherend_id;
1473
1474         ifp = sc->xn_ifp;
1475
1476         /**
1477          * Defragment the mbuf if necessary.
1478          */
1479         nfrags = xn_count_frags(m_head);
1480
1481         /*
1482          * Check to see whether this request is longer than netback
1483          * can handle, and try to defrag it.
1484          */
1485         /**
1486          * It is a bit lame, but the netback driver in Linux can't
1487          * deal with nfrags > MAX_TX_REQ_FRAGS, which is a quirk of
1488          * the Linux network stack.
1489          */
1490         if (nfrags > sc->maxfrags) {
1491                 m = m_defrag(m_head, M_NOWAIT);
1492                 if (!m) {
1493                         /*
1494                          * Defrag failed, so free the mbuf and
1495                          * therefore drop the packet.
1496                          */
1497                         m_freem(m_head);
1498                         return (EMSGSIZE);
1499                 }
1500                 m_head = m;
1501         }
1502
1503         /* Determine how many fragments now exist */
1504         nfrags = xn_count_frags(m_head);
1505
1506         /*
1507          * Check to see whether the defragmented packet has too many
1508          * segments for the Linux netback driver.
1509          */
1510         /**
1511          * The FreeBSD TCP stack, with TSO enabled, can produce a chain
1512          * of mbufs longer than Linux can handle.  Make sure we don't
1513          * pass a too-long chain over to the other side by dropping the
1514          * packet.  It doesn't look like there is currently a way to
1515          * tell the TCP stack to generate a shorter chain of packets.
1516          */
1517         if (nfrags > MAX_TX_REQ_FRAGS) {
1518 #ifdef DEBUG
1519                 printf("%s: nfrags %d > MAX_TX_REQ_FRAGS %d, netback "
1520                        "won't be able to handle it, dropping\n",
1521                        __func__, nfrags, MAX_TX_REQ_FRAGS);
1522 #endif
1523                 m_freem(m_head);
1524                 return (EMSGSIZE);
1525         }
1526
1527         /*
1528          * This check should be redundant.  We've already verified that we
1529          * have enough slots in the ring to handle a packet of maximum
1530          * size, and that our packet is less than the maximum size.  Keep
1531          * it in here as an assert for now just to make certain that
1532          * xn_tx_chain_cnt is accurate.
1533          */
1534         KASSERT((sc->xn_cdata.xn_tx_chain_cnt + nfrags) <= NET_TX_RING_SIZE,
1535                 ("%s: xn_tx_chain_cnt (%d) + nfrags (%d) > NET_TX_RING_SIZE "
1536                  "(%d)!", __func__, (int) sc->xn_cdata.xn_tx_chain_cnt,
1537                     (int) nfrags, (int) NET_TX_RING_SIZE));
1538
1539         /*
1540          * Start packing the mbufs in this chain into
1541          * the fragment pointers. Stop when we run out
1542          * of fragments or hit the end of the mbuf chain.
1543          */
1544         m = m_head;
1545         otherend_id = xenbus_get_otherend_id(sc->xbdev);
1546         for (m = m_head; m; m = m->m_next) {
1547                 netif_tx_request_t *tx;
1548                 uintptr_t id;
1549                 grant_ref_t ref;
1550                 u_long mfn; /* XXX Wrong type? */
1551
1552                 tx = RING_GET_REQUEST(&sc->tx, sc->tx.req_prod_pvt);
1553                 id = get_id_from_freelist(sc->tx_mbufs);
1554                 if (id == 0)
1555                         panic("%s: was allocated the freelist head!\n",
1556                             __func__);
1557                 sc->xn_cdata.xn_tx_chain_cnt++;
1558                 if (sc->xn_cdata.xn_tx_chain_cnt > NET_TX_RING_SIZE)
1559                         panic("%s: tx_chain_cnt must be <= NET_TX_RING_SIZE\n",
1560                             __func__);
1561                 sc->tx_mbufs[id] = m;
1562                 tx->id = id;
1563                 ref = gnttab_claim_grant_reference(&sc->gref_tx_head);
1564                 KASSERT((short)ref >= 0, ("Negative ref"));
1565                 mfn = virt_to_mfn(mtod(m, vm_offset_t));
1566                 gnttab_grant_foreign_access_ref(ref, otherend_id,
1567                     mfn, GNTMAP_readonly);
1568                 tx->gref = sc->grant_tx_ref[id] = ref;
1569                 tx->offset = mtod(m, vm_offset_t) & (PAGE_SIZE - 1);
1570                 tx->flags = 0;
1571                 if (m == m_head) {
1572                         /*
1573                          * The first fragment has the entire packet
1574                          * size, subsequent fragments have just the
1575                          * fragment size. The backend works out the
1576                          * true size of the first fragment by
1577                          * subtracting the sizes of the other
1578                          * fragments.
1579                          */
1580                         tx->size = m->m_pkthdr.len;
1581
1582                         /*
1583                          * The first fragment contains the checksum flags
1584                          * and is optionally followed by extra data for
1585                          * TSO etc.
1586                          */
1587                         /**
1588                          * CSUM_TSO requires checksum offloading.
1589                          * Some versions of FreeBSD fail to
1590                          * set CSUM_TCP in the CSUM_TSO case,
1591                          * so we have to test for CSUM_TSO
1592                          * explicitly.
1593                          */
1594                         if (m->m_pkthdr.csum_flags
1595                             & (CSUM_DELAY_DATA | CSUM_TSO)) {
1596                                 tx->flags |= (NETTXF_csum_blank
1597                                     | NETTXF_data_validated);
1598                         }
1599 #if __FreeBSD_version >= 700000
1600                         if (m->m_pkthdr.csum_flags & CSUM_TSO) {
1601                                 struct netif_extra_info *gso =
1602                                         (struct netif_extra_info *)
1603                                         RING_GET_REQUEST(&sc->tx,
1604                                                          ++sc->tx.req_prod_pvt);
1605
1606                                 tx->flags |= NETTXF_extra_info;
1607
1608                                 gso->u.gso.size = m->m_pkthdr.tso_segsz;
1609                                 gso->u.gso.type =
1610                                         XEN_NETIF_GSO_TYPE_TCPV4;
1611                                 gso->u.gso.pad = 0;
1612                                 gso->u.gso.features = 0;
1613
1614                                 gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
1615                                 gso->flags = 0;
1616                         }
1617 #endif
1618                 } else {
1619                         tx->size = m->m_len;
1620                 }
1621                 if (m->m_next)
1622                         tx->flags |= NETTXF_more_data;
1623
1624                 sc->tx.req_prod_pvt++;
1625         }
1626         BPF_MTAP(ifp, m_head);
1627
1628         sc->stats.tx_bytes += m_head->m_pkthdr.len;
1629         sc->stats.tx_packets++;
1630
1631         return (0);
1632 }
1633
1634 static void
1635 xn_start_locked(struct ifnet *ifp) 
1636 {
1637         struct netfront_info *sc;
1638         struct mbuf *m_head;
1639         int notify;
1640
1641         sc = ifp->if_softc;
1642
1643         if (!netfront_carrier_ok(sc))
1644                 return;
1645
1646         /*
1647          * While we have enough transmit slots available for at least one
1648          * maximum-sized packet, pull mbufs off the queue and put them on
1649          * the transmit ring.
1650          */
1651         while (xn_tx_slot_available(sc)) {
1652                 IF_DEQUEUE(&ifp->if_snd, m_head);
1653                 if (m_head == NULL)
1654                         break;
1655
1656                 if (xn_assemble_tx_request(sc, m_head) != 0)
1657                         break;
1658         }
1659
1660         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&sc->tx, notify);
1661         if (notify)
1662                 xen_intr_signal(sc->xen_intr_handle);
1663
1664         if (RING_FULL(&sc->tx)) {
1665                 sc->tx_full = 1;
1666 #if 0
1667                 netif_stop_queue(dev);
1668 #endif
1669         }
1670 }
1671
1672 static void
1673 xn_start(struct ifnet *ifp)
1674 {
1675         struct netfront_info *sc;
1676         sc = ifp->if_softc;
1677         XN_TX_LOCK(sc);
1678         xn_start_locked(ifp);
1679         XN_TX_UNLOCK(sc);
1680 }
1681
1682 /* equivalent of network_open() in Linux */
1683 static void 
1684 xn_ifinit_locked(struct netfront_info *sc) 
1685 {
1686         struct ifnet *ifp;
1687         
1688         XN_LOCK_ASSERT(sc);
1689         
1690         ifp = sc->xn_ifp;
1691         
1692         if (ifp->if_drv_flags & IFF_DRV_RUNNING) 
1693                 return;
1694         
1695         xn_stop(sc);
1696         
1697         network_alloc_rx_buffers(sc);
1698         sc->rx.sring->rsp_event = sc->rx.rsp_cons + 1;
1699         
1700         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1701         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1702         if_link_state_change(ifp, LINK_STATE_UP);
1703         
1704         callout_reset(&sc->xn_stat_ch, hz, xn_tick, sc);
1705 }
1706
1707 static void 
1708 xn_ifinit(void *xsc)
1709 {
1710         struct netfront_info *sc = xsc;
1711     
1712         XN_LOCK(sc);
1713         xn_ifinit_locked(sc);
1714         XN_UNLOCK(sc);
1715 }
1716
1717 static int
1718 xn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1719 {
1720         struct netfront_info *sc = ifp->if_softc;
1721         struct ifreq *ifr = (struct ifreq *) data;
1722 #ifdef INET
1723         struct ifaddr *ifa = (struct ifaddr *)data;
1724 #endif
1725
1726         int mask, error = 0;
1727         switch(cmd) {
1728         case SIOCSIFADDR:
1729 #ifdef INET
1730                 XN_LOCK(sc);
1731                 if (ifa->ifa_addr->sa_family == AF_INET) {
1732                         ifp->if_flags |= IFF_UP;
1733                         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) 
1734                                 xn_ifinit_locked(sc);
1735                         arp_ifinit(ifp, ifa);
1736                         XN_UNLOCK(sc);  
1737                 } else {
1738                         XN_UNLOCK(sc);  
1739 #endif
1740                         error = ether_ioctl(ifp, cmd, data);
1741 #ifdef INET
1742                 }
1743 #endif
1744                 break;
1745         case SIOCSIFMTU:
1746                 /* XXX can we alter the MTU on a VN ?*/
1747 #ifdef notyet
1748                 if (ifr->ifr_mtu > XN_JUMBO_MTU)
1749                         error = EINVAL;
1750                 else 
1751 #endif
1752                 {
1753                         ifp->if_mtu = ifr->ifr_mtu;
1754                         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1755                         xn_ifinit(sc);
1756                 }
1757                 break;
1758         case SIOCSIFFLAGS:
1759                 XN_LOCK(sc);
1760                 if (ifp->if_flags & IFF_UP) {
1761                         /*
1762                          * If only the state of the PROMISC flag changed,
1763                          * then just use the 'set promisc mode' command
1764                          * instead of reinitializing the entire NIC. Doing
1765                          * a full re-init means reloading the firmware and
1766                          * waiting for it to start up, which may take a
1767                          * second or two.
1768                          */
1769 #ifdef notyet
1770                         /* No promiscuous mode with Xen */
1771                         if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1772                             ifp->if_flags & IFF_PROMISC &&
1773                             !(sc->xn_if_flags & IFF_PROMISC)) {
1774                                 XN_SETBIT(sc, XN_RX_MODE,
1775                                           XN_RXMODE_RX_PROMISC);
1776                         } else if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1777                                    !(ifp->if_flags & IFF_PROMISC) &&
1778                                    sc->xn_if_flags & IFF_PROMISC) {
1779                                 XN_CLRBIT(sc, XN_RX_MODE,
1780                                           XN_RXMODE_RX_PROMISC);
1781                         } else
1782 #endif
1783                                 xn_ifinit_locked(sc);
1784                 } else {
1785                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1786                                 xn_stop(sc);
1787                         }
1788                 }
1789                 sc->xn_if_flags = ifp->if_flags;
1790                 XN_UNLOCK(sc);
1791                 error = 0;
1792                 break;
1793         case SIOCSIFCAP:
1794                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1795                 if (mask & IFCAP_TXCSUM) {
1796                         if (IFCAP_TXCSUM & ifp->if_capenable) {
1797                                 ifp->if_capenable &= ~(IFCAP_TXCSUM|IFCAP_TSO4);
1798                                 ifp->if_hwassist &= ~(CSUM_TCP | CSUM_UDP
1799                                     | CSUM_IP | CSUM_TSO);
1800                         } else {
1801                                 ifp->if_capenable |= IFCAP_TXCSUM;
1802                                 ifp->if_hwassist |= (CSUM_TCP | CSUM_UDP
1803                                     | CSUM_IP);
1804                         }
1805                 }
1806                 if (mask & IFCAP_RXCSUM) {
1807                         ifp->if_capenable ^= IFCAP_RXCSUM;
1808                 }
1809 #if __FreeBSD_version >= 700000
1810                 if (mask & IFCAP_TSO4) {
1811                         if (IFCAP_TSO4 & ifp->if_capenable) {
1812                                 ifp->if_capenable &= ~IFCAP_TSO4;
1813                                 ifp->if_hwassist &= ~CSUM_TSO;
1814                         } else if (IFCAP_TXCSUM & ifp->if_capenable) {
1815                                 ifp->if_capenable |= IFCAP_TSO4;
1816                                 ifp->if_hwassist |= CSUM_TSO;
1817                         } else {
1818                                 IPRINTK("Xen requires tx checksum offload"
1819                                     " be enabled to use TSO\n");
1820                                 error = EINVAL;
1821                         }
1822                 }
1823                 if (mask & IFCAP_LRO) {
1824                         ifp->if_capenable ^= IFCAP_LRO;
1825                         
1826                 }
1827 #endif
1828                 error = 0;
1829                 break;
1830         case SIOCADDMULTI:
1831         case SIOCDELMULTI:
1832 #ifdef notyet
1833                 if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1834                         XN_LOCK(sc);
1835                         xn_setmulti(sc);
1836                         XN_UNLOCK(sc);
1837                         error = 0;
1838                 }
1839 #endif
1840                 /* FALLTHROUGH */
1841         case SIOCSIFMEDIA:
1842         case SIOCGIFMEDIA:
1843                 error = ifmedia_ioctl(ifp, ifr, &sc->sc_media, cmd);
1844                 break;
1845         default:
1846                 error = ether_ioctl(ifp, cmd, data);
1847         }
1848     
1849         return (error);
1850 }
1851
1852 static void
1853 xn_stop(struct netfront_info *sc)
1854 {       
1855         struct ifnet *ifp;
1856
1857         XN_LOCK_ASSERT(sc);
1858     
1859         ifp = sc->xn_ifp;
1860
1861         callout_stop(&sc->xn_stat_ch);
1862
1863         xn_free_rx_ring(sc);
1864         xn_free_tx_ring(sc);
1865     
1866         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1867         if_link_state_change(ifp, LINK_STATE_DOWN);
1868 }
1869
1870 /* START of Xenolinux helper functions adapted to FreeBSD */
1871 int
1872 network_connect(struct netfront_info *np)
1873 {
1874         int i, requeue_idx, error;
1875         grant_ref_t ref;
1876         netif_rx_request_t *req;
1877         u_int feature_rx_copy, feature_rx_flip;
1878
1879         error = xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1880             "feature-rx-copy", NULL, "%u", &feature_rx_copy);
1881         if (error)
1882                 feature_rx_copy = 0;
1883         error = xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1884             "feature-rx-flip", NULL, "%u", &feature_rx_flip);
1885         if (error)
1886                 feature_rx_flip = 1;
1887
1888         /*
1889          * Copy packets on receive path if:
1890          *  (a) This was requested by user, and the backend supports it; or
1891          *  (b) Flipping was requested, but this is unsupported by the backend.
1892          */
1893         np->copying_receiver = ((MODPARM_rx_copy && feature_rx_copy) ||
1894                                 (MODPARM_rx_flip && !feature_rx_flip));
1895
1896         /* Recovery procedure: */
1897         error = talk_to_backend(np->xbdev, np);
1898         if (error) 
1899                 return (error);
1900         
1901         /* Step 1: Reinitialise variables. */
1902         xn_query_features(np);
1903         xn_configure_features(np);
1904         netif_release_tx_bufs(np);
1905
1906         /* Step 2: Rebuild the RX buffer freelist and the RX ring itself. */
1907         for (requeue_idx = 0, i = 0; i < NET_RX_RING_SIZE; i++) {
1908                 struct mbuf *m;
1909                 u_long pfn;
1910
1911                 if (np->rx_mbufs[i] == NULL)
1912                         continue;
1913
1914                 m = np->rx_mbufs[requeue_idx] = xennet_get_rx_mbuf(np, i);
1915                 ref = np->grant_rx_ref[requeue_idx] = xennet_get_rx_ref(np, i);
1916
1917                 req = RING_GET_REQUEST(&np->rx, requeue_idx);
1918                 pfn = vtophys(mtod(m, vm_offset_t)) >> PAGE_SHIFT;
1919
1920                 if (!np->copying_receiver) {
1921                         gnttab_grant_foreign_transfer_ref(ref,
1922                             xenbus_get_otherend_id(np->xbdev),
1923                             pfn);
1924                 } else {
1925                         gnttab_grant_foreign_access_ref(ref,
1926                             xenbus_get_otherend_id(np->xbdev),
1927                             pfn, 0);
1928                 }
1929                 req->gref = ref;
1930                 req->id   = requeue_idx;
1931
1932                 requeue_idx++;
1933         }
1934
1935         np->rx.req_prod_pvt = requeue_idx;
1936         
1937         /* Step 3: All public and private state should now be sane.  Get
1938          * ready to start sending and receiving packets and give the driver
1939          * domain a kick because we've probably just requeued some
1940          * packets.
1941          */
1942         netfront_carrier_on(np);
1943         xen_intr_signal(np->xen_intr_handle);
1944         XN_TX_LOCK(np);
1945         xn_txeof(np);
1946         XN_TX_UNLOCK(np);
1947         network_alloc_rx_buffers(np);
1948
1949         return (0);
1950 }
1951
1952 static void
1953 xn_query_features(struct netfront_info *np)
1954 {
1955         int val;
1956
1957         device_printf(np->xbdev, "backend features:");
1958
1959         if (xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1960                 "feature-sg", NULL, "%d", &val) < 0)
1961                 val = 0;
1962
1963         np->maxfrags = 1;
1964         if (val) {
1965                 np->maxfrags = MAX_TX_REQ_FRAGS;
1966                 printf(" feature-sg");
1967         }
1968
1969         if (xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1970                 "feature-gso-tcpv4", NULL, "%d", &val) < 0)
1971                 val = 0;
1972
1973         np->xn_ifp->if_capabilities &= ~(IFCAP_TSO4|IFCAP_LRO);
1974         if (val) {
1975                 np->xn_ifp->if_capabilities |= IFCAP_TSO4|IFCAP_LRO;
1976                 printf(" feature-gso-tcp4");
1977         }
1978
1979         printf("\n");
1980 }
1981
1982 static int
1983 xn_configure_features(struct netfront_info *np)
1984 {
1985         int err;
1986
1987         err = 0;
1988 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
1989         if ((np->xn_ifp->if_capenable & IFCAP_LRO) != 0)
1990                 tcp_lro_free(&np->xn_lro);
1991 #endif
1992         np->xn_ifp->if_capenable =
1993             np->xn_ifp->if_capabilities & ~(IFCAP_LRO|IFCAP_TSO4);
1994         np->xn_ifp->if_hwassist &= ~CSUM_TSO;
1995 #if __FreeBSD_version >= 700000 && (defined(INET) || defined(INET6))
1996         if (xn_enable_lro && (np->xn_ifp->if_capabilities & IFCAP_LRO) != 0) {
1997                 err = tcp_lro_init(&np->xn_lro);
1998                 if (err) {
1999                         device_printf(np->xbdev, "LRO initialization failed\n");
2000                 } else {
2001                         np->xn_lro.ifp = np->xn_ifp;
2002                         np->xn_ifp->if_capenable |= IFCAP_LRO;
2003                 }
2004         }
2005         if ((np->xn_ifp->if_capabilities & IFCAP_TSO4) != 0) {
2006                 np->xn_ifp->if_capenable |= IFCAP_TSO4;
2007                 np->xn_ifp->if_hwassist |= CSUM_TSO;
2008         }
2009 #endif
2010         return (err);
2011 }
2012
2013 /**
2014  * Create a network device.
2015  * @param dev  Newbus device representing this virtual NIC.
2016  */
2017 int 
2018 create_netdev(device_t dev)
2019 {
2020         int i;
2021         struct netfront_info *np;
2022         int err;
2023         struct ifnet *ifp;
2024
2025         np = device_get_softc(dev);
2026         
2027         np->xbdev         = dev;
2028     
2029         XN_LOCK_INIT(np, xennetif);
2030
2031         ifmedia_init(&np->sc_media, 0, xn_ifmedia_upd, xn_ifmedia_sts);
2032         ifmedia_add(&np->sc_media, IFM_ETHER|IFM_MANUAL, 0, NULL);
2033         ifmedia_set(&np->sc_media, IFM_ETHER|IFM_MANUAL);
2034
2035         np->rx_target     = RX_MIN_TARGET;
2036         np->rx_min_target = RX_MIN_TARGET;
2037         np->rx_max_target = RX_MAX_TARGET;
2038
2039         /* Initialise {tx,rx}_skbs to be a free chain containing every entry. */
2040         for (i = 0; i <= NET_TX_RING_SIZE; i++) {
2041                 np->tx_mbufs[i] = (void *) ((u_long) i+1);
2042                 np->grant_tx_ref[i] = GRANT_REF_INVALID;        
2043         }
2044         np->tx_mbufs[NET_TX_RING_SIZE] = (void *)0;
2045
2046         for (i = 0; i <= NET_RX_RING_SIZE; i++) {
2047
2048                 np->rx_mbufs[i] = NULL;
2049                 np->grant_rx_ref[i] = GRANT_REF_INVALID;
2050         }
2051
2052         mbufq_init(&np->xn_rx_batch, INT_MAX);
2053
2054         /* A grant for every tx ring slot */
2055         if (gnttab_alloc_grant_references(NET_TX_RING_SIZE,
2056                                           &np->gref_tx_head) != 0) {
2057                 IPRINTK("#### netfront can't alloc tx grant refs\n");
2058                 err = ENOMEM;
2059                 goto exit;
2060         }
2061         /* A grant for every rx ring slot */
2062         if (gnttab_alloc_grant_references(RX_MAX_TARGET,
2063                                           &np->gref_rx_head) != 0) {
2064                 WPRINTK("#### netfront can't alloc rx grant refs\n");
2065                 gnttab_free_grant_references(np->gref_tx_head);
2066                 err = ENOMEM;
2067                 goto exit;
2068         }
2069         
2070         err = xen_net_read_mac(dev, np->mac);
2071         if (err)
2072                 goto out;
2073         
2074         /* Set up ifnet structure */
2075         ifp = np->xn_ifp = if_alloc(IFT_ETHER);
2076         ifp->if_softc = np;
2077         if_initname(ifp, "xn",  device_get_unit(dev));
2078         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
2079         ifp->if_ioctl = xn_ioctl;
2080         ifp->if_output = ether_output;
2081         ifp->if_start = xn_start;
2082 #ifdef notyet
2083         ifp->if_watchdog = xn_watchdog;
2084 #endif
2085         ifp->if_init = xn_ifinit;
2086         ifp->if_snd.ifq_maxlen = NET_TX_RING_SIZE - 1;
2087         
2088         ifp->if_hwassist = XN_CSUM_FEATURES;
2089         ifp->if_capabilities = IFCAP_HWCSUM;
2090         ifp->if_hw_tsomax = 65536 - (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
2091         ifp->if_hw_tsomaxsegcount = MAX_TX_REQ_FRAGS;
2092         ifp->if_hw_tsomaxsegsize = PAGE_SIZE;
2093         
2094         ether_ifattach(ifp, np->mac);
2095         callout_init(&np->xn_stat_ch, 1);
2096         netfront_carrier_off(np);
2097
2098         return (0);
2099
2100 exit:
2101         gnttab_free_grant_references(np->gref_tx_head);
2102 out:
2103         return (err);
2104 }
2105
2106 /**
2107  * Handle the change of state of the backend to Closing.  We must delete our
2108  * device-layer structures now, to ensure that writes are flushed through to
2109  * the backend.  Once is this done, we can switch to Closed in
2110  * acknowledgement.
2111  */
2112 #if 0
2113 static void
2114 netfront_closing(device_t dev)
2115 {
2116 #if 0
2117         struct netfront_info *info = dev->dev_driver_data;
2118
2119         DPRINTK("netfront_closing: %s removed\n", dev->nodename);
2120
2121         close_netdev(info);
2122 #endif
2123         xenbus_switch_state(dev, XenbusStateClosed);
2124 }
2125 #endif
2126
2127 static int
2128 netfront_detach(device_t dev)
2129 {
2130         struct netfront_info *info = device_get_softc(dev);
2131
2132         DPRINTK("%s\n", xenbus_get_node(dev));
2133
2134         netif_free(info);
2135
2136         return 0;
2137 }
2138
2139 static void
2140 netif_free(struct netfront_info *info)
2141 {
2142         XN_LOCK(info);
2143         xn_stop(info);
2144         XN_UNLOCK(info);
2145         callout_drain(&info->xn_stat_ch);
2146         netif_disconnect_backend(info);
2147         if (info->xn_ifp != NULL) {
2148                 ether_ifdetach(info->xn_ifp);
2149                 if_free(info->xn_ifp);
2150                 info->xn_ifp = NULL;
2151         }
2152         ifmedia_removeall(&info->sc_media);
2153 }
2154
2155 static void
2156 netif_disconnect_backend(struct netfront_info *info)
2157 {
2158         XN_RX_LOCK(info);
2159         XN_TX_LOCK(info);
2160         netfront_carrier_off(info);
2161         XN_TX_UNLOCK(info);
2162         XN_RX_UNLOCK(info);
2163
2164         free_ring(&info->tx_ring_ref, &info->tx.sring);
2165         free_ring(&info->rx_ring_ref, &info->rx.sring);
2166
2167         xen_intr_unbind(&info->xen_intr_handle);
2168 }
2169
2170 static void
2171 free_ring(int *ref, void *ring_ptr_ref)
2172 {
2173         void **ring_ptr_ptr = ring_ptr_ref;
2174
2175         if (*ref != GRANT_REF_INVALID) {
2176                 /* This API frees the associated storage. */
2177                 gnttab_end_foreign_access(*ref, *ring_ptr_ptr);
2178                 *ref = GRANT_REF_INVALID;
2179         }
2180         *ring_ptr_ptr = NULL;
2181 }
2182
2183 static int
2184 xn_ifmedia_upd(struct ifnet *ifp)
2185 {
2186         return (0);
2187 }
2188
2189 static void
2190 xn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2191 {
2192         ifmr->ifm_status = IFM_AVALID|IFM_ACTIVE;
2193         ifmr->ifm_active = IFM_ETHER|IFM_MANUAL;
2194 }
2195
2196 /* ** Driver registration ** */
2197 static device_method_t netfront_methods[] = { 
2198         /* Device interface */ 
2199         DEVMETHOD(device_probe,         netfront_probe), 
2200         DEVMETHOD(device_attach,        netfront_attach), 
2201         DEVMETHOD(device_detach,        netfront_detach), 
2202         DEVMETHOD(device_shutdown,      bus_generic_shutdown), 
2203         DEVMETHOD(device_suspend,       netfront_suspend), 
2204         DEVMETHOD(device_resume,        netfront_resume), 
2205  
2206         /* Xenbus interface */
2207         DEVMETHOD(xenbus_otherend_changed, netfront_backend_changed),
2208
2209         DEVMETHOD_END
2210 }; 
2211
2212 static driver_t netfront_driver = { 
2213         "xn", 
2214         netfront_methods, 
2215         sizeof(struct netfront_info),                      
2216 }; 
2217 devclass_t netfront_devclass; 
2218  
2219 DRIVER_MODULE(xe, xenbusb_front, netfront_driver, netfront_devclass, NULL,
2220     NULL);