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