xref: /freebsd/sys/dev/xen/netback/netback.c (revision a18eacbefdfa1085ca3db829e86ece78cd416493)
1 /*-
2  * Copyright (c) 2009-2011 Spectra Logic Corporation
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  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    substantially similar to the "NO WARRANTY" disclaimer below
13  *    ("Disclaimer") and any redistribution must be conditioned upon
14  *    including a substantially similar Disclaimer requirement for further
15  *    binary redistribution.
16  *
17  * NO WARRANTY
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
27  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGES.
29  *
30  * Authors: Justin T. Gibbs     (Spectra Logic Corporation)
31  *          Alan Somers         (Spectra Logic Corporation)
32  *          John Suykerbuyk     (Spectra Logic Corporation)
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 /**
39  * \file netback.c
40  *
41  * \brief Device driver supporting the vending of network access
42  * 	  from this FreeBSD domain to other domains.
43  */
44 #include "opt_inet.h"
45 #include "opt_inet6.h"
46 #include "opt_global.h"
47 
48 #include "opt_sctp.h"
49 
50 #include <sys/param.h>
51 #include <sys/kernel.h>
52 
53 #include <sys/bus.h>
54 #include <sys/module.h>
55 #include <sys/rman.h>
56 #include <sys/socket.h>
57 #include <sys/sockio.h>
58 #include <sys/sysctl.h>
59 
60 #include <net/if.h>
61 #include <net/if_var.h>
62 #include <net/if_arp.h>
63 #include <net/ethernet.h>
64 #include <net/if_dl.h>
65 #include <net/if_media.h>
66 #include <net/if_types.h>
67 
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #include <netinet/if_ether.h>
71 #if __FreeBSD_version >= 700000
72 #include <netinet/tcp.h>
73 #endif
74 #include <netinet/ip_icmp.h>
75 #include <netinet/udp.h>
76 #include <machine/in_cksum.h>
77 
78 #include <vm/vm.h>
79 #include <vm/pmap.h>
80 #include <vm/vm_extern.h>
81 #include <vm/vm_kern.h>
82 
83 #include <machine/_inttypes.h>
84 
85 #include <xen/xen-os.h>
86 #include <xen/hypervisor.h>
87 #include <xen/xen_intr.h>
88 #include <xen/interface/io/netif.h>
89 #include <xen/xenbus/xenbusvar.h>
90 
91 #include <machine/xen/xenvar.h>
92 
93 /*--------------------------- Compile-time Tunables --------------------------*/
94 
95 /*---------------------------------- Macros ----------------------------------*/
96 /**
97  * Custom malloc type for all driver allocations.
98  */
99 static MALLOC_DEFINE(M_XENNETBACK, "xnb", "Xen Net Back Driver Data");
100 
101 #define	XNB_SG	1	/* netback driver supports feature-sg */
102 #define	XNB_GSO_TCPV4 1	/* netback driver supports feature-gso-tcpv4 */
103 #define	XNB_RX_COPY 1	/* netback driver supports feature-rx-copy */
104 #define	XNB_RX_FLIP 0	/* netback driver does not support feature-rx-flip */
105 
106 #undef XNB_DEBUG
107 #define	XNB_DEBUG /* hardcode on during development */
108 
109 #ifdef XNB_DEBUG
110 #define	DPRINTF(fmt, args...) \
111 	printf("xnb(%s:%d): " fmt, __FUNCTION__, __LINE__, ##args)
112 #else
113 #define	DPRINTF(fmt, args...) do {} while (0)
114 #endif
115 
116 /* Default length for stack-allocated grant tables */
117 #define	GNTTAB_LEN	(64)
118 
119 /* Features supported by all backends.  TSO and LRO can be negotiated */
120 #define	XNB_CSUM_FEATURES	(CSUM_TCP | CSUM_UDP)
121 
122 #define	NET_TX_RING_SIZE __RING_SIZE((netif_tx_sring_t *)0, PAGE_SIZE)
123 #define	NET_RX_RING_SIZE __RING_SIZE((netif_rx_sring_t *)0, PAGE_SIZE)
124 
125 /**
126  * Two argument version of the standard macro.  Second argument is a tentative
127  * value of req_cons
128  */
129 #define	RING_HAS_UNCONSUMED_REQUESTS_2(_r, cons) ({                     \
130 	unsigned int req = (_r)->sring->req_prod - cons;          	\
131 	unsigned int rsp = RING_SIZE(_r) -                              \
132 	(cons - (_r)->rsp_prod_pvt);                          		\
133 	req < rsp ? req : rsp;                                          \
134 })
135 
136 #define	virt_to_mfn(x) (vtomach(x) >> PAGE_SHIFT)
137 #define	virt_to_offset(x) ((x) & (PAGE_SIZE - 1))
138 
139 /**
140  * Predefined array type of grant table copy descriptors.  Used to pass around
141  * statically allocated memory structures.
142  */
143 typedef struct gnttab_copy gnttab_copy_table[GNTTAB_LEN];
144 
145 /*--------------------------- Forward Declarations ---------------------------*/
146 struct xnb_softc;
147 struct xnb_pkt;
148 
149 static void	xnb_attach_failed(struct xnb_softc *xnb,
150 				  int err, const char *fmt, ...)
151 				  __printflike(3,4);
152 static int	xnb_shutdown(struct xnb_softc *xnb);
153 static int	create_netdev(device_t dev);
154 static int	xnb_detach(device_t dev);
155 static int	xen_net_read_mac(device_t dev, uint8_t mac[]);
156 static int	xnb_ifmedia_upd(struct ifnet *ifp);
157 static void	xnb_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr);
158 static void 	xnb_intr(void *arg);
159 static int	xnb_send(netif_rx_back_ring_t *rxb, domid_t otherend,
160 			 const struct mbuf *mbufc, gnttab_copy_table gnttab);
161 static int	xnb_recv(netif_tx_back_ring_t *txb, domid_t otherend,
162 			 struct mbuf **mbufc, struct ifnet *ifnet,
163 			 gnttab_copy_table gnttab);
164 static int	xnb_ring2pkt(struct xnb_pkt *pkt,
165 			     const netif_tx_back_ring_t *tx_ring,
166 			     RING_IDX start);
167 static void	xnb_txpkt2rsp(const struct xnb_pkt *pkt,
168 			      netif_tx_back_ring_t *ring, int error);
169 static struct mbuf *xnb_pkt2mbufc(const struct xnb_pkt *pkt, struct ifnet *ifp);
170 static int	xnb_txpkt2gnttab(const struct xnb_pkt *pkt,
171 				 const struct mbuf *mbufc,
172 				 gnttab_copy_table gnttab,
173 				 const netif_tx_back_ring_t *txb,
174 				 domid_t otherend_id);
175 static void	xnb_update_mbufc(struct mbuf *mbufc,
176 				 const gnttab_copy_table gnttab, int n_entries);
177 static int	xnb_mbufc2pkt(const struct mbuf *mbufc,
178 			      struct xnb_pkt *pkt,
179 			      RING_IDX start, int space);
180 static int	xnb_rxpkt2gnttab(const struct xnb_pkt *pkt,
181 				 const struct mbuf *mbufc,
182 				 gnttab_copy_table gnttab,
183 				 const netif_rx_back_ring_t *rxb,
184 				 domid_t otherend_id);
185 static int	xnb_rxpkt2rsp(const struct xnb_pkt *pkt,
186 			      const gnttab_copy_table gnttab, int n_entries,
187 			      netif_rx_back_ring_t *ring);
188 static void	xnb_stop(struct xnb_softc*);
189 static int	xnb_ioctl(struct ifnet*, u_long, caddr_t);
190 static void	xnb_start_locked(struct ifnet*);
191 static void	xnb_start(struct ifnet*);
192 static void	xnb_ifinit_locked(struct xnb_softc*);
193 static void	xnb_ifinit(void*);
194 #ifdef XNB_DEBUG
195 static int	xnb_unit_test_main(SYSCTL_HANDLER_ARGS);
196 static int	xnb_dump_rings(SYSCTL_HANDLER_ARGS);
197 #endif
198 #if defined(INET) || defined(INET6)
199 static void	xnb_add_mbuf_cksum(struct mbuf *mbufc);
200 #endif
201 /*------------------------------ Data Structures -----------------------------*/
202 
203 
204 /**
205  * Representation of a xennet packet.  Simplified version of a packet as
206  * stored in the Xen tx ring.  Applicable to both RX and TX packets
207  */
208 struct xnb_pkt{
209 	/**
210 	 * Array index of the first data-bearing (eg, not extra info) entry
211 	 * for this packet
212 	 */
213 	RING_IDX	car;
214 
215 	/**
216 	 * Array index of the second data-bearing entry for this packet.
217 	 * Invalid if the packet has only one data-bearing entry.  If the
218 	 * packet has more than two data-bearing entries, then the second
219 	 * through the last will be sequential modulo the ring size
220 	 */
221 	RING_IDX	cdr;
222 
223 	/**
224 	 * Optional extra info.  Only valid if flags contains
225 	 * NETTXF_extra_info.  Note that extra.type will always be
226 	 * XEN_NETIF_EXTRA_TYPE_GSO.  Currently, no known netfront or netback
227 	 * driver will ever set XEN_NETIF_EXTRA_TYPE_MCAST_*
228 	 */
229 	netif_extra_info_t extra;
230 
231 	/** Size of entire packet in bytes.       */
232 	uint16_t	size;
233 
234 	/** The size of the first entry's data in bytes */
235 	uint16_t	car_size;
236 
237 	/**
238 	 * Either NETTXF_ or NETRXF_ flags.  Note that the flag values are
239 	 * not the same for TX and RX packets
240 	 */
241 	uint16_t	flags;
242 
243 	/**
244 	 * The number of valid data-bearing entries (either netif_tx_request's
245 	 * or netif_rx_response's) in the packet.  If this is 0, it means the
246 	 * entire packet is invalid.
247 	 */
248 	uint16_t	list_len;
249 
250 	/** There was an error processing the packet */
251 	uint8_t		error;
252 };
253 
254 /** xnb_pkt method: initialize it */
255 static inline void
256 xnb_pkt_initialize(struct xnb_pkt *pxnb)
257 {
258 	bzero(pxnb, sizeof(*pxnb));
259 }
260 
261 /** xnb_pkt method: mark the packet as valid */
262 static inline void
263 xnb_pkt_validate(struct xnb_pkt *pxnb)
264 {
265 	pxnb->error = 0;
266 };
267 
268 /** xnb_pkt method: mark the packet as invalid */
269 static inline void
270 xnb_pkt_invalidate(struct xnb_pkt *pxnb)
271 {
272 	pxnb->error = 1;
273 };
274 
275 /** xnb_pkt method: Check whether the packet is valid */
276 static inline int
277 xnb_pkt_is_valid(const struct xnb_pkt *pxnb)
278 {
279 	return (! pxnb->error);
280 }
281 
282 #ifdef XNB_DEBUG
283 /** xnb_pkt method: print the packet's contents in human-readable format*/
284 static void __unused
285 xnb_dump_pkt(const struct xnb_pkt *pkt) {
286 	if (pkt == NULL) {
287 	  DPRINTF("Was passed a null pointer.\n");
288 	  return;
289 	}
290 	DPRINTF("pkt address= %p\n", pkt);
291 	DPRINTF("pkt->size=%d\n", pkt->size);
292 	DPRINTF("pkt->car_size=%d\n", pkt->car_size);
293 	DPRINTF("pkt->flags=0x%04x\n", pkt->flags);
294 	DPRINTF("pkt->list_len=%d\n", pkt->list_len);
295 	/* DPRINTF("pkt->extra");	TODO */
296 	DPRINTF("pkt->car=%d\n", pkt->car);
297 	DPRINTF("pkt->cdr=%d\n", pkt->cdr);
298 	DPRINTF("pkt->error=%d\n", pkt->error);
299 }
300 #endif /* XNB_DEBUG */
301 
302 static void
303 xnb_dump_txreq(RING_IDX idx, const struct netif_tx_request *txreq)
304 {
305 	if (txreq != NULL) {
306 		DPRINTF("netif_tx_request index =%u\n", idx);
307 		DPRINTF("netif_tx_request.gref  =%u\n", txreq->gref);
308 		DPRINTF("netif_tx_request.offset=%hu\n", txreq->offset);
309 		DPRINTF("netif_tx_request.flags =%hu\n", txreq->flags);
310 		DPRINTF("netif_tx_request.id    =%hu\n", txreq->id);
311 		DPRINTF("netif_tx_request.size  =%hu\n", txreq->size);
312 	}
313 }
314 
315 
316 /**
317  * \brief Configuration data for a shared memory request ring
318  *        used to communicate with the front-end client of this
319  *        this driver.
320  */
321 struct xnb_ring_config {
322 	/**
323 	 * Runtime structures for ring access.  Unfortunately, TX and RX rings
324 	 * use different data structures, and that cannot be changed since it
325 	 * is part of the interdomain protocol.
326 	 */
327 	union{
328 		netif_rx_back_ring_t	  rx_ring;
329 		netif_tx_back_ring_t	  tx_ring;
330 	} back_ring;
331 
332 	/**
333 	 * The device bus address returned by the hypervisor when
334 	 * mapping the ring and required to unmap it when a connection
335 	 * is torn down.
336 	 */
337 	uint64_t	bus_addr;
338 
339 	/** The pseudo-physical address where ring memory is mapped.*/
340 	uint64_t	gnt_addr;
341 
342 	/** KVA address where ring memory is mapped. */
343 	vm_offset_t	va;
344 
345 	/**
346 	 * Grant table handles, one per-ring page, returned by the
347 	 * hyperpervisor upon mapping of the ring and required to
348 	 * unmap it when a connection is torn down.
349 	 */
350 	grant_handle_t	handle;
351 
352 	/** The number of ring pages mapped for the current connection. */
353 	unsigned	ring_pages;
354 
355 	/**
356 	 * The grant references, one per-ring page, supplied by the
357 	 * front-end, allowing us to reference the ring pages in the
358 	 * front-end's domain and to map these pages into our own domain.
359 	 */
360 	grant_ref_t	ring_ref;
361 };
362 
363 /**
364  * Per-instance connection state flags.
365  */
366 typedef enum
367 {
368 	/** Communication with the front-end has been established. */
369 	XNBF_RING_CONNECTED    = 0x01,
370 
371 	/**
372 	 * Front-end requests exist in the ring and are waiting for
373 	 * xnb_xen_req objects to free up.
374 	 */
375 	XNBF_RESOURCE_SHORTAGE = 0x02,
376 
377 	/** Connection teardown has started. */
378 	XNBF_SHUTDOWN          = 0x04,
379 
380 	/** A thread is already performing shutdown processing. */
381 	XNBF_IN_SHUTDOWN       = 0x08
382 } xnb_flag_t;
383 
384 /**
385  * Types of rings.  Used for array indices and to identify a ring's control
386  * data structure type
387  */
388 typedef enum{
389 	XNB_RING_TYPE_TX = 0,	/* ID of TX rings, used for array indices */
390 	XNB_RING_TYPE_RX = 1,	/* ID of RX rings, used for array indices */
391 	XNB_NUM_RING_TYPES
392 } xnb_ring_type_t;
393 
394 /**
395  * Per-instance configuration data.
396  */
397 struct xnb_softc {
398 	/** NewBus device corresponding to this instance. */
399 	device_t		dev;
400 
401 	/* Media related fields */
402 
403 	/** Generic network media state */
404 	struct ifmedia		sc_media;
405 
406 	/** Media carrier info */
407 	struct ifnet 		*xnb_ifp;
408 
409 	/** Our own private carrier state */
410 	unsigned carrier;
411 
412 	/** Device MAC Address */
413 	uint8_t			mac[ETHER_ADDR_LEN];
414 
415 	/* Xen related fields */
416 
417 	/**
418 	 * \brief The netif protocol abi in effect.
419 	 *
420 	 * There are situations where the back and front ends can
421 	 * have a different, native abi (e.g. intel x86_64 and
422 	 * 32bit x86 domains on the same machine).  The back-end
423 	 * always accomodates the front-end's native abi.  That
424 	 * value is pulled from the XenStore and recorded here.
425 	 */
426 	int			abi;
427 
428 	/**
429 	 * Name of the bridge to which this VIF is connected, if any
430 	 * This field is dynamically allocated by xenbus and must be free()ed
431 	 * when no longer needed
432 	 */
433 	char			*bridge;
434 
435 	/** The interrupt driven even channel used to signal ring events. */
436 	evtchn_port_t		evtchn;
437 
438 	/** Xen device handle.*/
439 	long 			handle;
440 
441 	/** Handle to the communication ring event channel. */
442 	xen_intr_handle_t	xen_intr_handle;
443 
444 	/**
445 	 * \brief Cached value of the front-end's domain id.
446 	 *
447 	 * This value is used at once for each mapped page in
448 	 * a transaction.  We cache it to avoid incuring the
449 	 * cost of an ivar access every time this is needed.
450 	 */
451 	domid_t			otherend_id;
452 
453 	/**
454 	 * Undocumented frontend feature.  Has something to do with
455 	 * scatter/gather IO
456 	 */
457 	uint8_t			can_sg;
458 	/** Undocumented frontend feature */
459 	uint8_t			gso;
460 	/** Undocumented frontend feature */
461 	uint8_t			gso_prefix;
462 	/** Can checksum TCP/UDP over IPv4 */
463 	uint8_t			ip_csum;
464 
465 	/* Implementation related fields */
466 	/**
467 	 * Preallocated grant table copy descriptor for RX operations.
468 	 * Access must be protected by rx_lock
469 	 */
470 	gnttab_copy_table	rx_gnttab;
471 
472 	/**
473 	 * Preallocated grant table copy descriptor for TX operations.
474 	 * Access must be protected by tx_lock
475 	 */
476 	gnttab_copy_table	tx_gnttab;
477 
478 #ifdef XENHVM
479 	/**
480 	 * Resource representing allocated physical address space
481 	 * associated with our per-instance kva region.
482 	 */
483 	struct resource		*pseudo_phys_res;
484 
485 	/** Resource id for allocated physical address space. */
486 	int			pseudo_phys_res_id;
487 #endif
488 
489 	/** Ring mapping and interrupt configuration data. */
490 	struct xnb_ring_config	ring_configs[XNB_NUM_RING_TYPES];
491 
492 	/**
493 	 * Global pool of kva used for mapping remote domain ring
494 	 * and I/O transaction data.
495 	 */
496 	vm_offset_t		kva;
497 
498 	/** Psuedo-physical address corresponding to kva. */
499 	uint64_t		gnt_base_addr;
500 
501 	/** Various configuration and state bit flags. */
502 	xnb_flag_t		flags;
503 
504 	/** Mutex protecting per-instance data in the receive path. */
505 	struct mtx		rx_lock;
506 
507 	/** Mutex protecting per-instance data in the softc structure. */
508 	struct mtx		sc_lock;
509 
510 	/** Mutex protecting per-instance data in the transmit path. */
511 	struct mtx		tx_lock;
512 
513 	/** The size of the global kva pool. */
514 	int			kva_size;
515 };
516 
517 /*---------------------------- Debugging functions ---------------------------*/
518 #ifdef XNB_DEBUG
519 static void __unused
520 xnb_dump_gnttab_copy(const struct gnttab_copy *entry)
521 {
522 	if (entry == NULL) {
523 		printf("NULL grant table pointer\n");
524 		return;
525 	}
526 
527 	if (entry->flags & GNTCOPY_dest_gref)
528 		printf("gnttab dest ref=\t%u\n", entry->dest.u.ref);
529 	else
530 		printf("gnttab dest gmfn=\t%lu\n", entry->dest.u.gmfn);
531 	printf("gnttab dest offset=\t%hu\n", entry->dest.offset);
532 	printf("gnttab dest domid=\t%hu\n", entry->dest.domid);
533 	if (entry->flags & GNTCOPY_source_gref)
534 		printf("gnttab source ref=\t%u\n", entry->source.u.ref);
535 	else
536 		printf("gnttab source gmfn=\t%lu\n", entry->source.u.gmfn);
537 	printf("gnttab source offset=\t%hu\n", entry->source.offset);
538 	printf("gnttab source domid=\t%hu\n", entry->source.domid);
539 	printf("gnttab len=\t%hu\n", entry->len);
540 	printf("gnttab flags=\t%hu\n", entry->flags);
541 	printf("gnttab status=\t%hd\n", entry->status);
542 }
543 
544 static int
545 xnb_dump_rings(SYSCTL_HANDLER_ARGS)
546 {
547 	static char results[720];
548 	struct xnb_softc const* xnb = (struct xnb_softc*)arg1;
549 	netif_rx_back_ring_t const* rxb =
550 		&xnb->ring_configs[XNB_RING_TYPE_RX].back_ring.rx_ring;
551 	netif_tx_back_ring_t const* txb =
552 		&xnb->ring_configs[XNB_RING_TYPE_TX].back_ring.tx_ring;
553 
554 	/* empty the result strings */
555 	results[0] = 0;
556 
557 	if ( !txb || !txb->sring || !rxb || !rxb->sring )
558 		return (SYSCTL_OUT(req, results, strnlen(results, 720)));
559 
560 	snprintf(results, 720,
561 	    "\n\t%35s %18s\n"	/* TX, RX */
562 	    "\t%16s %18d %18d\n"	/* req_cons */
563 	    "\t%16s %18d %18d\n"	/* nr_ents */
564 	    "\t%16s %18d %18d\n"	/* rsp_prod_pvt */
565 	    "\t%16s %18p %18p\n"	/* sring */
566 	    "\t%16s %18d %18d\n"	/* req_prod */
567 	    "\t%16s %18d %18d\n"	/* req_event */
568 	    "\t%16s %18d %18d\n"	/* rsp_prod */
569 	    "\t%16s %18d %18d\n",	/* rsp_event */
570 	    "TX", "RX",
571 	    "req_cons", txb->req_cons, rxb->req_cons,
572 	    "nr_ents", txb->nr_ents, rxb->nr_ents,
573 	    "rsp_prod_pvt", txb->rsp_prod_pvt, rxb->rsp_prod_pvt,
574 	    "sring", txb->sring, rxb->sring,
575 	    "sring->req_prod", txb->sring->req_prod, rxb->sring->req_prod,
576 	    "sring->req_event", txb->sring->req_event, rxb->sring->req_event,
577 	    "sring->rsp_prod", txb->sring->rsp_prod, rxb->sring->rsp_prod,
578 	    "sring->rsp_event", txb->sring->rsp_event, rxb->sring->rsp_event);
579 
580 	return (SYSCTL_OUT(req, results, strnlen(results, 720)));
581 }
582 
583 static void __unused
584 xnb_dump_mbuf(const struct mbuf *m)
585 {
586 	int len;
587 	uint8_t *d;
588 	if (m == NULL)
589 		return;
590 
591 	printf("xnb_dump_mbuf:\n");
592 	if (m->m_flags & M_PKTHDR) {
593 		printf("    flowid=%10d, csum_flags=%#8x, csum_data=%#8x, "
594 		       "tso_segsz=%5hd\n",
595 		       m->m_pkthdr.flowid, (int)m->m_pkthdr.csum_flags,
596 		       m->m_pkthdr.csum_data, m->m_pkthdr.tso_segsz);
597 		printf("    rcvif=%16p,  len=%19d\n",
598 		       m->m_pkthdr.rcvif, m->m_pkthdr.len);
599 	}
600 	printf("    m_next=%16p, m_nextpk=%16p, m_data=%16p\n",
601 	       m->m_next, m->m_nextpkt, m->m_data);
602 	printf("    m_len=%17d, m_flags=%#15x, m_type=%18u\n",
603 	       m->m_len, m->m_flags, m->m_type);
604 
605 	len = m->m_len;
606 	d = mtod(m, uint8_t*);
607 	while (len > 0) {
608 		int i;
609 		printf("                ");
610 		for (i = 0; (i < 16) && (len > 0); i++, len--) {
611 			printf("%02hhx ", *(d++));
612 		}
613 		printf("\n");
614 	}
615 }
616 #endif /* XNB_DEBUG */
617 
618 /*------------------------ Inter-Domain Communication ------------------------*/
619 /**
620  * Free dynamically allocated KVA or pseudo-physical address allocations.
621  *
622  * \param xnb  Per-instance xnb configuration structure.
623  */
624 static void
625 xnb_free_communication_mem(struct xnb_softc *xnb)
626 {
627 	if (xnb->kva != 0) {
628 #ifndef XENHVM
629 		kva_free(xnb->kva, xnb->kva_size);
630 #else
631 		if (xnb->pseudo_phys_res != NULL) {
632 			bus_release_resource(xnb->dev, SYS_RES_MEMORY,
633 			    xnb->pseudo_phys_res_id,
634 			    xnb->pseudo_phys_res);
635 			xnb->pseudo_phys_res = NULL;
636 		}
637 #endif /* XENHVM */
638 	}
639 	xnb->kva = 0;
640 	xnb->gnt_base_addr = 0;
641 }
642 
643 /**
644  * Cleanup all inter-domain communication mechanisms.
645  *
646  * \param xnb  Per-instance xnb configuration structure.
647  */
648 static int
649 xnb_disconnect(struct xnb_softc *xnb)
650 {
651 	struct gnttab_unmap_grant_ref gnts[XNB_NUM_RING_TYPES];
652 	int error;
653 	int i;
654 
655 	xen_intr_unbind(xnb->xen_intr_handle);
656 
657 	/*
658 	 * We may still have another thread currently processing requests.  We
659 	 * must acquire the rx and tx locks to make sure those threads are done,
660 	 * but we can release those locks as soon as we acquire them, because no
661 	 * more interrupts will be arriving.
662 	 */
663 	mtx_lock(&xnb->tx_lock);
664 	mtx_unlock(&xnb->tx_lock);
665 	mtx_lock(&xnb->rx_lock);
666 	mtx_unlock(&xnb->rx_lock);
667 
668 	/* Free malloc'd softc member variables */
669 	if (xnb->bridge != NULL)
670 		free(xnb->bridge, M_XENSTORE);
671 
672 	/* All request processing has stopped, so unmap the rings */
673 	for (i=0; i < XNB_NUM_RING_TYPES; i++) {
674 		gnts[i].host_addr = xnb->ring_configs[i].gnt_addr;
675 		gnts[i].dev_bus_addr = xnb->ring_configs[i].bus_addr;
676 		gnts[i].handle = xnb->ring_configs[i].handle;
677 	}
678 	error = HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref, gnts,
679 					  XNB_NUM_RING_TYPES);
680 	KASSERT(error == 0, ("Grant table unmap op failed (%d)", error));
681 
682 	xnb_free_communication_mem(xnb);
683 	/*
684 	 * Zero the ring config structs because the pointers, handles, and
685 	 * grant refs contained therein are no longer valid.
686 	 */
687 	bzero(&xnb->ring_configs[XNB_RING_TYPE_TX],
688 	    sizeof(struct xnb_ring_config));
689 	bzero(&xnb->ring_configs[XNB_RING_TYPE_RX],
690 	    sizeof(struct xnb_ring_config));
691 
692 	xnb->flags &= ~XNBF_RING_CONNECTED;
693 	return (0);
694 }
695 
696 /**
697  * Map a single shared memory ring into domain local address space and
698  * initialize its control structure
699  *
700  * \param xnb	Per-instance xnb configuration structure
701  * \param ring_type	Array index of this ring in the xnb's array of rings
702  * \return 	An errno
703  */
704 static int
705 xnb_connect_ring(struct xnb_softc *xnb, xnb_ring_type_t ring_type)
706 {
707 	struct gnttab_map_grant_ref gnt;
708 	struct xnb_ring_config *ring = &xnb->ring_configs[ring_type];
709 	int error;
710 
711 	/* TX ring type = 0, RX =1 */
712 	ring->va = xnb->kva + ring_type * PAGE_SIZE;
713 	ring->gnt_addr = xnb->gnt_base_addr + ring_type * PAGE_SIZE;
714 
715 	gnt.host_addr = ring->gnt_addr;
716 	gnt.flags     = GNTMAP_host_map;
717 	gnt.ref       = ring->ring_ref;
718 	gnt.dom       = xnb->otherend_id;
719 
720 	error = HYPERVISOR_grant_table_op(GNTTABOP_map_grant_ref, &gnt, 1);
721 	if (error != 0)
722 		panic("netback: Ring page grant table op failed (%d)", error);
723 
724 	if (gnt.status != 0) {
725 		ring->va = 0;
726 		error = EACCES;
727 		xenbus_dev_fatal(xnb->dev, error,
728 				 "Ring shared page mapping failed. "
729 				 "Status %d.", gnt.status);
730 	} else {
731 		ring->handle = gnt.handle;
732 		ring->bus_addr = gnt.dev_bus_addr;
733 
734 		if (ring_type == XNB_RING_TYPE_TX) {
735 			BACK_RING_INIT(&ring->back_ring.tx_ring,
736 			    (netif_tx_sring_t*)ring->va,
737 			    ring->ring_pages * PAGE_SIZE);
738 		} else if (ring_type == XNB_RING_TYPE_RX) {
739 			BACK_RING_INIT(&ring->back_ring.rx_ring,
740 			    (netif_rx_sring_t*)ring->va,
741 			    ring->ring_pages * PAGE_SIZE);
742 		} else {
743 			xenbus_dev_fatal(xnb->dev, error,
744 				 "Unknown ring type %d", ring_type);
745 		}
746 	}
747 
748 	return error;
749 }
750 
751 /**
752  * Setup the shared memory rings and bind an interrupt to the event channel
753  * used to notify us of ring changes.
754  *
755  * \param xnb  Per-instance xnb configuration structure.
756  */
757 static int
758 xnb_connect_comms(struct xnb_softc *xnb)
759 {
760 	int	error;
761 	xnb_ring_type_t i;
762 
763 	if ((xnb->flags & XNBF_RING_CONNECTED) != 0)
764 		return (0);
765 
766 	/*
767 	 * Kva for our rings are at the tail of the region of kva allocated
768 	 * by xnb_alloc_communication_mem().
769 	 */
770 	for (i=0; i < XNB_NUM_RING_TYPES; i++) {
771 		error = xnb_connect_ring(xnb, i);
772 		if (error != 0)
773 	  		return error;
774 	}
775 
776 	xnb->flags |= XNBF_RING_CONNECTED;
777 
778 	error = xen_intr_bind_remote_port(xnb->dev,
779 					  xnb->otherend_id,
780 					  xnb->evtchn,
781 					  /*filter*/NULL,
782 					  xnb_intr, /*arg*/xnb,
783 					  INTR_TYPE_BIO | INTR_MPSAFE,
784 					  &xnb->xen_intr_handle);
785 	if (error != 0) {
786 		(void)xnb_disconnect(xnb);
787 		xenbus_dev_fatal(xnb->dev, error, "binding event channel");
788 		return (error);
789 	}
790 
791 	DPRINTF("rings connected!\n");
792 
793 	return (0);
794 }
795 
796 /**
797  * Size KVA and pseudo-physical address allocations based on negotiated
798  * values for the size and number of I/O requests, and the size of our
799  * communication ring.
800  *
801  * \param xnb  Per-instance xnb configuration structure.
802  *
803  * These address spaces are used to dynamically map pages in the
804  * front-end's domain into our own.
805  */
806 static int
807 xnb_alloc_communication_mem(struct xnb_softc *xnb)
808 {
809 	xnb_ring_type_t i;
810 
811 	xnb->kva_size = 0;
812 	for (i=0; i < XNB_NUM_RING_TYPES; i++) {
813 		xnb->kva_size += xnb->ring_configs[i].ring_pages * PAGE_SIZE;
814 	}
815 #ifndef XENHVM
816 	xnb->kva = kva_alloc(xnb->kva_size);
817 	if (xnb->kva == 0)
818 		return (ENOMEM);
819 	xnb->gnt_base_addr = xnb->kva;
820 #else /* defined XENHVM */
821 	/*
822 	 * Reserve a range of pseudo physical memory that we can map
823 	 * into kva.  These pages will only be backed by machine
824 	 * pages ("real memory") during the lifetime of front-end requests
825 	 * via grant table operations.  We will map the netif tx and rx rings
826 	 * into this space.
827 	 */
828 	xnb->pseudo_phys_res_id = 0;
829 	xnb->pseudo_phys_res = bus_alloc_resource(xnb->dev, SYS_RES_MEMORY,
830 						  &xnb->pseudo_phys_res_id,
831 						  0, ~0, xnb->kva_size,
832 						  RF_ACTIVE);
833 	if (xnb->pseudo_phys_res == NULL) {
834 		xnb->kva = 0;
835 		return (ENOMEM);
836 	}
837 	xnb->kva = (vm_offset_t)rman_get_virtual(xnb->pseudo_phys_res);
838 	xnb->gnt_base_addr = rman_get_start(xnb->pseudo_phys_res);
839 #endif /* !defined XENHVM */
840 	return (0);
841 }
842 
843 /**
844  * Collect information from the XenStore related to our device and its frontend
845  *
846  * \param xnb  Per-instance xnb configuration structure.
847  */
848 static int
849 xnb_collect_xenstore_info(struct xnb_softc *xnb)
850 {
851 	/**
852 	 * \todo Linux collects the following info.  We should collect most
853 	 * of this, too:
854 	 * "feature-rx-notify"
855 	 */
856 	const char *otherend_path;
857 	const char *our_path;
858 	int err;
859 	unsigned int rx_copy, bridge_len;
860 	uint8_t no_csum_offload;
861 
862 	otherend_path = xenbus_get_otherend_path(xnb->dev);
863 	our_path = xenbus_get_node(xnb->dev);
864 
865 	/* Collect the critical communication parameters */
866 	err = xs_gather(XST_NIL, otherend_path,
867 	    "tx-ring-ref", "%l" PRIu32,
868 	    	&xnb->ring_configs[XNB_RING_TYPE_TX].ring_ref,
869 	    "rx-ring-ref", "%l" PRIu32,
870 	    	&xnb->ring_configs[XNB_RING_TYPE_RX].ring_ref,
871 	    "event-channel", "%" PRIu32, &xnb->evtchn,
872 	    NULL);
873 	if (err != 0) {
874 		xenbus_dev_fatal(xnb->dev, err,
875 				 "Unable to retrieve ring information from "
876 				 "frontend %s.  Unable to connect.",
877 				 otherend_path);
878 		return (err);
879 	}
880 
881 	/* Collect the handle from xenstore */
882 	err = xs_scanf(XST_NIL, our_path, "handle", NULL, "%li", &xnb->handle);
883 	if (err != 0) {
884 		xenbus_dev_fatal(xnb->dev, err,
885 		    "Error reading handle from frontend %s.  "
886 		    "Unable to connect.", otherend_path);
887 	}
888 
889 	/*
890 	 * Collect the bridgename, if any.  We do not need bridge_len; we just
891 	 * throw it away
892 	 */
893 	err = xs_read(XST_NIL, our_path, "bridge", &bridge_len,
894 		      (void**)&xnb->bridge);
895 	if (err != 0)
896 		xnb->bridge = NULL;
897 
898 	/*
899 	 * Does the frontend request that we use rx copy?  If not, return an
900 	 * error because this driver only supports rx copy.
901 	 */
902 	err = xs_scanf(XST_NIL, otherend_path, "request-rx-copy", NULL,
903 		       "%" PRIu32, &rx_copy);
904 	if (err == ENOENT) {
905 		err = 0;
906 	 	rx_copy = 0;
907 	}
908 	if (err < 0) {
909 		xenbus_dev_fatal(xnb->dev, err, "reading %s/request-rx-copy",
910 				 otherend_path);
911 		return err;
912 	}
913 	/**
914 	 * \todo: figure out the exact meaning of this feature, and when
915 	 * the frontend will set it to true.  It should be set to true
916 	 * at some point
917 	 */
918 /*        if (!rx_copy)*/
919 /*          return EOPNOTSUPP;*/
920 
921 	/** \todo Collect the rx notify feature */
922 
923 	/*  Collect the feature-sg. */
924 	if (xs_scanf(XST_NIL, otherend_path, "feature-sg", NULL,
925 		     "%hhu", &xnb->can_sg) < 0)
926 		xnb->can_sg = 0;
927 
928 	/* Collect remaining frontend features */
929 	if (xs_scanf(XST_NIL, otherend_path, "feature-gso-tcpv4", NULL,
930 		     "%hhu", &xnb->gso) < 0)
931 		xnb->gso = 0;
932 
933 	if (xs_scanf(XST_NIL, otherend_path, "feature-gso-tcpv4-prefix", NULL,
934 		     "%hhu", &xnb->gso_prefix) < 0)
935 		xnb->gso_prefix = 0;
936 
937 	if (xs_scanf(XST_NIL, otherend_path, "feature-no-csum-offload", NULL,
938 		     "%hhu", &no_csum_offload) < 0)
939 		no_csum_offload = 0;
940 	xnb->ip_csum = (no_csum_offload == 0);
941 
942 	return (0);
943 }
944 
945 /**
946  * Supply information about the physical device to the frontend
947  * via XenBus.
948  *
949  * \param xnb  Per-instance xnb configuration structure.
950  */
951 static int
952 xnb_publish_backend_info(struct xnb_softc *xnb)
953 {
954 	struct xs_transaction xst;
955 	const char *our_path;
956 	int error;
957 
958 	our_path = xenbus_get_node(xnb->dev);
959 
960 	do {
961 		error = xs_transaction_start(&xst);
962 		if (error != 0) {
963 			xenbus_dev_fatal(xnb->dev, error,
964 					 "Error publishing backend info "
965 					 "(start transaction)");
966 			break;
967 		}
968 
969 		error = xs_printf(xst, our_path, "feature-sg",
970 				  "%d", XNB_SG);
971 		if (error != 0)
972 			break;
973 
974 		error = xs_printf(xst, our_path, "feature-gso-tcpv4",
975 				  "%d", XNB_GSO_TCPV4);
976 		if (error != 0)
977 			break;
978 
979 		error = xs_printf(xst, our_path, "feature-rx-copy",
980 				  "%d", XNB_RX_COPY);
981 		if (error != 0)
982 			break;
983 
984 		error = xs_printf(xst, our_path, "feature-rx-flip",
985 				  "%d", XNB_RX_FLIP);
986 		if (error != 0)
987 			break;
988 
989 		error = xs_transaction_end(xst, 0);
990 		if (error != 0 && error != EAGAIN) {
991 			xenbus_dev_fatal(xnb->dev, error, "ending transaction");
992 			break;
993 		}
994 
995 	} while (error == EAGAIN);
996 
997 	return (error);
998 }
999 
1000 /**
1001  * Connect to our netfront peer now that it has completed publishing
1002  * its configuration into the XenStore.
1003  *
1004  * \param xnb  Per-instance xnb configuration structure.
1005  */
1006 static void
1007 xnb_connect(struct xnb_softc *xnb)
1008 {
1009 	int	error;
1010 
1011 	if (xenbus_get_state(xnb->dev) == XenbusStateConnected)
1012 		return;
1013 
1014 	if (xnb_collect_xenstore_info(xnb) != 0)
1015 		return;
1016 
1017 	xnb->flags &= ~XNBF_SHUTDOWN;
1018 
1019 	/* Read front end configuration. */
1020 
1021 	/* Allocate resources whose size depends on front-end configuration. */
1022 	error = xnb_alloc_communication_mem(xnb);
1023 	if (error != 0) {
1024 		xenbus_dev_fatal(xnb->dev, error,
1025 				 "Unable to allocate communication memory");
1026 		return;
1027 	}
1028 
1029 	/*
1030 	 * Connect communication channel.
1031 	 */
1032 	error = xnb_connect_comms(xnb);
1033 	if (error != 0) {
1034 		/* Specific errors are reported by xnb_connect_comms(). */
1035 		return;
1036 	}
1037 	xnb->carrier = 1;
1038 
1039 	/* Ready for I/O. */
1040 	xenbus_set_state(xnb->dev, XenbusStateConnected);
1041 }
1042 
1043 /*-------------------------- Device Teardown Support -------------------------*/
1044 /**
1045  * Perform device shutdown functions.
1046  *
1047  * \param xnb  Per-instance xnb configuration structure.
1048  *
1049  * Mark this instance as shutting down, wait for any active requests
1050  * to drain, disconnect from the front-end, and notify any waiters (e.g.
1051  * a thread invoking our detach method) that detach can now proceed.
1052  */
1053 static int
1054 xnb_shutdown(struct xnb_softc *xnb)
1055 {
1056 	/*
1057 	 * Due to the need to drop our mutex during some
1058 	 * xenbus operations, it is possible for two threads
1059 	 * to attempt to close out shutdown processing at
1060 	 * the same time.  Tell the caller that hits this
1061 	 * race to try back later.
1062 	 */
1063 	if ((xnb->flags & XNBF_IN_SHUTDOWN) != 0)
1064 		return (EAGAIN);
1065 
1066 	xnb->flags |= XNBF_SHUTDOWN;
1067 
1068 	xnb->flags |= XNBF_IN_SHUTDOWN;
1069 
1070 	mtx_unlock(&xnb->sc_lock);
1071 	/* Free the network interface */
1072 	xnb->carrier = 0;
1073 	if (xnb->xnb_ifp != NULL) {
1074 		ether_ifdetach(xnb->xnb_ifp);
1075 		if_free(xnb->xnb_ifp);
1076 		xnb->xnb_ifp = NULL;
1077 	}
1078 	mtx_lock(&xnb->sc_lock);
1079 
1080 	xnb_disconnect(xnb);
1081 
1082 	mtx_unlock(&xnb->sc_lock);
1083 	if (xenbus_get_state(xnb->dev) < XenbusStateClosing)
1084 		xenbus_set_state(xnb->dev, XenbusStateClosing);
1085 	mtx_lock(&xnb->sc_lock);
1086 
1087 	xnb->flags &= ~XNBF_IN_SHUTDOWN;
1088 
1089 
1090 	/* Indicate to xnb_detach() that is it safe to proceed. */
1091 	wakeup(xnb);
1092 
1093 	return (0);
1094 }
1095 
1096 /**
1097  * Report an attach time error to the console and Xen, and cleanup
1098  * this instance by forcing immediate detach processing.
1099  *
1100  * \param xnb  Per-instance xnb configuration structure.
1101  * \param err  Errno describing the error.
1102  * \param fmt  Printf style format and arguments
1103  */
1104 static void
1105 xnb_attach_failed(struct xnb_softc *xnb, int err, const char *fmt, ...)
1106 {
1107 	va_list ap;
1108 	va_list ap_hotplug;
1109 
1110 	va_start(ap, fmt);
1111 	va_copy(ap_hotplug, ap);
1112 	xs_vprintf(XST_NIL, xenbus_get_node(xnb->dev),
1113 		  "hotplug-error", fmt, ap_hotplug);
1114 	va_end(ap_hotplug);
1115 	xs_printf(XST_NIL, xenbus_get_node(xnb->dev),
1116 		  "hotplug-status", "error");
1117 
1118 	xenbus_dev_vfatal(xnb->dev, err, fmt, ap);
1119 	va_end(ap);
1120 
1121 	xs_printf(XST_NIL, xenbus_get_node(xnb->dev),
1122 		  "online", "0");
1123 	xnb_detach(xnb->dev);
1124 }
1125 
1126 /*---------------------------- NewBus Entrypoints ----------------------------*/
1127 /**
1128  * Inspect a XenBus device and claim it if is of the appropriate type.
1129  *
1130  * \param dev  NewBus device object representing a candidate XenBus device.
1131  *
1132  * \return  0 for success, errno codes for failure.
1133  */
1134 static int
1135 xnb_probe(device_t dev)
1136 {
1137 	 if (!strcmp(xenbus_get_type(dev), "vif")) {
1138 		DPRINTF("Claiming device %d, %s\n", device_get_unit(dev),
1139 		    devclass_get_name(device_get_devclass(dev)));
1140 		device_set_desc(dev, "Backend Virtual Network Device");
1141 		device_quiet(dev);
1142 		return (0);
1143 	}
1144 	return (ENXIO);
1145 }
1146 
1147 /**
1148  * Setup sysctl variables to control various Network Back parameters.
1149  *
1150  * \param xnb  Xen Net Back softc.
1151  *
1152  */
1153 static void
1154 xnb_setup_sysctl(struct xnb_softc *xnb)
1155 {
1156 	struct sysctl_ctx_list *sysctl_ctx = NULL;
1157 	struct sysctl_oid      *sysctl_tree = NULL;
1158 
1159 	sysctl_ctx = device_get_sysctl_ctx(xnb->dev);
1160 	if (sysctl_ctx == NULL)
1161 		return;
1162 
1163 	sysctl_tree = device_get_sysctl_tree(xnb->dev);
1164 	if (sysctl_tree == NULL)
1165 		return;
1166 
1167 #ifdef XNB_DEBUG
1168 	SYSCTL_ADD_PROC(sysctl_ctx,
1169 			SYSCTL_CHILDREN(sysctl_tree),
1170 			OID_AUTO,
1171 			"unit_test_results",
1172 			CTLTYPE_STRING | CTLFLAG_RD,
1173 			xnb,
1174 			0,
1175 			xnb_unit_test_main,
1176 			"A",
1177 			"Results of builtin unit tests");
1178 
1179 	SYSCTL_ADD_PROC(sysctl_ctx,
1180 			SYSCTL_CHILDREN(sysctl_tree),
1181 			OID_AUTO,
1182 			"dump_rings",
1183 			CTLTYPE_STRING | CTLFLAG_RD,
1184 			xnb,
1185 			0,
1186 			xnb_dump_rings,
1187 			"A",
1188 			"Xennet Back Rings");
1189 #endif /* XNB_DEBUG */
1190 }
1191 
1192 /**
1193  * Create a network device.
1194  * @param handle device handle
1195  */
1196 int
1197 create_netdev(device_t dev)
1198 {
1199 	struct ifnet *ifp;
1200 	struct xnb_softc *xnb;
1201 	int err = 0;
1202 
1203 	xnb = device_get_softc(dev);
1204 	mtx_init(&xnb->sc_lock, "xnb_softc", "xen netback softc lock", MTX_DEF);
1205 	mtx_init(&xnb->tx_lock, "xnb_tx", "xen netback tx lock", MTX_DEF);
1206 	mtx_init(&xnb->rx_lock, "xnb_rx", "xen netback rx lock", MTX_DEF);
1207 
1208 	xnb->dev = dev;
1209 
1210 	ifmedia_init(&xnb->sc_media, 0, xnb_ifmedia_upd, xnb_ifmedia_sts);
1211 	ifmedia_add(&xnb->sc_media, IFM_ETHER|IFM_MANUAL, 0, NULL);
1212 	ifmedia_set(&xnb->sc_media, IFM_ETHER|IFM_MANUAL);
1213 
1214 	err = xen_net_read_mac(dev, xnb->mac);
1215 	if (err == 0) {
1216 		/* Set up ifnet structure */
1217 		ifp = xnb->xnb_ifp = if_alloc(IFT_ETHER);
1218 		ifp->if_softc = xnb;
1219 		if_initname(ifp, "xnb",  device_get_unit(dev));
1220 		ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1221 		ifp->if_ioctl = xnb_ioctl;
1222 		ifp->if_output = ether_output;
1223 		ifp->if_start = xnb_start;
1224 #ifdef notyet
1225 		ifp->if_watchdog = xnb_watchdog;
1226 #endif
1227 		ifp->if_init = xnb_ifinit;
1228 		ifp->if_mtu = ETHERMTU;
1229 		ifp->if_snd.ifq_maxlen = NET_RX_RING_SIZE - 1;
1230 
1231 		ifp->if_hwassist = XNB_CSUM_FEATURES;
1232 		ifp->if_capabilities = IFCAP_HWCSUM;
1233 		ifp->if_capenable = IFCAP_HWCSUM;
1234 
1235 		ether_ifattach(ifp, xnb->mac);
1236 		xnb->carrier = 0;
1237 	}
1238 
1239 	return err;
1240 }
1241 
1242 /**
1243  * Attach to a XenBus device that has been claimed by our probe routine.
1244  *
1245  * \param dev  NewBus device object representing this Xen Net Back instance.
1246  *
1247  * \return  0 for success, errno codes for failure.
1248  */
1249 static int
1250 xnb_attach(device_t dev)
1251 {
1252 	struct xnb_softc *xnb;
1253 	int	error;
1254 	xnb_ring_type_t	i;
1255 
1256 	error = create_netdev(dev);
1257 	if (error != 0) {
1258 		xenbus_dev_fatal(dev, error, "creating netdev");
1259 		return (error);
1260 	}
1261 
1262 	DPRINTF("Attaching to %s\n", xenbus_get_node(dev));
1263 
1264 	/*
1265 	 * Basic initialization.
1266 	 * After this block it is safe to call xnb_detach()
1267 	 * to clean up any allocated data for this instance.
1268 	 */
1269 	xnb = device_get_softc(dev);
1270 	xnb->otherend_id = xenbus_get_otherend_id(dev);
1271 	for (i=0; i < XNB_NUM_RING_TYPES; i++) {
1272 		xnb->ring_configs[i].ring_pages = 1;
1273 	}
1274 
1275 	/*
1276 	 * Setup sysctl variables.
1277 	 */
1278 	xnb_setup_sysctl(xnb);
1279 
1280 	/* Update hot-plug status to satisfy xend. */
1281 	error = xs_printf(XST_NIL, xenbus_get_node(xnb->dev),
1282 			  "hotplug-status", "connected");
1283 	if (error != 0) {
1284 		xnb_attach_failed(xnb, error, "writing %s/hotplug-status",
1285 				  xenbus_get_node(xnb->dev));
1286 		return (error);
1287 	}
1288 
1289 	if ((error = xnb_publish_backend_info(xnb)) != 0) {
1290 		/*
1291 		 * If we can't publish our data, we cannot participate
1292 		 * in this connection, and waiting for a front-end state
1293 		 * change will not help the situation.
1294 		 */
1295 		xnb_attach_failed(xnb, error,
1296 		    "Publishing backend status for %s",
1297 				  xenbus_get_node(xnb->dev));
1298 		return error;
1299 	}
1300 
1301 	/* Tell the front end that we are ready to connect. */
1302 	xenbus_set_state(dev, XenbusStateInitWait);
1303 
1304 	return (0);
1305 }
1306 
1307 /**
1308  * Detach from a net back device instance.
1309  *
1310  * \param dev  NewBus device object representing this Xen Net Back instance.
1311  *
1312  * \return  0 for success, errno codes for failure.
1313  *
1314  * \note A net back device may be detached at any time in its life-cycle,
1315  *       including part way through the attach process.  For this reason,
1316  *       initialization order and the intialization state checks in this
1317  *       routine must be carefully coupled so that attach time failures
1318  *       are gracefully handled.
1319  */
1320 static int
1321 xnb_detach(device_t dev)
1322 {
1323 	struct xnb_softc *xnb;
1324 
1325 	DPRINTF("\n");
1326 
1327 	xnb = device_get_softc(dev);
1328 	mtx_lock(&xnb->sc_lock);
1329 	while (xnb_shutdown(xnb) == EAGAIN) {
1330 		msleep(xnb, &xnb->sc_lock, /*wakeup prio unchanged*/0,
1331 		       "xnb_shutdown", 0);
1332 	}
1333 	mtx_unlock(&xnb->sc_lock);
1334 	DPRINTF("\n");
1335 
1336 	mtx_destroy(&xnb->tx_lock);
1337 	mtx_destroy(&xnb->rx_lock);
1338 	mtx_destroy(&xnb->sc_lock);
1339 	return (0);
1340 }
1341 
1342 /**
1343  * Prepare this net back device for suspension of this VM.
1344  *
1345  * \param dev  NewBus device object representing this Xen net Back instance.
1346  *
1347  * \return  0 for success, errno codes for failure.
1348  */
1349 static int
1350 xnb_suspend(device_t dev)
1351 {
1352 	return (0);
1353 }
1354 
1355 /**
1356  * Perform any processing required to recover from a suspended state.
1357  *
1358  * \param dev  NewBus device object representing this Xen Net Back instance.
1359  *
1360  * \return  0 for success, errno codes for failure.
1361  */
1362 static int
1363 xnb_resume(device_t dev)
1364 {
1365 	return (0);
1366 }
1367 
1368 /**
1369  * Handle state changes expressed via the XenStore by our front-end peer.
1370  *
1371  * \param dev             NewBus device object representing this Xen
1372  *                        Net Back instance.
1373  * \param frontend_state  The new state of the front-end.
1374  *
1375  * \return  0 for success, errno codes for failure.
1376  */
1377 static void
1378 xnb_frontend_changed(device_t dev, XenbusState frontend_state)
1379 {
1380 	struct xnb_softc *xnb;
1381 
1382 	xnb = device_get_softc(dev);
1383 
1384 	DPRINTF("frontend_state=%s, xnb_state=%s\n",
1385 	        xenbus_strstate(frontend_state),
1386 		xenbus_strstate(xenbus_get_state(xnb->dev)));
1387 
1388 	switch (frontend_state) {
1389 	case XenbusStateInitialising:
1390 		break;
1391 	case XenbusStateInitialised:
1392 	case XenbusStateConnected:
1393 		xnb_connect(xnb);
1394 		break;
1395 	case XenbusStateClosing:
1396 	case XenbusStateClosed:
1397 		mtx_lock(&xnb->sc_lock);
1398 		xnb_shutdown(xnb);
1399 		mtx_unlock(&xnb->sc_lock);
1400 		if (frontend_state == XenbusStateClosed)
1401 			xenbus_set_state(xnb->dev, XenbusStateClosed);
1402 		break;
1403 	default:
1404 		xenbus_dev_fatal(xnb->dev, EINVAL, "saw state %d at frontend",
1405 				 frontend_state);
1406 		break;
1407 	}
1408 }
1409 
1410 
1411 /*---------------------------- Request Processing ----------------------------*/
1412 /**
1413  * Interrupt handler bound to the shared ring's event channel.
1414  * Entry point for the xennet transmit path in netback
1415  * Transfers packets from the Xen ring to the host's generic networking stack
1416  *
1417  * \param arg  Callback argument registerd during event channel
1418  *             binding - the xnb_softc for this instance.
1419  */
1420 static void
1421 xnb_intr(void *arg)
1422 {
1423 	struct xnb_softc *xnb;
1424 	struct ifnet *ifp;
1425 	netif_tx_back_ring_t *txb;
1426 	RING_IDX req_prod_local;
1427 
1428 	xnb = (struct xnb_softc *)arg;
1429 	ifp = xnb->xnb_ifp;
1430 	txb = &xnb->ring_configs[XNB_RING_TYPE_TX].back_ring.tx_ring;
1431 
1432 	mtx_lock(&xnb->tx_lock);
1433 	do {
1434 		int notify;
1435 		req_prod_local = txb->sring->req_prod;
1436 		xen_rmb();
1437 
1438 		for (;;) {
1439 			struct mbuf *mbufc;
1440 			int err;
1441 
1442 			err = xnb_recv(txb, xnb->otherend_id, &mbufc, ifp,
1443 			    	       xnb->tx_gnttab);
1444 			if (err || (mbufc == NULL))
1445 				break;
1446 
1447 			/* Send the packet to the generic network stack */
1448 			(*xnb->xnb_ifp->if_input)(xnb->xnb_ifp, mbufc);
1449 		}
1450 
1451 		RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(txb, notify);
1452 		if (notify != 0)
1453 			xen_intr_signal(xnb->xen_intr_handle);
1454 
1455 		txb->sring->req_event = txb->req_cons + 1;
1456 		xen_mb();
1457 	} while (txb->sring->req_prod != req_prod_local) ;
1458 	mtx_unlock(&xnb->tx_lock);
1459 
1460 	xnb_start(ifp);
1461 }
1462 
1463 
1464 /**
1465  * Build a struct xnb_pkt based on netif_tx_request's from a netif tx ring.
1466  * Will read exactly 0 or 1 packets from the ring; never a partial packet.
1467  * \param[out]	pkt	The returned packet.  If there is an error building
1468  * 			the packet, pkt.list_len will be set to 0.
1469  * \param[in]	tx_ring	Pointer to the Ring that is the input to this function
1470  * \param[in]	start	The ring index of the first potential request
1471  * \return		The number of requests consumed to build this packet
1472  */
1473 static int
1474 xnb_ring2pkt(struct xnb_pkt *pkt, const netif_tx_back_ring_t *tx_ring,
1475 	     RING_IDX start)
1476 {
1477 	/*
1478 	 * Outline:
1479 	 * 1) Initialize pkt
1480 	 * 2) Read the first request of the packet
1481 	 * 3) Read the extras
1482 	 * 4) Set cdr
1483 	 * 5) Loop on the remainder of the packet
1484 	 * 6) Finalize pkt (stuff like car_size and list_len)
1485 	 */
1486 	int idx = start;
1487 	int discard = 0;	/* whether to discard the packet */
1488 	int more_data = 0;	/* there are more request past the last one */
1489 	uint16_t cdr_size = 0;	/* accumulated size of requests 2 through n */
1490 
1491 	xnb_pkt_initialize(pkt);
1492 
1493 	/* Read the first request */
1494 	if (RING_HAS_UNCONSUMED_REQUESTS_2(tx_ring, idx)) {
1495 		netif_tx_request_t *tx = RING_GET_REQUEST(tx_ring, idx);
1496 		pkt->size = tx->size;
1497 		pkt->flags = tx->flags & ~NETTXF_more_data;
1498 		more_data = tx->flags & NETTXF_more_data;
1499 		pkt->list_len++;
1500 		pkt->car = idx;
1501 		idx++;
1502 	}
1503 
1504 	/* Read the extra info */
1505 	if ((pkt->flags & NETTXF_extra_info) &&
1506 	    RING_HAS_UNCONSUMED_REQUESTS_2(tx_ring, idx)) {
1507 		netif_extra_info_t *ext =
1508 		    (netif_extra_info_t*) RING_GET_REQUEST(tx_ring, idx);
1509 		pkt->extra.type = ext->type;
1510 		switch (pkt->extra.type) {
1511 			case XEN_NETIF_EXTRA_TYPE_GSO:
1512 				pkt->extra.u.gso = ext->u.gso;
1513 				break;
1514 			default:
1515 				/*
1516 				 * The reference Linux netfront driver will
1517 				 * never set any other extra.type.  So we don't
1518 				 * know what to do with it.  Let's print an
1519 				 * error, then consume and discard the packet
1520 				 */
1521 				printf("xnb(%s:%d): Unknown extra info type %d."
1522 				       "  Discarding packet\n",
1523 				       __func__, __LINE__, pkt->extra.type);
1524 				xnb_dump_txreq(start, RING_GET_REQUEST(tx_ring,
1525 				    start));
1526 				xnb_dump_txreq(idx, RING_GET_REQUEST(tx_ring,
1527 				    idx));
1528 				discard = 1;
1529 				break;
1530 		}
1531 
1532 		pkt->extra.flags = ext->flags;
1533 		if (ext->flags & XEN_NETIF_EXTRA_FLAG_MORE) {
1534 			/*
1535 			 * The reference linux netfront driver never sets this
1536 			 * flag (nor does any other known netfront).  So we
1537 			 * will discard the packet.
1538 			 */
1539 			printf("xnb(%s:%d): Request sets "
1540 			    "XEN_NETIF_EXTRA_FLAG_MORE, but we can't handle "
1541 			    "that\n", __func__, __LINE__);
1542 			xnb_dump_txreq(start, RING_GET_REQUEST(tx_ring, start));
1543 			xnb_dump_txreq(idx, RING_GET_REQUEST(tx_ring, idx));
1544 			discard = 1;
1545 		}
1546 
1547 		idx++;
1548 	}
1549 
1550 	/* Set cdr.  If there is not more data, cdr is invalid */
1551 	pkt->cdr = idx;
1552 
1553 	/* Loop on remainder of packet */
1554 	while (more_data && RING_HAS_UNCONSUMED_REQUESTS_2(tx_ring, idx)) {
1555 		netif_tx_request_t *tx = RING_GET_REQUEST(tx_ring, idx);
1556 		pkt->list_len++;
1557 		cdr_size += tx->size;
1558 		if (tx->flags & ~NETTXF_more_data) {
1559 			/* There should be no other flags set at this point */
1560 			printf("xnb(%s:%d): Request sets unknown flags %d "
1561 			    "after the 1st request in the packet.\n",
1562 			    __func__, __LINE__, tx->flags);
1563 			xnb_dump_txreq(start, RING_GET_REQUEST(tx_ring, start));
1564 			xnb_dump_txreq(idx, RING_GET_REQUEST(tx_ring, idx));
1565 		}
1566 
1567 		more_data = tx->flags & NETTXF_more_data;
1568 		idx++;
1569 	}
1570 
1571 	/* Finalize packet */
1572 	if (more_data != 0) {
1573 		/* The ring ran out of requests before finishing the packet */
1574 		xnb_pkt_invalidate(pkt);
1575 		idx = start;	/* tell caller that we consumed no requests */
1576 	} else {
1577 		/* Calculate car_size */
1578 		pkt->car_size = pkt->size - cdr_size;
1579 	}
1580 	if (discard != 0) {
1581 		xnb_pkt_invalidate(pkt);
1582 	}
1583 
1584 	return idx - start;
1585 }
1586 
1587 
1588 /**
1589  * Respond to all the requests that constituted pkt.  Builds the responses and
1590  * writes them to the ring, but doesn't push them to the shared ring.
1591  * \param[in] pkt	the packet that needs a response
1592  * \param[in] error	true if there was an error handling the packet, such
1593  * 			as in the hypervisor copy op or mbuf allocation
1594  * \param[out] ring	Responses go here
1595  */
1596 static void
1597 xnb_txpkt2rsp(const struct xnb_pkt *pkt, netif_tx_back_ring_t *ring,
1598 	      int error)
1599 {
1600 	/*
1601 	 * Outline:
1602 	 * 1) Respond to the first request
1603 	 * 2) Respond to the extra info reques
1604 	 * Loop through every remaining request in the packet, generating
1605 	 * responses that copy those requests' ids and sets the status
1606 	 * appropriately.
1607 	 */
1608 	netif_tx_request_t *tx;
1609 	netif_tx_response_t *rsp;
1610 	int i;
1611 	uint16_t status;
1612 
1613 	status = (xnb_pkt_is_valid(pkt) == 0) || error ?
1614 		NETIF_RSP_ERROR : NETIF_RSP_OKAY;
1615 	KASSERT((pkt->list_len == 0) || (ring->rsp_prod_pvt == pkt->car),
1616 	    ("Cannot respond to ring requests out of order"));
1617 
1618 	if (pkt->list_len >= 1) {
1619 		uint16_t id;
1620 		tx = RING_GET_REQUEST(ring, ring->rsp_prod_pvt);
1621 		id = tx->id;
1622 		rsp = RING_GET_RESPONSE(ring, ring->rsp_prod_pvt);
1623 		rsp->id = id;
1624 		rsp->status = status;
1625 		ring->rsp_prod_pvt++;
1626 
1627 		if (pkt->flags & NETRXF_extra_info) {
1628 			rsp = RING_GET_RESPONSE(ring, ring->rsp_prod_pvt);
1629 			rsp->status = NETIF_RSP_NULL;
1630 			ring->rsp_prod_pvt++;
1631 		}
1632 	}
1633 
1634 	for (i=0; i < pkt->list_len - 1; i++) {
1635 		uint16_t id;
1636 		tx = RING_GET_REQUEST(ring, ring->rsp_prod_pvt);
1637 		id = tx->id;
1638 		rsp = RING_GET_RESPONSE(ring, ring->rsp_prod_pvt);
1639 		rsp->id = id;
1640 		rsp->status = status;
1641 		ring->rsp_prod_pvt++;
1642 	}
1643 }
1644 
1645 /**
1646  * Create an mbuf chain to represent a packet.  Initializes all of the headers
1647  * in the mbuf chain, but does not copy the data.  The returned chain must be
1648  * free()'d when no longer needed
1649  * \param[in]	pkt	A packet to model the mbuf chain after
1650  * \return	A newly allocated mbuf chain, possibly with clusters attached.
1651  * 		NULL on failure
1652  */
1653 static struct mbuf*
1654 xnb_pkt2mbufc(const struct xnb_pkt *pkt, struct ifnet *ifp)
1655 {
1656 	/**
1657 	 * \todo consider using a memory pool for mbufs instead of
1658 	 * reallocating them for every packet
1659 	 */
1660 	/** \todo handle extra data */
1661 	struct mbuf *m;
1662 
1663 	m = m_getm(NULL, pkt->size, M_NOWAIT, MT_DATA);
1664 
1665 	if (m != NULL) {
1666 		m->m_pkthdr.rcvif = ifp;
1667 		if (pkt->flags & NETTXF_data_validated) {
1668 			/*
1669 			 * We lie to the host OS and always tell it that the
1670 			 * checksums are ok, because the packet is unlikely to
1671 			 * get corrupted going across domains.
1672 			 */
1673 			m->m_pkthdr.csum_flags = (
1674 				CSUM_IP_CHECKED |
1675 				CSUM_IP_VALID   |
1676 				CSUM_DATA_VALID |
1677 				CSUM_PSEUDO_HDR
1678 				);
1679 			m->m_pkthdr.csum_data = 0xffff;
1680 		}
1681 	}
1682 	return m;
1683 }
1684 
1685 /**
1686  * Build a gnttab_copy table that can be used to copy data from a pkt
1687  * to an mbufc.  Does not actually perform the copy.  Always uses gref's on
1688  * the packet side.
1689  * \param[in]	pkt	pkt's associated requests form the src for
1690  * 			the copy operation
1691  * \param[in]	mbufc	mbufc's storage forms the dest for the copy operation
1692  * \param[out]  gnttab	Storage for the returned grant table
1693  * \param[in]	txb	Pointer to the backend ring structure
1694  * \param[in]	otherend_id	The domain ID of the other end of the copy
1695  * \return 		The number of gnttab entries filled
1696  */
1697 static int
1698 xnb_txpkt2gnttab(const struct xnb_pkt *pkt, const struct mbuf *mbufc,
1699 		 gnttab_copy_table gnttab, const netif_tx_back_ring_t *txb,
1700 		 domid_t otherend_id)
1701 {
1702 
1703 	const struct mbuf *mbuf = mbufc;/* current mbuf within the chain */
1704 	int gnt_idx = 0;		/* index into grant table */
1705 	RING_IDX r_idx = pkt->car;	/* index into tx ring buffer */
1706 	int r_ofs = 0;	/* offset of next data within tx request's data area */
1707 	int m_ofs = 0;	/* offset of next data within mbuf's data area */
1708 	/* size in bytes that still needs to be represented in the table */
1709 	uint16_t size_remaining = pkt->size;
1710 
1711 	while (size_remaining > 0) {
1712 		const netif_tx_request_t *txq = RING_GET_REQUEST(txb, r_idx);
1713 		const size_t mbuf_space = M_TRAILINGSPACE(mbuf) - m_ofs;
1714 		const size_t req_size =
1715 			r_idx == pkt->car ? pkt->car_size : txq->size;
1716 		const size_t pkt_space = req_size - r_ofs;
1717 		/*
1718 		 * space is the largest amount of data that can be copied in the
1719 		 * grant table's next entry
1720 		 */
1721 		const size_t space = MIN(pkt_space, mbuf_space);
1722 
1723 		/* TODO: handle this error condition without panicking */
1724 		KASSERT(gnt_idx < GNTTAB_LEN, ("Grant table is too short"));
1725 
1726 		gnttab[gnt_idx].source.u.ref = txq->gref;
1727 		gnttab[gnt_idx].source.domid = otherend_id;
1728 		gnttab[gnt_idx].source.offset = txq->offset + r_ofs;
1729 		gnttab[gnt_idx].dest.u.gmfn = virt_to_mfn(
1730 		    mtod(mbuf, vm_offset_t) + m_ofs);
1731 		gnttab[gnt_idx].dest.offset = virt_to_offset(
1732 		    mtod(mbuf, vm_offset_t) + m_ofs);
1733 		gnttab[gnt_idx].dest.domid = DOMID_SELF;
1734 		gnttab[gnt_idx].len = space;
1735 		gnttab[gnt_idx].flags = GNTCOPY_source_gref;
1736 
1737 		gnt_idx++;
1738 		r_ofs += space;
1739 		m_ofs += space;
1740 		size_remaining -= space;
1741 		if (req_size - r_ofs <= 0) {
1742 			/* Must move to the next tx request */
1743 			r_ofs = 0;
1744 			r_idx = (r_idx == pkt->car) ? pkt->cdr : r_idx + 1;
1745 		}
1746 		if (M_TRAILINGSPACE(mbuf) - m_ofs <= 0) {
1747 			/* Must move to the next mbuf */
1748 			m_ofs = 0;
1749 			mbuf = mbuf->m_next;
1750 		}
1751 	}
1752 
1753 	return gnt_idx;
1754 }
1755 
1756 /**
1757  * Check the status of the grant copy operations, and update mbufs various
1758  * non-data fields to reflect the data present.
1759  * \param[in,out] mbufc	mbuf chain to update.  The chain must be valid and of
1760  * 			the correct length, and data should already be present
1761  * \param[in] gnttab	A grant table for a just completed copy op
1762  * \param[in] n_entries The number of valid entries in the grant table
1763  */
1764 static void
1765 xnb_update_mbufc(struct mbuf *mbufc, const gnttab_copy_table gnttab,
1766     		 int n_entries)
1767 {
1768 	struct mbuf *mbuf = mbufc;
1769 	int i;
1770 	size_t total_size = 0;
1771 
1772 	for (i = 0; i < n_entries; i++) {
1773 		KASSERT(gnttab[i].status == GNTST_okay,
1774 		    ("Some gnttab_copy entry had error status %hd\n",
1775 		    gnttab[i].status));
1776 
1777 		mbuf->m_len += gnttab[i].len;
1778 		total_size += gnttab[i].len;
1779 		if (M_TRAILINGSPACE(mbuf) <= 0) {
1780 			mbuf = mbuf->m_next;
1781 		}
1782 	}
1783 	mbufc->m_pkthdr.len = total_size;
1784 
1785 #if defined(INET) || defined(INET6)
1786 	xnb_add_mbuf_cksum(mbufc);
1787 #endif
1788 }
1789 
1790 /**
1791  * Dequeue at most one packet from the shared ring
1792  * \param[in,out] txb	Netif tx ring.  A packet will be removed from it, and
1793  * 			its private indices will be updated.  But the indices
1794  * 			will not be pushed to the shared ring.
1795  * \param[in] ifnet	Interface to which the packet will be sent
1796  * \param[in] otherend	Domain ID of the other end of the ring
1797  * \param[out] mbufc	The assembled mbuf chain, ready to send to the generic
1798  * 			networking stack
1799  * \param[in,out] gnttab Pointer to enough memory for a grant table.  We make
1800  * 			this a function parameter so that we will take less
1801  * 			stack space.
1802  * \return		An error code
1803  */
1804 static int
1805 xnb_recv(netif_tx_back_ring_t *txb, domid_t otherend, struct mbuf **mbufc,
1806 	 struct ifnet *ifnet, gnttab_copy_table gnttab)
1807 {
1808 	struct xnb_pkt pkt;
1809 	/* number of tx requests consumed to build the last packet */
1810 	int num_consumed;
1811 	int nr_ents;
1812 
1813 	*mbufc = NULL;
1814 	num_consumed = xnb_ring2pkt(&pkt, txb, txb->req_cons);
1815 	if (num_consumed == 0)
1816 		return 0;	/* Nothing to receive */
1817 
1818 	/* update statistics independent of errors */
1819 	ifnet->if_ipackets++;
1820 
1821 	/*
1822 	 * if we got here, then 1 or more requests was consumed, but the packet
1823 	 * is not necessarily valid.
1824 	 */
1825 	if (xnb_pkt_is_valid(&pkt) == 0) {
1826 		/* got a garbage packet, respond and drop it */
1827 		xnb_txpkt2rsp(&pkt, txb, 1);
1828 		txb->req_cons += num_consumed;
1829 		DPRINTF("xnb_intr: garbage packet, num_consumed=%d\n",
1830 				num_consumed);
1831 		ifnet->if_ierrors++;
1832 		return EINVAL;
1833 	}
1834 
1835 	*mbufc = xnb_pkt2mbufc(&pkt, ifnet);
1836 
1837 	if (*mbufc == NULL) {
1838 		/*
1839 		 * Couldn't allocate mbufs.  Respond and drop the packet.  Do
1840 		 * not consume the requests
1841 		 */
1842 		xnb_txpkt2rsp(&pkt, txb, 1);
1843 		DPRINTF("xnb_intr: Couldn't allocate mbufs, num_consumed=%d\n",
1844 		    num_consumed);
1845 		ifnet->if_iqdrops++;
1846 		return ENOMEM;
1847 	}
1848 
1849 	nr_ents = xnb_txpkt2gnttab(&pkt, *mbufc, gnttab, txb, otherend);
1850 
1851 	if (nr_ents > 0) {
1852 		int __unused hv_ret = HYPERVISOR_grant_table_op(GNTTABOP_copy,
1853 		    gnttab, nr_ents);
1854 		KASSERT(hv_ret == 0,
1855 		    ("HYPERVISOR_grant_table_op returned %d\n", hv_ret));
1856 		xnb_update_mbufc(*mbufc, gnttab, nr_ents);
1857 	}
1858 
1859 	xnb_txpkt2rsp(&pkt, txb, 0);
1860 	txb->req_cons += num_consumed;
1861 	return 0;
1862 }
1863 
1864 /**
1865  * Create an xnb_pkt based on the contents of an mbuf chain.
1866  * \param[in] mbufc	mbuf chain to transform into a packet
1867  * \param[out] pkt	Storage for the newly generated xnb_pkt
1868  * \param[in] start	The ring index of the first available slot in the rx
1869  * 			ring
1870  * \param[in] space	The number of free slots in the rx ring
1871  * \retval 0		Success
1872  * \retval EINVAL	mbufc was corrupt or not convertible into a pkt
1873  * \retval EAGAIN	There was not enough space in the ring to queue the
1874  * 			packet
1875  */
1876 static int
1877 xnb_mbufc2pkt(const struct mbuf *mbufc, struct xnb_pkt *pkt,
1878 	      RING_IDX start, int space)
1879 {
1880 
1881 	int retval = 0;
1882 
1883 	if ((mbufc == NULL) ||
1884 	     ( (mbufc->m_flags & M_PKTHDR) == 0) ||
1885 	     (mbufc->m_pkthdr.len == 0)) {
1886 		xnb_pkt_invalidate(pkt);
1887 		retval = EINVAL;
1888 	} else {
1889 		int slots_required;
1890 
1891 		xnb_pkt_validate(pkt);
1892 		pkt->flags = 0;
1893 		pkt->size = mbufc->m_pkthdr.len;
1894 		pkt->car = start;
1895 		pkt->car_size = mbufc->m_len;
1896 
1897 		if (mbufc->m_pkthdr.csum_flags & CSUM_TSO) {
1898 			pkt->flags |= NETRXF_extra_info;
1899 			pkt->extra.u.gso.size = mbufc->m_pkthdr.tso_segsz;
1900 			pkt->extra.u.gso.type = XEN_NETIF_GSO_TYPE_TCPV4;
1901 			pkt->extra.u.gso.pad = 0;
1902 			pkt->extra.u.gso.features = 0;
1903 			pkt->extra.type = XEN_NETIF_EXTRA_TYPE_GSO;
1904 			pkt->extra.flags = 0;
1905 			pkt->cdr = start + 2;
1906 		} else {
1907 			pkt->cdr = start + 1;
1908 		}
1909 		if (mbufc->m_pkthdr.csum_flags & (CSUM_TSO | CSUM_DELAY_DATA)) {
1910 			pkt->flags |=
1911 			    (NETRXF_csum_blank | NETRXF_data_validated);
1912 		}
1913 
1914 		/*
1915 		 * Each ring response can have up to PAGE_SIZE of data.
1916 		 * Assume that we can defragment the mbuf chain efficiently
1917 		 * into responses so that each response but the last uses all
1918 		 * PAGE_SIZE bytes.
1919 		 */
1920 		pkt->list_len = (pkt->size + PAGE_SIZE - 1) / PAGE_SIZE;
1921 
1922 		if (pkt->list_len > 1) {
1923 			pkt->flags |= NETRXF_more_data;
1924 		}
1925 
1926 		slots_required = pkt->list_len +
1927 			(pkt->flags & NETRXF_extra_info ? 1 : 0);
1928 		if (slots_required > space) {
1929 			xnb_pkt_invalidate(pkt);
1930 			retval = EAGAIN;
1931 		}
1932 	}
1933 
1934 	return retval;
1935 }
1936 
1937 /**
1938  * Build a gnttab_copy table that can be used to copy data from an mbuf chain
1939  * to the frontend's shared buffers.  Does not actually perform the copy.
1940  * Always uses gref's on the other end's side.
1941  * \param[in]	pkt	pkt's associated responses form the dest for the copy
1942  * 			operatoin
1943  * \param[in]	mbufc	The source for the copy operation
1944  * \param[out]	gnttab	Storage for the returned grant table
1945  * \param[in]	rxb	Pointer to the backend ring structure
1946  * \param[in]	otherend_id	The domain ID of the other end of the copy
1947  * \return 		The number of gnttab entries filled
1948  */
1949 static int
1950 xnb_rxpkt2gnttab(const struct xnb_pkt *pkt, const struct mbuf *mbufc,
1951 		 gnttab_copy_table gnttab, const netif_rx_back_ring_t *rxb,
1952 		 domid_t otherend_id)
1953 {
1954 
1955 	const struct mbuf *mbuf = mbufc;/* current mbuf within the chain */
1956 	int gnt_idx = 0;		/* index into grant table */
1957 	RING_IDX r_idx = pkt->car;	/* index into rx ring buffer */
1958 	int r_ofs = 0;	/* offset of next data within rx request's data area */
1959 	int m_ofs = 0;	/* offset of next data within mbuf's data area */
1960 	/* size in bytes that still needs to be represented in the table */
1961 	uint16_t size_remaining;
1962 
1963 	size_remaining = (xnb_pkt_is_valid(pkt) != 0) ? pkt->size : 0;
1964 
1965 	while (size_remaining > 0) {
1966 		const netif_rx_request_t *rxq = RING_GET_REQUEST(rxb, r_idx);
1967 		const size_t mbuf_space = mbuf->m_len - m_ofs;
1968 		/* Xen shared pages have an implied size of PAGE_SIZE */
1969 		const size_t req_size = PAGE_SIZE;
1970 		const size_t pkt_space = req_size - r_ofs;
1971 		/*
1972 		 * space is the largest amount of data that can be copied in the
1973 		 * grant table's next entry
1974 		 */
1975 		const size_t space = MIN(pkt_space, mbuf_space);
1976 
1977 		/* TODO: handle this error condition without panicing */
1978 		KASSERT(gnt_idx < GNTTAB_LEN, ("Grant table is too short"));
1979 
1980 		gnttab[gnt_idx].dest.u.ref = rxq->gref;
1981 		gnttab[gnt_idx].dest.domid = otherend_id;
1982 		gnttab[gnt_idx].dest.offset = r_ofs;
1983 		gnttab[gnt_idx].source.u.gmfn = virt_to_mfn(
1984 		    mtod(mbuf, vm_offset_t) + m_ofs);
1985 		gnttab[gnt_idx].source.offset = virt_to_offset(
1986 		    mtod(mbuf, vm_offset_t) + m_ofs);
1987 		gnttab[gnt_idx].source.domid = DOMID_SELF;
1988 		gnttab[gnt_idx].len = space;
1989 		gnttab[gnt_idx].flags = GNTCOPY_dest_gref;
1990 
1991 		gnt_idx++;
1992 
1993 		r_ofs += space;
1994 		m_ofs += space;
1995 		size_remaining -= space;
1996 		if (req_size - r_ofs <= 0) {
1997 			/* Must move to the next rx request */
1998 			r_ofs = 0;
1999 			r_idx = (r_idx == pkt->car) ? pkt->cdr : r_idx + 1;
2000 		}
2001 		if (mbuf->m_len - m_ofs <= 0) {
2002 			/* Must move to the next mbuf */
2003 			m_ofs = 0;
2004 			mbuf = mbuf->m_next;
2005 		}
2006 	}
2007 
2008 	return gnt_idx;
2009 }
2010 
2011 /**
2012  * Generates responses for all the requests that constituted pkt.  Builds
2013  * responses and writes them to the ring, but doesn't push the shared ring
2014  * indices.
2015  * \param[in] pkt	the packet that needs a response
2016  * \param[in] gnttab	The grant copy table corresponding to this packet.
2017  * 			Used to determine how many rsp->netif_rx_response_t's to
2018  * 			generate.
2019  * \param[in] n_entries	Number of relevant entries in the grant table
2020  * \param[out] ring	Responses go here
2021  * \return		The number of RX requests that were consumed to generate
2022  * 			the responses
2023  */
2024 static int
2025 xnb_rxpkt2rsp(const struct xnb_pkt *pkt, const gnttab_copy_table gnttab,
2026     	      int n_entries, netif_rx_back_ring_t *ring)
2027 {
2028 	/*
2029 	 * This code makes the following assumptions:
2030 	 *	* All entries in gnttab set GNTCOPY_dest_gref
2031 	 *	* The entries in gnttab are grouped by their grefs: any two
2032 	 *	   entries with the same gref must be adjacent
2033 	 */
2034 	int error = 0;
2035 	int gnt_idx, i;
2036 	int n_responses = 0;
2037 	grant_ref_t last_gref = GRANT_REF_INVALID;
2038 	RING_IDX r_idx;
2039 
2040 	KASSERT(gnttab != NULL, ("Received a null granttable copy"));
2041 
2042 	/*
2043 	 * In the event of an error, we only need to send one response to the
2044 	 * netfront.  In that case, we musn't write any data to the responses
2045 	 * after the one we send.  So we must loop all the way through gnttab
2046 	 * looking for errors before we generate any responses
2047 	 *
2048 	 * Since we're looping through the grant table anyway, we'll count the
2049 	 * number of different gref's in it, which will tell us how many
2050 	 * responses to generate
2051 	 */
2052 	for (gnt_idx = 0; gnt_idx < n_entries; gnt_idx++) {
2053 		int16_t status = gnttab[gnt_idx].status;
2054 		if (status != GNTST_okay) {
2055 			DPRINTF(
2056 			    "Got error %d for hypervisor gnttab_copy status\n",
2057 			    status);
2058 			error = 1;
2059 			break;
2060 		}
2061 		if (gnttab[gnt_idx].dest.u.ref != last_gref) {
2062 			n_responses++;
2063 			last_gref = gnttab[gnt_idx].dest.u.ref;
2064 		}
2065 	}
2066 
2067 	if (error != 0) {
2068 		uint16_t id;
2069 		netif_rx_response_t *rsp;
2070 
2071 		id = RING_GET_REQUEST(ring, ring->rsp_prod_pvt)->id;
2072 		rsp = RING_GET_RESPONSE(ring, ring->rsp_prod_pvt);
2073 		rsp->id = id;
2074 		rsp->status = NETIF_RSP_ERROR;
2075 		n_responses = 1;
2076 	} else {
2077 		gnt_idx = 0;
2078 		const int has_extra = pkt->flags & NETRXF_extra_info;
2079 		if (has_extra != 0)
2080 			n_responses++;
2081 
2082 		for (i = 0; i < n_responses; i++) {
2083 			netif_rx_request_t rxq;
2084 			netif_rx_response_t *rsp;
2085 
2086 			r_idx = ring->rsp_prod_pvt + i;
2087 			/*
2088 			 * We copy the structure of rxq instead of making a
2089 			 * pointer because it shares the same memory as rsp.
2090 			 */
2091 			rxq = *(RING_GET_REQUEST(ring, r_idx));
2092 			rsp = RING_GET_RESPONSE(ring, r_idx);
2093 			if (has_extra && (i == 1)) {
2094 				netif_extra_info_t *ext =
2095 					(netif_extra_info_t*)rsp;
2096 				ext->type = XEN_NETIF_EXTRA_TYPE_GSO;
2097 				ext->flags = 0;
2098 				ext->u.gso.size = pkt->extra.u.gso.size;
2099 				ext->u.gso.type = XEN_NETIF_GSO_TYPE_TCPV4;
2100 				ext->u.gso.pad = 0;
2101 				ext->u.gso.features = 0;
2102 			} else {
2103 				rsp->id = rxq.id;
2104 				rsp->status = GNTST_okay;
2105 				rsp->offset = 0;
2106 				rsp->flags = 0;
2107 				if (i < pkt->list_len - 1)
2108 					rsp->flags |= NETRXF_more_data;
2109 				if ((i == 0) && has_extra)
2110 					rsp->flags |= NETRXF_extra_info;
2111 				if ((i == 0) &&
2112 					(pkt->flags & NETRXF_data_validated)) {
2113 					rsp->flags |= NETRXF_data_validated;
2114 					rsp->flags |= NETRXF_csum_blank;
2115 				}
2116 				rsp->status = 0;
2117 				for (; gnttab[gnt_idx].dest.u.ref == rxq.gref;
2118 				    gnt_idx++) {
2119 					rsp->status += gnttab[gnt_idx].len;
2120 				}
2121 			}
2122 		}
2123 	}
2124 
2125 	ring->req_cons += n_responses;
2126 	ring->rsp_prod_pvt += n_responses;
2127 	return n_responses;
2128 }
2129 
2130 #if defined(INET) || defined(INET6)
2131 /**
2132  * Add IP, TCP, and/or UDP checksums to every mbuf in a chain.  The first mbuf
2133  * in the chain must start with a struct ether_header.
2134  *
2135  * XXX This function will perform incorrectly on UDP packets that are split up
2136  * into multiple ethernet frames.
2137  */
2138 static void
2139 xnb_add_mbuf_cksum(struct mbuf *mbufc)
2140 {
2141 	struct ether_header *eh;
2142 	struct ip *iph;
2143 	uint16_t ether_type;
2144 
2145 	eh = mtod(mbufc, struct ether_header*);
2146 	ether_type = ntohs(eh->ether_type);
2147 	if (ether_type != ETHERTYPE_IP) {
2148 		/* Nothing to calculate */
2149 		return;
2150 	}
2151 
2152 	iph = (struct ip*)(eh + 1);
2153 	if (mbufc->m_pkthdr.csum_flags & CSUM_IP_VALID) {
2154 		iph->ip_sum = 0;
2155 		iph->ip_sum = in_cksum_hdr(iph);
2156 	}
2157 
2158 	switch (iph->ip_p) {
2159 	case IPPROTO_TCP:
2160 		if (mbufc->m_pkthdr.csum_flags & CSUM_IP_VALID) {
2161 			size_t tcplen = ntohs(iph->ip_len) - sizeof(struct ip);
2162 			struct tcphdr *th = (struct tcphdr*)(iph + 1);
2163 			th->th_sum = in_pseudo(iph->ip_src.s_addr,
2164 			    iph->ip_dst.s_addr, htons(IPPROTO_TCP + tcplen));
2165 			th->th_sum = in_cksum_skip(mbufc,
2166 			    sizeof(struct ether_header) + ntohs(iph->ip_len),
2167 			    sizeof(struct ether_header) + (iph->ip_hl << 2));
2168 		}
2169 		break;
2170 	case IPPROTO_UDP:
2171 		if (mbufc->m_pkthdr.csum_flags & CSUM_IP_VALID) {
2172 			size_t udplen = ntohs(iph->ip_len) - sizeof(struct ip);
2173 			struct udphdr *uh = (struct udphdr*)(iph + 1);
2174 			uh->uh_sum = in_pseudo(iph->ip_src.s_addr,
2175 			    iph->ip_dst.s_addr, htons(IPPROTO_UDP + udplen));
2176 			uh->uh_sum = in_cksum_skip(mbufc,
2177 			    sizeof(struct ether_header) + ntohs(iph->ip_len),
2178 			    sizeof(struct ether_header) + (iph->ip_hl << 2));
2179 		}
2180 		break;
2181 	default:
2182 		break;
2183 	}
2184 }
2185 #endif /* INET || INET6 */
2186 
2187 static void
2188 xnb_stop(struct xnb_softc *xnb)
2189 {
2190 	struct ifnet *ifp;
2191 
2192 	mtx_assert(&xnb->sc_lock, MA_OWNED);
2193 	ifp = xnb->xnb_ifp;
2194 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2195 	if_link_state_change(ifp, LINK_STATE_DOWN);
2196 }
2197 
2198 static int
2199 xnb_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2200 {
2201 	struct xnb_softc *xnb = ifp->if_softc;
2202 	struct ifreq *ifr = (struct ifreq*) data;
2203 #ifdef INET
2204 	struct ifaddr *ifa = (struct ifaddr*)data;
2205 #endif
2206 	int error = 0;
2207 
2208 	switch (cmd) {
2209 		case SIOCSIFFLAGS:
2210 			mtx_lock(&xnb->sc_lock);
2211 			if (ifp->if_flags & IFF_UP) {
2212 				xnb_ifinit_locked(xnb);
2213 			} else {
2214 				if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2215 					xnb_stop(xnb);
2216 				}
2217 			}
2218 			/*
2219 			 * Note: netfront sets a variable named xn_if_flags
2220 			 * here, but that variable is never read
2221 			 */
2222 			mtx_unlock(&xnb->sc_lock);
2223 			break;
2224 		case SIOCSIFADDR:
2225 		case SIOCGIFADDR:
2226 #ifdef INET
2227 			mtx_lock(&xnb->sc_lock);
2228 			if (ifa->ifa_addr->sa_family == AF_INET) {
2229 				ifp->if_flags |= IFF_UP;
2230 				if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2231 					ifp->if_drv_flags &= ~(IFF_DRV_RUNNING |
2232 							IFF_DRV_OACTIVE);
2233 					if_link_state_change(ifp,
2234 							LINK_STATE_DOWN);
2235 					ifp->if_drv_flags |= IFF_DRV_RUNNING;
2236 					ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2237 					if_link_state_change(ifp,
2238 					    LINK_STATE_UP);
2239 				}
2240 				arp_ifinit(ifp, ifa);
2241 				mtx_unlock(&xnb->sc_lock);
2242 			} else {
2243 				mtx_unlock(&xnb->sc_lock);
2244 #endif
2245 				error = ether_ioctl(ifp, cmd, data);
2246 #ifdef INET
2247 			}
2248 #endif
2249 			break;
2250 		case SIOCSIFCAP:
2251 			mtx_lock(&xnb->sc_lock);
2252 			if (ifr->ifr_reqcap & IFCAP_TXCSUM) {
2253 				ifp->if_capenable |= IFCAP_TXCSUM;
2254 				ifp->if_hwassist |= XNB_CSUM_FEATURES;
2255 			} else {
2256 				ifp->if_capenable &= ~(IFCAP_TXCSUM);
2257 				ifp->if_hwassist &= ~(XNB_CSUM_FEATURES);
2258 			}
2259 			if ((ifr->ifr_reqcap & IFCAP_RXCSUM)) {
2260 				ifp->if_capenable |= IFCAP_RXCSUM;
2261 			} else {
2262 				ifp->if_capenable &= ~(IFCAP_RXCSUM);
2263 			}
2264 			/*
2265 			 * TODO enable TSO4 and LRO once we no longer need
2266 			 * to calculate checksums in software
2267 			 */
2268 #if 0
2269 			if (ifr->if_reqcap |= IFCAP_TSO4) {
2270 				if (IFCAP_TXCSUM & ifp->if_capenable) {
2271 					printf("xnb: Xen netif requires that "
2272 						"TXCSUM be enabled in order "
2273 						"to use TSO4\n");
2274 					error = EINVAL;
2275 				} else {
2276 					ifp->if_capenable |= IFCAP_TSO4;
2277 					ifp->if_hwassist |= CSUM_TSO;
2278 				}
2279 			} else {
2280 				ifp->if_capenable &= ~(IFCAP_TSO4);
2281 				ifp->if_hwassist &= ~(CSUM_TSO);
2282 			}
2283 			if (ifr->ifreqcap |= IFCAP_LRO) {
2284 				ifp->if_capenable |= IFCAP_LRO;
2285 			} else {
2286 				ifp->if_capenable &= ~(IFCAP_LRO);
2287 			}
2288 #endif
2289 			mtx_unlock(&xnb->sc_lock);
2290 			break;
2291 		case SIOCSIFMTU:
2292 			ifp->if_mtu = ifr->ifr_mtu;
2293 			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2294 			xnb_ifinit(xnb);
2295 			break;
2296 		case SIOCADDMULTI:
2297 		case SIOCDELMULTI:
2298 		case SIOCSIFMEDIA:
2299 		case SIOCGIFMEDIA:
2300 			error = ifmedia_ioctl(ifp, ifr, &xnb->sc_media, cmd);
2301 			break;
2302 		default:
2303 			error = ether_ioctl(ifp, cmd, data);
2304 			break;
2305 	}
2306 	return (error);
2307 }
2308 
2309 static void
2310 xnb_start_locked(struct ifnet *ifp)
2311 {
2312 	netif_rx_back_ring_t *rxb;
2313 	struct xnb_softc *xnb;
2314 	struct mbuf *mbufc;
2315 	RING_IDX req_prod_local;
2316 
2317 	xnb = ifp->if_softc;
2318 	rxb = &xnb->ring_configs[XNB_RING_TYPE_RX].back_ring.rx_ring;
2319 
2320 	if (!xnb->carrier)
2321 		return;
2322 
2323 	do {
2324 		int out_of_space = 0;
2325 		int notify;
2326 		req_prod_local = rxb->sring->req_prod;
2327 		xen_rmb();
2328 		for (;;) {
2329 			int error;
2330 
2331 			IF_DEQUEUE(&ifp->if_snd, mbufc);
2332 			if (mbufc == NULL)
2333 				break;
2334 			error = xnb_send(rxb, xnb->otherend_id, mbufc,
2335 			    		 xnb->rx_gnttab);
2336 			switch (error) {
2337 				case EAGAIN:
2338 					/*
2339 					 * Insufficient space in the ring.
2340 					 * Requeue pkt and send when space is
2341 					 * available.
2342 					 */
2343 					IF_PREPEND(&ifp->if_snd, mbufc);
2344 					/*
2345 					 * Perhaps the frontend missed an IRQ
2346 					 * and went to sleep.  Notify it to wake
2347 					 * it up.
2348 					 */
2349 					out_of_space = 1;
2350 					break;
2351 
2352 				case EINVAL:
2353 					/* OS gave a corrupt packet.  Drop it.*/
2354 					ifp->if_oerrors++;
2355 					/* FALLTHROUGH */
2356 				default:
2357 					/* Send succeeded, or packet had error.
2358 					 * Free the packet */
2359 					ifp->if_opackets++;
2360 					if (mbufc)
2361 						m_freem(mbufc);
2362 					break;
2363 			}
2364 			if (out_of_space != 0)
2365 				break;
2366 		}
2367 
2368 		RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(rxb, notify);
2369 		if ((notify != 0) || (out_of_space != 0))
2370 			xen_intr_signal(xnb->xen_intr_handle);
2371 		rxb->sring->req_event = req_prod_local + 1;
2372 		xen_mb();
2373 	} while (rxb->sring->req_prod != req_prod_local) ;
2374 }
2375 
2376 /**
2377  * Sends one packet to the ring.  Blocks until the packet is on the ring
2378  * \param[in]	mbufc	Contains one packet to send.  Caller must free
2379  * \param[in,out] rxb	The packet will be pushed onto this ring, but the
2380  * 			otherend will not be notified.
2381  * \param[in]	otherend The domain ID of the other end of the connection
2382  * \retval	EAGAIN	The ring did not have enough space for the packet.
2383  * 			The ring has not been modified
2384  * \param[in,out] gnttab Pointer to enough memory for a grant table.  We make
2385  * 			this a function parameter so that we will take less
2386  * 			stack space.
2387  * \retval EINVAL	mbufc was corrupt or not convertible into a pkt
2388  */
2389 static int
2390 xnb_send(netif_rx_back_ring_t *ring, domid_t otherend, const struct mbuf *mbufc,
2391 	 gnttab_copy_table gnttab)
2392 {
2393 	struct xnb_pkt pkt;
2394 	int error, n_entries, n_reqs;
2395 	RING_IDX space;
2396 
2397 	space = ring->sring->req_prod - ring->req_cons;
2398 	error = xnb_mbufc2pkt(mbufc, &pkt, ring->rsp_prod_pvt, space);
2399 	if (error != 0)
2400 		return error;
2401 	n_entries = xnb_rxpkt2gnttab(&pkt, mbufc, gnttab, ring, otherend);
2402 	if (n_entries != 0) {
2403 		int __unused hv_ret = HYPERVISOR_grant_table_op(GNTTABOP_copy,
2404 		    gnttab, n_entries);
2405 		KASSERT(hv_ret == 0, ("HYPERVISOR_grant_table_op returned %d\n",
2406 		    hv_ret));
2407 	}
2408 
2409 	n_reqs = xnb_rxpkt2rsp(&pkt, gnttab, n_entries, ring);
2410 
2411 	return 0;
2412 }
2413 
2414 static void
2415 xnb_start(struct ifnet *ifp)
2416 {
2417 	struct xnb_softc *xnb;
2418 
2419 	xnb = ifp->if_softc;
2420 	mtx_lock(&xnb->rx_lock);
2421 	xnb_start_locked(ifp);
2422 	mtx_unlock(&xnb->rx_lock);
2423 }
2424 
2425 /* equivalent of network_open() in Linux */
2426 static void
2427 xnb_ifinit_locked(struct xnb_softc *xnb)
2428 {
2429 	struct ifnet *ifp;
2430 
2431 	ifp = xnb->xnb_ifp;
2432 
2433 	mtx_assert(&xnb->sc_lock, MA_OWNED);
2434 
2435 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2436 		return;
2437 
2438 	xnb_stop(xnb);
2439 
2440 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2441 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2442 	if_link_state_change(ifp, LINK_STATE_UP);
2443 }
2444 
2445 
2446 static void
2447 xnb_ifinit(void *xsc)
2448 {
2449 	struct xnb_softc *xnb = xsc;
2450 
2451 	mtx_lock(&xnb->sc_lock);
2452 	xnb_ifinit_locked(xnb);
2453 	mtx_unlock(&xnb->sc_lock);
2454 }
2455 
2456 
2457 /**
2458  * Read the 'mac' node at the given device's node in the store, and parse that
2459  * as colon-separated octets, placing result the given mac array.  mac must be
2460  * a preallocated array of length ETHER_ADDR_LEN ETH_ALEN (as declared in
2461  * net/ethernet.h).
2462  * Return 0 on success, or errno on error.
2463  */
2464 static int
2465 xen_net_read_mac(device_t dev, uint8_t mac[])
2466 {
2467 	char *s, *e, *macstr;
2468 	const char *path;
2469 	int error = 0;
2470 	int i;
2471 
2472 	path = xenbus_get_node(dev);
2473 	error = xs_read(XST_NIL, path, "mac", NULL, (void **) &macstr);
2474 	if (error != 0) {
2475 		xenbus_dev_fatal(dev, error, "parsing %s/mac", path);
2476 	} else {
2477 	        s = macstr;
2478 	        for (i = 0; i < ETHER_ADDR_LEN; i++) {
2479 		        mac[i] = strtoul(s, &e, 16);
2480 		        if (s == e || (e[0] != ':' && e[0] != 0)) {
2481 				error = ENOENT;
2482 				break;
2483 		        }
2484 		        s = &e[1];
2485 	        }
2486 	        free(macstr, M_XENBUS);
2487 	}
2488 	return error;
2489 }
2490 
2491 
2492 /**
2493  * Callback used by the generic networking code to tell us when our carrier
2494  * state has changed.  Since we don't have a physical carrier, we don't care
2495  */
2496 static int
2497 xnb_ifmedia_upd(struct ifnet *ifp)
2498 {
2499 	return (0);
2500 }
2501 
2502 /**
2503  * Callback used by the generic networking code to ask us what our carrier
2504  * state is.  Since we don't have a physical carrier, this is very simple
2505  */
2506 static void
2507 xnb_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2508 {
2509 	ifmr->ifm_status = IFM_AVALID|IFM_ACTIVE;
2510 	ifmr->ifm_active = IFM_ETHER|IFM_MANUAL;
2511 }
2512 
2513 
2514 /*---------------------------- NewBus Registration ---------------------------*/
2515 static device_method_t xnb_methods[] = {
2516 	/* Device interface */
2517 	DEVMETHOD(device_probe,		xnb_probe),
2518 	DEVMETHOD(device_attach,	xnb_attach),
2519 	DEVMETHOD(device_detach,	xnb_detach),
2520 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
2521 	DEVMETHOD(device_suspend,	xnb_suspend),
2522 	DEVMETHOD(device_resume,	xnb_resume),
2523 
2524 	/* Xenbus interface */
2525 	DEVMETHOD(xenbus_otherend_changed, xnb_frontend_changed),
2526 
2527 	{ 0, 0 }
2528 };
2529 
2530 static driver_t xnb_driver = {
2531 	"xnb",
2532 	xnb_methods,
2533 	sizeof(struct xnb_softc),
2534 };
2535 devclass_t xnb_devclass;
2536 
2537 DRIVER_MODULE(xnb, xenbusb_back, xnb_driver, xnb_devclass, 0, 0);
2538 
2539 
2540 /*-------------------------- Unit Tests -------------------------------------*/
2541 #ifdef XNB_DEBUG
2542 #include "netback_unit_tests.c"
2543 #endif
2544