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