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