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