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