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