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