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