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