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