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