1/*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2009-2011 Spectra Logic Corporation
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions, and the following disclaimer,
12 *    without modification.
13 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
14 *    substantially similar to the "NO WARRANTY" disclaimer below
15 *    ("Disclaimer") and any redistribution must be conditioned upon
16 *    including a substantially similar Disclaimer requirement for further
17 *    binary redistribution.
18 *
19 * NO WARRANTY
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
28 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
29 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGES.
31 *
32 * Authors: Justin T. Gibbs     (Spectra Logic Corporation)
33 *          Alan Somers         (Spectra Logic Corporation)
34 *          John Suykerbuyk     (Spectra Logic Corporation)
35 */
36
37#include <sys/cdefs.h>
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
47#include <sys/param.h>
48#include <sys/kernel.h>
49
50#include <sys/bus.h>
51#include <sys/module.h>
52#include <sys/rman.h>
53#include <sys/socket.h>
54#include <sys/sockio.h>
55#include <sys/sysctl.h>
56
57#include <net/if.h>
58#include <net/if_var.h>
59#include <net/if_arp.h>
60#include <net/ethernet.h>
61#include <net/if_dl.h>
62#include <net/if_media.h>
63#include <net/if_types.h>
64
65#include <netinet/in.h>
66#include <netinet/ip.h>
67#include <netinet/if_ether.h>
68#include <netinet/tcp.h>
69#include <netinet/ip_icmp.h>
70#include <netinet/udp.h>
71#include <machine/in_cksum.h>
72
73#include <vm/vm.h>
74#include <vm/pmap.h>
75#include <vm/vm_extern.h>
76#include <vm/vm_kern.h>
77
78#include <machine/_inttypes.h>
79
80#include <xen/xen-os.h>
81#include <xen/hypervisor.h>
82#include <xen/xen_intr.h>
83#include <contrib/xen/io/netif.h>
84#include <xen/xenbus/xenbusvar.h>
85
86/*--------------------------- Compile-time Tunables --------------------------*/
87
88/*---------------------------------- Macros ----------------------------------*/
89/**
90 * Custom malloc type for all driver allocations.
91 */
92static MALLOC_DEFINE(M_XENNETBACK, "xnb", "Xen Net Back Driver Data");
93
94#define	XNB_SG	1	/* netback driver supports feature-sg */
95#define	XNB_GSO_TCPV4 0	/* netback driver supports feature-gso-tcpv4 */
96#define	XNB_RX_COPY 1	/* netback driver supports feature-rx-copy */
97#define	XNB_RX_FLIP 0	/* netback driver does not support feature-rx-flip */
98
99#undef XNB_DEBUG
100#define	XNB_DEBUG /* hardcode on during development */
101
102#ifdef XNB_DEBUG
103#define	DPRINTF(fmt, args...) \
104	printf("xnb(%s:%d): " fmt, __FUNCTION__, __LINE__, ##args)
105#else
106#define	DPRINTF(fmt, args...) do {} while (0)
107#endif
108
109/* Default length for stack-allocated grant tables */
110#define	GNTTAB_LEN	(64)
111
112/* Features supported by all backends.  TSO and LRO can be negotiated */
113#define	XNB_CSUM_FEATURES	(CSUM_TCP | CSUM_UDP)
114
115#define	NET_TX_RING_SIZE __RING_SIZE((netif_tx_sring_t *)0, PAGE_SIZE)
116#define	NET_RX_RING_SIZE __RING_SIZE((netif_rx_sring_t *)0, PAGE_SIZE)
117
118/**
119 * Two argument version of the standard macro.  Second argument is a tentative
120 * value of req_cons
121 */
122#define	RING_HAS_UNCONSUMED_REQUESTS_2(_r, cons) ({                     \
123	unsigned int req = (_r)->sring->req_prod - cons;          	\
124	unsigned int rsp = RING_SIZE(_r) -                              \
125	(cons - (_r)->rsp_prod_pvt);                          		\
126	req < rsp ? req : rsp;                                          \
127})
128
129#define	virt_to_mfn(x) (vtophys(x) >> PAGE_SHIFT)
130#define	virt_to_offset(x) ((x) & (PAGE_SIZE - 1))
131
132/**
133 * Predefined array type of grant table copy descriptors.  Used to pass around
134 * statically allocated memory structures.
135 */
136typedef struct gnttab_copy gnttab_copy_table[GNTTAB_LEN];
137
138/*--------------------------- Forward Declarations ---------------------------*/
139struct xnb_softc;
140struct xnb_pkt;
141
142static void	xnb_attach_failed(struct xnb_softc *xnb,
143				  int err, const char *fmt, ...)
144				  __printflike(3,4);
145static int	xnb_shutdown(struct xnb_softc *xnb);
146static int	create_netdev(device_t dev);
147static int	xnb_detach(device_t dev);
148static int	xnb_ifmedia_upd(if_t ifp);
149static void	xnb_ifmedia_sts(if_t ifp, struct ifmediareq *ifmr);
150static void 	xnb_intr(void *arg);
151static int	xnb_send(netif_rx_back_ring_t *rxb, domid_t otherend,
152			 const struct mbuf *mbufc, gnttab_copy_table gnttab);
153static int	xnb_recv(netif_tx_back_ring_t *txb, domid_t otherend,
154			 struct mbuf **mbufc, if_t ifnet,
155			 gnttab_copy_table gnttab);
156static int	xnb_ring2pkt(struct xnb_pkt *pkt,
157			     const netif_tx_back_ring_t *tx_ring,
158			     RING_IDX start);
159static void	xnb_txpkt2rsp(const struct xnb_pkt *pkt,
160			      netif_tx_back_ring_t *ring, int error);
161static struct mbuf *xnb_pkt2mbufc(const struct xnb_pkt *pkt, if_t ifp);
162static int	xnb_txpkt2gnttab(const struct xnb_pkt *pkt,
163				 struct mbuf *mbufc,
164				 gnttab_copy_table gnttab,
165				 const netif_tx_back_ring_t *txb,
166				 domid_t otherend_id);
167static void	xnb_update_mbufc(struct mbuf *mbufc,
168				 const gnttab_copy_table gnttab, int n_entries);
169static int	xnb_mbufc2pkt(const struct mbuf *mbufc,
170			      struct xnb_pkt *pkt,
171			      RING_IDX start, int space);
172static int	xnb_rxpkt2gnttab(const struct xnb_pkt *pkt,
173				 const struct mbuf *mbufc,
174				 gnttab_copy_table gnttab,
175				 const netif_rx_back_ring_t *rxb,
176				 domid_t otherend_id);
177static int	xnb_rxpkt2rsp(const struct xnb_pkt *pkt,
178			      const gnttab_copy_table gnttab, int n_entries,
179			      netif_rx_back_ring_t *ring);
180static void	xnb_stop(struct xnb_softc*);
181static int	xnb_ioctl(if_t, u_long, caddr_t);
182static void	xnb_start_locked(if_t);
183static void	xnb_start(if_t);
184static void	xnb_ifinit_locked(struct xnb_softc*);
185static void	xnb_ifinit(void*);
186#ifdef XNB_DEBUG
187static int	xnb_unit_test_main(SYSCTL_HANDLER_ARGS);
188static int	xnb_dump_rings(SYSCTL_HANDLER_ARGS);
189#endif
190#if defined(INET) || defined(INET6)
191static void	xnb_add_mbuf_cksum(struct mbuf *mbufc);
192#endif
193/*------------------------------ Data Structures -----------------------------*/
194
195/**
196 * Representation of a xennet packet.  Simplified version of a packet as
197 * stored in the Xen tx ring.  Applicable to both RX and TX packets
198 */
199struct xnb_pkt{
200	/**
201	 * Array index of the first data-bearing (eg, not extra info) entry
202	 * for this packet
203	 */
204	RING_IDX	car;
205
206	/**
207	 * Array index of the second data-bearing entry for this packet.
208	 * Invalid if the packet has only one data-bearing entry.  If the
209	 * packet has more than two data-bearing entries, then the second
210	 * through the last will be sequential modulo the ring size
211	 */
212	RING_IDX	cdr;
213
214	/**
215	 * Optional extra info.  Only valid if flags contains
216	 * NETTXF_extra_info.  Note that extra.type will always be
217	 * XEN_NETIF_EXTRA_TYPE_GSO.  Currently, no known netfront or netback
218	 * driver will ever set XEN_NETIF_EXTRA_TYPE_MCAST_*
219	 */
220	netif_extra_info_t extra;
221
222	/** Size of entire packet in bytes.       */
223	uint16_t	size;
224
225	/** The size of the first entry's data in bytes */
226	uint16_t	car_size;
227
228	/**
229	 * Either NETTXF_ or NETRXF_ flags.  Note that the flag values are
230	 * not the same for TX and RX packets
231	 */
232	uint16_t	flags;
233
234	/**
235	 * The number of valid data-bearing entries (either netif_tx_request's
236	 * or netif_rx_response's) in the packet.  If this is 0, it means the
237	 * entire packet is invalid.
238	 */
239	uint16_t	list_len;
240
241	/** There was an error processing the packet */
242	uint8_t		error;
243};
244
245/** xnb_pkt method: initialize it */
246static inline void
247xnb_pkt_initialize(struct xnb_pkt *pxnb)
248{
249	bzero(pxnb, sizeof(*pxnb));
250}
251
252/** xnb_pkt method: mark the packet as valid */
253static inline void
254xnb_pkt_validate(struct xnb_pkt *pxnb)
255{
256	pxnb->error = 0;
257};
258
259/** xnb_pkt method: mark the packet as invalid */
260static inline void
261xnb_pkt_invalidate(struct xnb_pkt *pxnb)
262{
263	pxnb->error = 1;
264};
265
266/** xnb_pkt method: Check whether the packet is valid */
267static inline int
268xnb_pkt_is_valid(const struct xnb_pkt *pxnb)
269{
270	return (! pxnb->error);
271}
272
273#ifdef XNB_DEBUG
274/** xnb_pkt method: print the packet's contents in human-readable format*/
275static void __unused
276xnb_dump_pkt(const struct xnb_pkt *pkt) {
277	if (pkt == NULL) {
278	  DPRINTF("Was passed a null pointer.\n");
279	  return;
280	}
281	DPRINTF("pkt address= %p\n", pkt);
282	DPRINTF("pkt->size=%d\n", pkt->size);
283	DPRINTF("pkt->car_size=%d\n", pkt->car_size);
284	DPRINTF("pkt->flags=0x%04x\n", pkt->flags);
285	DPRINTF("pkt->list_len=%d\n", pkt->list_len);
286	/* DPRINTF("pkt->extra");	TODO */
287	DPRINTF("pkt->car=%d\n", pkt->car);
288	DPRINTF("pkt->cdr=%d\n", pkt->cdr);
289	DPRINTF("pkt->error=%d\n", pkt->error);
290}
291#endif /* XNB_DEBUG */
292
293static void
294xnb_dump_txreq(RING_IDX idx, const struct netif_tx_request *txreq)
295{
296	if (txreq != NULL) {
297		DPRINTF("netif_tx_request index =%u\n", idx);
298		DPRINTF("netif_tx_request.gref  =%u\n", txreq->gref);
299		DPRINTF("netif_tx_request.offset=%hu\n", txreq->offset);
300		DPRINTF("netif_tx_request.flags =%hu\n", txreq->flags);
301		DPRINTF("netif_tx_request.id    =%hu\n", txreq->id);
302		DPRINTF("netif_tx_request.size  =%hu\n", txreq->size);
303	}
304}
305
306/**
307 * \brief Configuration data for a shared memory request ring
308 *        used to communicate with the front-end client of this
309 *        this driver.
310 */
311struct xnb_ring_config {
312	/**
313	 * Runtime structures for ring access.  Unfortunately, TX and RX rings
314	 * use different data structures, and that cannot be changed since it
315	 * is part of the interdomain protocol.
316	 */
317	union{
318		netif_rx_back_ring_t	  rx_ring;
319		netif_tx_back_ring_t	  tx_ring;
320	} back_ring;
321
322	/**
323	 * The device bus address returned by the hypervisor when
324	 * mapping the ring and required to unmap it when a connection
325	 * is torn down.
326	 */
327	uint64_t	bus_addr;
328
329	/** The pseudo-physical address where ring memory is mapped.*/
330	uint64_t	gnt_addr;
331
332	/** KVA address where ring memory is mapped. */
333	vm_offset_t	va;
334
335	/**
336	 * Grant table handles, one per-ring page, returned by the
337	 * hyperpervisor upon mapping of the ring and required to
338	 * unmap it when a connection is torn down.
339	 */
340	grant_handle_t	handle;
341
342	/** The number of ring pages mapped for the current connection. */
343	unsigned	ring_pages;
344
345	/**
346	 * The grant references, one per-ring page, supplied by the
347	 * front-end, allowing us to reference the ring pages in the
348	 * front-end's domain and to map these pages into our own domain.
349	 */
350	grant_ref_t	ring_ref;
351};
352
353/**
354 * Per-instance connection state flags.
355 */
356typedef enum
357{
358	/** Communication with the front-end has been established. */
359	XNBF_RING_CONNECTED    = 0x01,
360
361	/**
362	 * Front-end requests exist in the ring and are waiting for
363	 * xnb_xen_req objects to free up.
364	 */
365	XNBF_RESOURCE_SHORTAGE = 0x02,
366
367	/** Connection teardown has started. */
368	XNBF_SHUTDOWN          = 0x04,
369
370	/** A thread is already performing shutdown processing. */
371	XNBF_IN_SHUTDOWN       = 0x08
372} xnb_flag_t;
373
374/**
375 * Types of rings.  Used for array indices and to identify a ring's control
376 * data structure type
377 */
378typedef enum{
379	XNB_RING_TYPE_TX = 0,	/* ID of TX rings, used for array indices */
380	XNB_RING_TYPE_RX = 1,	/* ID of RX rings, used for array indices */
381	XNB_NUM_RING_TYPES
382} xnb_ring_type_t;
383
384/**
385 * Per-instance configuration data.
386 */
387struct xnb_softc {
388	/** NewBus device corresponding to this instance. */
389	device_t		dev;
390
391	/* Media related fields */
392
393	/** Generic network media state */
394	struct ifmedia		sc_media;
395
396	/** Media carrier info */
397	if_t			xnb_ifp;
398
399	/** Our own private carrier state */
400	unsigned carrier;
401
402	/** Device MAC Address */
403	uint8_t			mac[ETHER_ADDR_LEN];
404
405	/* Xen related fields */
406
407	/**
408	 * \brief The netif protocol abi in effect.
409	 *
410	 * There are situations where the back and front ends can
411	 * have a different, native abi (e.g. intel x86_64 and
412	 * 32bit x86 domains on the same machine).  The back-end
413	 * always accommodates the front-end's native abi.  That
414	 * value is pulled from the XenStore and recorded here.
415	 */
416	int			abi;
417
418	/**
419	 * Name of the bridge to which this VIF is connected, if any
420	 * This field is dynamically allocated by xenbus and must be free()ed
421	 * when no longer needed
422	 */
423	char			*bridge;
424
425	/** The interrupt driven even channel used to signal ring events. */
426	evtchn_port_t		evtchn;
427
428	/** Xen device handle.*/
429	long 			handle;
430
431	/** Handle to the communication ring event channel. */
432	xen_intr_handle_t	xen_intr_handle;
433
434	/**
435	 * \brief Cached value of the front-end's domain id.
436	 *
437	 * This value is used at once for each mapped page in
438	 * a transaction.  We cache it to avoid incuring the
439	 * cost of an ivar access every time this is needed.
440	 */
441	domid_t			otherend_id;
442
443	/**
444	 * Undocumented frontend feature.  Has something to do with
445	 * scatter/gather IO
446	 */
447	uint8_t			can_sg;
448	/** Undocumented frontend feature */
449	uint8_t			gso;
450	/** Undocumented frontend feature */
451	uint8_t			gso_prefix;
452	/** Can checksum TCP/UDP over IPv4 */
453	uint8_t			ip_csum;
454
455	/* Implementation related fields */
456	/**
457	 * Preallocated grant table copy descriptor for RX operations.
458	 * Access must be protected by rx_lock
459	 */
460	gnttab_copy_table	rx_gnttab;
461
462	/**
463	 * Preallocated grant table copy descriptor for TX operations.
464	 * Access must be protected by tx_lock
465	 */
466	gnttab_copy_table	tx_gnttab;
467
468	/**
469	 * Resource representing allocated physical address space
470	 * associated with our per-instance kva region.
471	 */
472	struct resource		*pseudo_phys_res;
473
474	/** Resource id for allocated physical address space. */
475	int			pseudo_phys_res_id;
476
477	/** Ring mapping and interrupt configuration data. */
478	struct xnb_ring_config	ring_configs[XNB_NUM_RING_TYPES];
479
480	/**
481	 * Global pool of kva used for mapping remote domain ring
482	 * and I/O transaction data.
483	 */
484	vm_offset_t		kva;
485
486	/** Pseudo-physical address corresponding to kva. */
487	uint64_t		gnt_base_addr;
488
489	/** Various configuration and state bit flags. */
490	xnb_flag_t		flags;
491
492	/** Mutex protecting per-instance data in the receive path. */
493	struct mtx		rx_lock;
494
495	/** Mutex protecting per-instance data in the softc structure. */
496	struct mtx		sc_lock;
497
498	/** Mutex protecting per-instance data in the transmit path. */
499	struct mtx		tx_lock;
500
501	/** The size of the global kva pool. */
502	int			kva_size;
503
504	/** Name of the interface */
505	char			 if_name[IFNAMSIZ];
506};
507
508/*---------------------------- Debugging functions ---------------------------*/
509#ifdef XNB_DEBUG
510static void __unused
511xnb_dump_gnttab_copy(const struct gnttab_copy *entry)
512{
513	if (entry == NULL) {
514		printf("NULL grant table pointer\n");
515		return;
516	}
517
518	if (entry->flags & GNTCOPY_dest_gref)
519		printf("gnttab dest ref=\t%u\n", entry->dest.u.ref);
520	else
521		printf("gnttab dest gmfn=\t%"PRI_xen_pfn"\n",
522		       entry->dest.u.gmfn);
523	printf("gnttab dest offset=\t%hu\n", entry->dest.offset);
524	printf("gnttab dest domid=\t%hu\n", entry->dest.domid);
525	if (entry->flags & GNTCOPY_source_gref)
526		printf("gnttab source ref=\t%u\n", entry->source.u.ref);
527	else
528		printf("gnttab source gmfn=\t%"PRI_xen_pfn"\n",
529		       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, (int)m->m_pkthdr.csum_flags,
589		       m->m_pkthdr.csum_data, m->m_pkthdr.tso_segsz);
590		printf("    rcvif=%16p,  len=%19d\n",
591		       m->m_pkthdr.rcvif, 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=%18u\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		if (xnb->pseudo_phys_res != NULL) {
622			xenmem_free(xnb->dev, xnb->pseudo_phys_res_id,
623			    xnb->pseudo_phys_res);
624			xnb->pseudo_phys_res = NULL;
625		}
626	}
627	xnb->kva = 0;
628	xnb->gnt_base_addr = 0;
629}
630
631/**
632 * Cleanup all inter-domain communication mechanisms.
633 *
634 * \param xnb  Per-instance xnb configuration structure.
635 */
636static int
637xnb_disconnect(struct xnb_softc *xnb)
638{
639	struct gnttab_unmap_grant_ref gnts[XNB_NUM_RING_TYPES];
640	int error __diagused;
641	int i;
642
643	if (xnb->xen_intr_handle != NULL)
644		xen_intr_unbind(&xnb->xen_intr_handle);
645
646	/*
647	 * We may still have another thread currently processing requests.  We
648	 * must acquire the rx and tx locks to make sure those threads are done,
649	 * but we can release those locks as soon as we acquire them, because no
650	 * more interrupts will be arriving.
651	 */
652	mtx_lock(&xnb->tx_lock);
653	mtx_unlock(&xnb->tx_lock);
654	mtx_lock(&xnb->rx_lock);
655	mtx_unlock(&xnb->rx_lock);
656
657	mtx_lock(&xnb->sc_lock);
658	/* Free malloc'd softc member variables */
659	if (xnb->bridge != NULL) {
660		free(xnb->bridge, M_XENSTORE);
661		xnb->bridge = NULL;
662	}
663
664	/* All request processing has stopped, so unmap the rings */
665	for (i=0; i < XNB_NUM_RING_TYPES; i++) {
666		gnts[i].host_addr = xnb->ring_configs[i].gnt_addr;
667		gnts[i].dev_bus_addr = xnb->ring_configs[i].bus_addr;
668		gnts[i].handle = xnb->ring_configs[i].handle;
669	}
670	error = HYPERVISOR_grant_table_op(GNTTABOP_unmap_grant_ref, gnts,
671					  XNB_NUM_RING_TYPES);
672	KASSERT(error == 0, ("Grant table unmap op failed (%d)", error));
673
674	xnb_free_communication_mem(xnb);
675	/*
676	 * Zero the ring config structs because the pointers, handles, and
677	 * grant refs contained therein are no longer valid.
678	 */
679	bzero(&xnb->ring_configs[XNB_RING_TYPE_TX],
680	    sizeof(struct xnb_ring_config));
681	bzero(&xnb->ring_configs[XNB_RING_TYPE_RX],
682	    sizeof(struct xnb_ring_config));
683
684	xnb->flags &= ~XNBF_RING_CONNECTED;
685	mtx_unlock(&xnb->sc_lock);
686
687	return (0);
688}
689
690/**
691 * Map a single shared memory ring into domain local address space and
692 * initialize its control structure
693 *
694 * \param xnb	Per-instance xnb configuration structure
695 * \param ring_type	Array index of this ring in the xnb's array of rings
696 * \return 	An errno
697 */
698static int
699xnb_connect_ring(struct xnb_softc *xnb, xnb_ring_type_t ring_type)
700{
701	struct gnttab_map_grant_ref gnt;
702	struct xnb_ring_config *ring = &xnb->ring_configs[ring_type];
703	int error;
704
705	/* TX ring type = 0, RX =1 */
706	ring->va = xnb->kva + ring_type * PAGE_SIZE;
707	ring->gnt_addr = xnb->gnt_base_addr + ring_type * PAGE_SIZE;
708
709	gnt.host_addr = ring->gnt_addr;
710	gnt.flags     = GNTMAP_host_map;
711	gnt.ref       = ring->ring_ref;
712	gnt.dom       = xnb->otherend_id;
713
714	error = HYPERVISOR_grant_table_op(GNTTABOP_map_grant_ref, &gnt, 1);
715	if (error != 0)
716		panic("netback: Ring page grant table op failed (%d)", error);
717
718	if (gnt.status != 0) {
719		ring->va = 0;
720		error = EACCES;
721		xenbus_dev_fatal(xnb->dev, error,
722				 "Ring shared page mapping failed. "
723				 "Status %d.", gnt.status);
724	} else {
725		ring->handle = gnt.handle;
726		ring->bus_addr = gnt.dev_bus_addr;
727
728		if (ring_type == XNB_RING_TYPE_TX) {
729			BACK_RING_INIT(&ring->back_ring.tx_ring,
730			    (netif_tx_sring_t*)ring->va,
731			    ring->ring_pages * PAGE_SIZE);
732		} else if (ring_type == XNB_RING_TYPE_RX) {
733			BACK_RING_INIT(&ring->back_ring.rx_ring,
734			    (netif_rx_sring_t*)ring->va,
735			    ring->ring_pages * PAGE_SIZE);
736		} else {
737			xenbus_dev_fatal(xnb->dev, error,
738				 "Unknown ring type %d", ring_type);
739		}
740	}
741
742	return error;
743}
744
745/**
746 * Setup the shared memory rings and bind an interrupt to the event channel
747 * used to notify us of ring changes.
748 *
749 * \param xnb  Per-instance xnb configuration structure.
750 */
751static int
752xnb_connect_comms(struct xnb_softc *xnb)
753{
754	int	error;
755	xnb_ring_type_t i;
756
757	if ((xnb->flags & XNBF_RING_CONNECTED) != 0)
758		return (0);
759
760	/*
761	 * Kva for our rings are at the tail of the region of kva allocated
762	 * by xnb_alloc_communication_mem().
763	 */
764	for (i=0; i < XNB_NUM_RING_TYPES; i++) {
765		error = xnb_connect_ring(xnb, i);
766		if (error != 0)
767	  		return error;
768	}
769
770	xnb->flags |= XNBF_RING_CONNECTED;
771
772	error = xen_intr_bind_remote_port(xnb->dev,
773					  xnb->otherend_id,
774					  xnb->evtchn,
775					  /*filter*/NULL,
776					  xnb_intr, /*arg*/xnb,
777					  INTR_TYPE_NET | INTR_MPSAFE,
778					  &xnb->xen_intr_handle);
779	if (error != 0) {
780		(void)xnb_disconnect(xnb);
781		xenbus_dev_fatal(xnb->dev, error, "binding event channel");
782		return (error);
783	}
784
785	DPRINTF("rings connected!\n");
786
787	return (0);
788}
789
790/**
791 * Size KVA and pseudo-physical address allocations based on negotiated
792 * values for the size and number of I/O requests, and the size of our
793 * communication ring.
794 *
795 * \param xnb  Per-instance xnb configuration structure.
796 *
797 * These address spaces are used to dynamically map pages in the
798 * front-end's domain into our own.
799 */
800static int
801xnb_alloc_communication_mem(struct xnb_softc *xnb)
802{
803	xnb_ring_type_t i;
804
805	xnb->kva_size = 0;
806	for (i=0; i < XNB_NUM_RING_TYPES; i++) {
807		xnb->kva_size += xnb->ring_configs[i].ring_pages * PAGE_SIZE;
808	}
809
810	/*
811	 * Reserve a range of pseudo physical memory that we can map
812	 * into kva.  These pages will only be backed by machine
813	 * pages ("real memory") during the lifetime of front-end requests
814	 * via grant table operations.  We will map the netif tx and rx rings
815	 * into this space.
816	 */
817	xnb->pseudo_phys_res_id = 0;
818	xnb->pseudo_phys_res = xenmem_alloc(xnb->dev, &xnb->pseudo_phys_res_id,
819	    xnb->kva_size);
820	if (xnb->pseudo_phys_res == NULL) {
821		xnb->kva = 0;
822		return (ENOMEM);
823	}
824	xnb->kva = (vm_offset_t)rman_get_virtual(xnb->pseudo_phys_res);
825	xnb->gnt_base_addr = rman_get_start(xnb->pseudo_phys_res);
826	return (0);
827}
828
829/**
830 * Collect information from the XenStore related to our device and its frontend
831 *
832 * \param xnb  Per-instance xnb configuration structure.
833 */
834static int
835xnb_collect_xenstore_info(struct xnb_softc *xnb)
836{
837	/**
838	 * \todo Linux collects the following info.  We should collect most
839	 * of this, too:
840	 * "feature-rx-notify"
841	 */
842	const char *otherend_path;
843	const char *our_path;
844	int err;
845	unsigned int rx_copy, bridge_len;
846	uint8_t no_csum_offload;
847
848	otherend_path = xenbus_get_otherend_path(xnb->dev);
849	our_path = xenbus_get_node(xnb->dev);
850
851	/* Collect the critical communication parameters */
852	err = xs_gather(XST_NIL, otherend_path,
853	    "tx-ring-ref", "%l" PRIu32,
854	    	&xnb->ring_configs[XNB_RING_TYPE_TX].ring_ref,
855	    "rx-ring-ref", "%l" PRIu32,
856	    	&xnb->ring_configs[XNB_RING_TYPE_RX].ring_ref,
857	    "event-channel", "%" PRIu32, &xnb->evtchn,
858	    NULL);
859	if (err != 0) {
860		xenbus_dev_fatal(xnb->dev, err,
861				 "Unable to retrieve ring information from "
862				 "frontend %s.  Unable to connect.",
863				 otherend_path);
864		return (err);
865	}
866
867	/* Collect the handle from xenstore */
868	err = xs_scanf(XST_NIL, our_path, "handle", NULL, "%li", &xnb->handle);
869	if (err != 0) {
870		xenbus_dev_fatal(xnb->dev, err,
871		    "Error reading handle from frontend %s.  "
872		    "Unable to connect.", otherend_path);
873	}
874
875	/*
876	 * Collect the bridgename, if any.  We do not need bridge_len; we just
877	 * throw it away
878	 */
879	err = xs_read(XST_NIL, our_path, "bridge", &bridge_len,
880		      (void**)&xnb->bridge);
881	if (err != 0)
882		xnb->bridge = NULL;
883
884	/*
885	 * Does the frontend request that we use rx copy?  If not, return an
886	 * error because this driver only supports rx copy.
887	 */
888	err = xs_scanf(XST_NIL, otherend_path, "request-rx-copy", NULL,
889		       "%" PRIu32, &rx_copy);
890	if (err == ENOENT) {
891		err = 0;
892	 	rx_copy = 0;
893	}
894	if (err < 0) {
895		xenbus_dev_fatal(xnb->dev, err, "reading %s/request-rx-copy",
896				 otherend_path);
897		return err;
898	}
899	/**
900	 * \todo: figure out the exact meaning of this feature, and when
901	 * the frontend will set it to true.  It should be set to true
902	 * at some point
903	 */
904/*        if (!rx_copy)*/
905/*          return EOPNOTSUPP;*/
906
907	/** \todo Collect the rx notify feature */
908
909	/*  Collect the feature-sg. */
910	if (xs_scanf(XST_NIL, otherend_path, "feature-sg", NULL,
911		     "%hhu", &xnb->can_sg) < 0)
912		xnb->can_sg = 0;
913
914	/* Collect remaining frontend features */
915	if (xs_scanf(XST_NIL, otherend_path, "feature-gso-tcpv4", NULL,
916		     "%hhu", &xnb->gso) < 0)
917		xnb->gso = 0;
918
919	if (xs_scanf(XST_NIL, otherend_path, "feature-gso-tcpv4-prefix", NULL,
920		     "%hhu", &xnb->gso_prefix) < 0)
921		xnb->gso_prefix = 0;
922
923	if (xs_scanf(XST_NIL, otherend_path, "feature-no-csum-offload", NULL,
924		     "%hhu", &no_csum_offload) < 0)
925		no_csum_offload = 0;
926	xnb->ip_csum = (no_csum_offload == 0);
927
928	return (0);
929}
930
931/**
932 * Supply information about the physical device to the frontend
933 * via XenBus.
934 *
935 * \param xnb  Per-instance xnb configuration structure.
936 */
937static int
938xnb_publish_backend_info(struct xnb_softc *xnb)
939{
940	struct xs_transaction xst;
941	const char *our_path;
942	int error;
943
944	our_path = xenbus_get_node(xnb->dev);
945
946	do {
947		error = xs_transaction_start(&xst);
948		if (error != 0) {
949			xenbus_dev_fatal(xnb->dev, error,
950					 "Error publishing backend info "
951					 "(start transaction)");
952			break;
953		}
954
955		error = xs_printf(xst, our_path, "feature-sg",
956				  "%d", XNB_SG);
957		if (error != 0)
958			break;
959
960		error = xs_printf(xst, our_path, "feature-gso-tcpv4",
961				  "%d", XNB_GSO_TCPV4);
962		if (error != 0)
963			break;
964
965		error = xs_printf(xst, our_path, "feature-rx-copy",
966				  "%d", XNB_RX_COPY);
967		if (error != 0)
968			break;
969
970		error = xs_printf(xst, our_path, "feature-rx-flip",
971				  "%d", XNB_RX_FLIP);
972		if (error != 0)
973			break;
974
975		error = xs_transaction_end(xst, 0);
976		if (error != 0 && error != EAGAIN) {
977			xenbus_dev_fatal(xnb->dev, error, "ending transaction");
978			break;
979		}
980
981	} while (error == EAGAIN);
982
983	return (error);
984}
985
986/**
987 * Connect to our netfront peer now that it has completed publishing
988 * its configuration into the XenStore.
989 *
990 * \param xnb  Per-instance xnb configuration structure.
991 */
992static void
993xnb_connect(struct xnb_softc *xnb)
994{
995	int	error;
996
997	if (xenbus_get_state(xnb->dev) == XenbusStateConnected)
998		return;
999
1000	if (xnb_collect_xenstore_info(xnb) != 0)
1001		return;
1002
1003	xnb->flags &= ~XNBF_SHUTDOWN;
1004
1005	/* Read front end configuration. */
1006
1007	/* Allocate resources whose size depends on front-end configuration. */
1008	error = xnb_alloc_communication_mem(xnb);
1009	if (error != 0) {
1010		xenbus_dev_fatal(xnb->dev, error,
1011				 "Unable to allocate communication memory");
1012		return;
1013	}
1014
1015	/*
1016	 * Connect communication channel.
1017	 */
1018	error = xnb_connect_comms(xnb);
1019	if (error != 0) {
1020		/* Specific errors are reported by xnb_connect_comms(). */
1021		return;
1022	}
1023	xnb->carrier = 1;
1024
1025	/* Ready for I/O. */
1026	xenbus_set_state(xnb->dev, XenbusStateConnected);
1027}
1028
1029/*-------------------------- Device Teardown Support -------------------------*/
1030/**
1031 * Perform device shutdown functions.
1032 *
1033 * \param xnb  Per-instance xnb configuration structure.
1034 *
1035 * Mark this instance as shutting down, wait for any active requests
1036 * to drain, disconnect from the front-end, and notify any waiters (e.g.
1037 * a thread invoking our detach method) that detach can now proceed.
1038 */
1039static int
1040xnb_shutdown(struct xnb_softc *xnb)
1041{
1042	/*
1043	 * Due to the need to drop our mutex during some
1044	 * xenbus operations, it is possible for two threads
1045	 * to attempt to close out shutdown processing at
1046	 * the same time.  Tell the caller that hits this
1047	 * race to try back later.
1048	 */
1049	if ((xnb->flags & XNBF_IN_SHUTDOWN) != 0)
1050		return (EAGAIN);
1051
1052	xnb->flags |= XNBF_SHUTDOWN;
1053
1054	xnb->flags |= XNBF_IN_SHUTDOWN;
1055
1056	mtx_unlock(&xnb->sc_lock);
1057	/* Free the network interface */
1058	xnb->carrier = 0;
1059	if (xnb->xnb_ifp != NULL) {
1060		ether_ifdetach(xnb->xnb_ifp);
1061		if_free(xnb->xnb_ifp);
1062		xnb->xnb_ifp = NULL;
1063	}
1064
1065	xnb_disconnect(xnb);
1066
1067	if (xenbus_get_state(xnb->dev) < XenbusStateClosing)
1068		xenbus_set_state(xnb->dev, XenbusStateClosing);
1069	mtx_lock(&xnb->sc_lock);
1070
1071	xnb->flags &= ~XNBF_IN_SHUTDOWN;
1072
1073	/* Indicate to xnb_detach() that is it safe to proceed. */
1074	wakeup(xnb);
1075
1076	return (0);
1077}
1078
1079/**
1080 * Report an attach time error to the console and Xen, and cleanup
1081 * this instance by forcing immediate detach processing.
1082 *
1083 * \param xnb  Per-instance xnb configuration structure.
1084 * \param err  Errno describing the error.
1085 * \param fmt  Printf style format and arguments
1086 */
1087static void
1088xnb_attach_failed(struct xnb_softc *xnb, int err, const char *fmt, ...)
1089{
1090	va_list ap;
1091	va_list ap_hotplug;
1092
1093	va_start(ap, fmt);
1094	va_copy(ap_hotplug, ap);
1095	xs_vprintf(XST_NIL, xenbus_get_node(xnb->dev),
1096		  "hotplug-error", fmt, ap_hotplug);
1097	va_end(ap_hotplug);
1098	(void)xs_printf(XST_NIL, xenbus_get_node(xnb->dev),
1099		  "hotplug-status", "error");
1100
1101	xenbus_dev_vfatal(xnb->dev, err, fmt, ap);
1102	va_end(ap);
1103
1104	(void)xs_printf(XST_NIL, xenbus_get_node(xnb->dev), "online", "0");
1105	xnb_detach(xnb->dev);
1106}
1107
1108/*---------------------------- NewBus Entrypoints ----------------------------*/
1109/**
1110 * Inspect a XenBus device and claim it if is of the appropriate type.
1111 *
1112 * \param dev  NewBus device object representing a candidate XenBus device.
1113 *
1114 * \return  0 for success, errno codes for failure.
1115 */
1116static int
1117xnb_probe(device_t dev)
1118{
1119	 if (!strcmp(xenbus_get_type(dev), "vif")) {
1120		DPRINTF("Claiming device %d, %s\n", device_get_unit(dev),
1121		    devclass_get_name(device_get_devclass(dev)));
1122		device_set_desc(dev, "Backend Virtual Network Device");
1123		device_quiet(dev);
1124		return (0);
1125	}
1126	return (ENXIO);
1127}
1128
1129/**
1130 * Setup sysctl variables to control various Network Back parameters.
1131 *
1132 * \param xnb  Xen Net Back softc.
1133 *
1134 */
1135static void
1136xnb_setup_sysctl(struct xnb_softc *xnb)
1137{
1138	struct sysctl_ctx_list *sysctl_ctx = NULL;
1139	struct sysctl_oid      *sysctl_tree = NULL;
1140
1141	sysctl_ctx = device_get_sysctl_ctx(xnb->dev);
1142	if (sysctl_ctx == NULL)
1143		return;
1144
1145	sysctl_tree = device_get_sysctl_tree(xnb->dev);
1146	if (sysctl_tree == NULL)
1147		return;
1148
1149#ifdef XNB_DEBUG
1150	SYSCTL_ADD_PROC(sysctl_ctx,
1151			SYSCTL_CHILDREN(sysctl_tree),
1152			OID_AUTO,
1153			"unit_test_results",
1154			CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
1155			xnb,
1156			0,
1157			xnb_unit_test_main,
1158			"A",
1159			"Results of builtin unit tests");
1160
1161	SYSCTL_ADD_PROC(sysctl_ctx,
1162			SYSCTL_CHILDREN(sysctl_tree),
1163			OID_AUTO,
1164			"dump_rings",
1165			CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
1166			xnb,
1167			0,
1168			xnb_dump_rings,
1169			"A",
1170			"Xennet Back Rings");
1171#endif /* XNB_DEBUG */
1172}
1173
1174/**
1175 * Create a network device.
1176 * @param handle device handle
1177 */
1178int
1179create_netdev(device_t dev)
1180{
1181	if_t ifp;
1182	struct xnb_softc *xnb;
1183	int err = 0;
1184	uint32_t handle;
1185
1186	xnb = device_get_softc(dev);
1187	mtx_init(&xnb->sc_lock, "xnb_softc", "xen netback softc lock", MTX_DEF);
1188	mtx_init(&xnb->tx_lock, "xnb_tx", "xen netback tx lock", MTX_DEF);
1189	mtx_init(&xnb->rx_lock, "xnb_rx", "xen netback rx lock", MTX_DEF);
1190
1191	xnb->dev = dev;
1192
1193	ifmedia_init(&xnb->sc_media, 0, xnb_ifmedia_upd, xnb_ifmedia_sts);
1194	ifmedia_add(&xnb->sc_media, IFM_ETHER|IFM_MANUAL, 0, NULL);
1195	ifmedia_set(&xnb->sc_media, IFM_ETHER|IFM_MANUAL);
1196
1197	/*
1198	 * Set the MAC address to a dummy value (00:00:00:00:00),
1199	 * if the MAC address of the host-facing interface is set
1200	 * to the same as the guest-facing one (the value found in
1201	 * xenstore), the bridge would stop delivering packets to
1202	 * us because it would see that the destination address of
1203	 * the packet is the same as the interface, and so the bridge
1204	 * would expect the packet has already been delivered locally
1205	 * (and just drop it).
1206	 */
1207	bzero(&xnb->mac[0], sizeof(xnb->mac));
1208
1209	/* The interface will be named using the following nomenclature:
1210	 *
1211	 * xnb<domid>.<handle>
1212	 *
1213	 * Where handle is the oder of the interface referred to the guest.
1214	 */
1215	err = xs_scanf(XST_NIL, xenbus_get_node(xnb->dev), "handle", NULL,
1216		       "%" PRIu32, &handle);
1217	if (err != 0)
1218		return (err);
1219	snprintf(xnb->if_name, IFNAMSIZ, "xnb%" PRIu16 ".%" PRIu32,
1220	    xenbus_get_otherend_id(dev), handle);
1221
1222	if (err == 0) {
1223		/* Set up ifnet structure */
1224		ifp = xnb->xnb_ifp = if_alloc(IFT_ETHER);
1225		if_setsoftc(ifp, xnb);
1226		if_initname(ifp, xnb->if_name,  IF_DUNIT_NONE);
1227		if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
1228		if_setioctlfn(ifp, xnb_ioctl);
1229		if_setstartfn(ifp, xnb_start);
1230		if_setinitfn(ifp, xnb_ifinit);
1231		if_setmtu(ifp, ETHERMTU);
1232		if_setsendqlen(ifp, NET_RX_RING_SIZE - 1);
1233
1234		if_sethwassist(ifp, XNB_CSUM_FEATURES);
1235		if_setcapabilities(ifp, IFCAP_HWCSUM);
1236		if_setcapenable(ifp, IFCAP_HWCSUM);
1237
1238		ether_ifattach(ifp, xnb->mac);
1239		xnb->carrier = 0;
1240	}
1241
1242	return err;
1243}
1244
1245/**
1246 * Attach to a XenBus device that has been claimed by our probe routine.
1247 *
1248 * \param dev  NewBus device object representing this Xen Net Back instance.
1249 *
1250 * \return  0 for success, errno codes for failure.
1251 */
1252static int
1253xnb_attach(device_t dev)
1254{
1255	struct xnb_softc *xnb;
1256	int	error;
1257	xnb_ring_type_t	i;
1258
1259	error = create_netdev(dev);
1260	if (error != 0) {
1261		xenbus_dev_fatal(dev, error, "creating netdev");
1262		return (error);
1263	}
1264
1265	DPRINTF("Attaching to %s\n", xenbus_get_node(dev));
1266
1267	/*
1268	 * Basic initialization.
1269	 * After this block it is safe to call xnb_detach()
1270	 * to clean up any allocated data for this instance.
1271	 */
1272	xnb = device_get_softc(dev);
1273	xnb->otherend_id = xenbus_get_otherend_id(dev);
1274	for (i=0; i < XNB_NUM_RING_TYPES; i++) {
1275		xnb->ring_configs[i].ring_pages = 1;
1276	}
1277
1278	/*
1279	 * Setup sysctl variables.
1280	 */
1281	xnb_setup_sysctl(xnb);
1282
1283	/* Update hot-plug status to satisfy xend. */
1284	error = xs_printf(XST_NIL, xenbus_get_node(xnb->dev),
1285			  "hotplug-status", "connected");
1286	if (error != 0) {
1287		xnb_attach_failed(xnb, error, "writing %s/hotplug-status",
1288				  xenbus_get_node(xnb->dev));
1289		return (error);
1290	}
1291
1292	if ((error = xnb_publish_backend_info(xnb)) != 0) {
1293		/*
1294		 * If we can't publish our data, we cannot participate
1295		 * in this connection, and waiting for a front-end state
1296		 * change will not help the situation.
1297		 */
1298		xnb_attach_failed(xnb, error,
1299		    "Publishing backend status for %s",
1300				  xenbus_get_node(xnb->dev));
1301		return error;
1302	}
1303
1304	/* Tell the front end that we are ready to connect. */
1305	xenbus_set_state(dev, XenbusStateInitWait);
1306
1307	return (0);
1308}
1309
1310/**
1311 * Detach from a net back device instance.
1312 *
1313 * \param dev  NewBus device object representing this Xen Net Back instance.
1314 *
1315 * \return  0 for success, errno codes for failure.
1316 *
1317 * \note A net back device may be detached at any time in its life-cycle,
1318 *       including part way through the attach process.  For this reason,
1319 *       initialization order and the initialization state checks in this
1320 *       routine must be carefully coupled so that attach time failures
1321 *       are gracefully handled.
1322 */
1323static int
1324xnb_detach(device_t dev)
1325{
1326	struct xnb_softc *xnb;
1327
1328	DPRINTF("\n");
1329
1330	xnb = device_get_softc(dev);
1331	mtx_lock(&xnb->sc_lock);
1332	while (xnb_shutdown(xnb) == EAGAIN) {
1333		msleep(xnb, &xnb->sc_lock, /*wakeup prio unchanged*/0,
1334		       "xnb_shutdown", 0);
1335	}
1336	mtx_unlock(&xnb->sc_lock);
1337	DPRINTF("\n");
1338
1339	mtx_destroy(&xnb->tx_lock);
1340	mtx_destroy(&xnb->rx_lock);
1341	mtx_destroy(&xnb->sc_lock);
1342	return (0);
1343}
1344
1345/**
1346 * Prepare this net back device for suspension of this VM.
1347 *
1348 * \param dev  NewBus device object representing this Xen net Back instance.
1349 *
1350 * \return  0 for success, errno codes for failure.
1351 */
1352static int
1353xnb_suspend(device_t dev)
1354{
1355	return (0);
1356}
1357
1358/**
1359 * Perform any processing required to recover from a suspended state.
1360 *
1361 * \param dev  NewBus device object representing this Xen Net Back instance.
1362 *
1363 * \return  0 for success, errno codes for failure.
1364 */
1365static int
1366xnb_resume(device_t dev)
1367{
1368	return (0);
1369}
1370
1371/**
1372 * Handle state changes expressed via the XenStore by our front-end peer.
1373 *
1374 * \param dev             NewBus device object representing this Xen
1375 *                        Net Back instance.
1376 * \param frontend_state  The new state of the front-end.
1377 *
1378 * \return  0 for success, errno codes for failure.
1379 */
1380static void
1381xnb_frontend_changed(device_t dev, XenbusState frontend_state)
1382{
1383	struct xnb_softc *xnb;
1384
1385	xnb = device_get_softc(dev);
1386
1387	DPRINTF("frontend_state=%s, xnb_state=%s\n",
1388	        xenbus_strstate(frontend_state),
1389		xenbus_strstate(xenbus_get_state(xnb->dev)));
1390
1391	switch (frontend_state) {
1392	case XenbusStateInitialising:
1393	case XenbusStateInitialised:
1394		break;
1395	case XenbusStateConnected:
1396		xnb_connect(xnb);
1397		break;
1398	case XenbusStateClosing:
1399	case XenbusStateClosed:
1400		mtx_lock(&xnb->sc_lock);
1401		xnb_shutdown(xnb);
1402		mtx_unlock(&xnb->sc_lock);
1403		if (frontend_state == XenbusStateClosed)
1404			xenbus_set_state(xnb->dev, XenbusStateClosed);
1405		break;
1406	default:
1407		xenbus_dev_fatal(xnb->dev, EINVAL, "saw state %d at frontend",
1408				 frontend_state);
1409		break;
1410	}
1411}
1412
1413/*---------------------------- Request Processing ----------------------------*/
1414/**
1415 * Interrupt handler bound to the shared ring's event channel.
1416 * Entry point for the xennet transmit path in netback
1417 * Transfers packets from the Xen ring to the host's generic networking stack
1418 *
1419 * \param arg  Callback argument registerd during event channel
1420 *             binding - the xnb_softc for this instance.
1421 */
1422static void
1423xnb_intr(void *arg)
1424{
1425	struct xnb_softc *xnb;
1426	if_t ifp;
1427	netif_tx_back_ring_t *txb;
1428	RING_IDX req_prod_local;
1429
1430	xnb = (struct xnb_softc *)arg;
1431	ifp = xnb->xnb_ifp;
1432	txb = &xnb->ring_configs[XNB_RING_TYPE_TX].back_ring.tx_ring;
1433
1434	mtx_lock(&xnb->tx_lock);
1435	do {
1436		int notify;
1437		req_prod_local = txb->sring->req_prod;
1438		xen_rmb();
1439
1440		for (;;) {
1441			struct mbuf *mbufc;
1442			int err;
1443
1444			err = xnb_recv(txb, xnb->otherend_id, &mbufc, ifp,
1445			    	       xnb->tx_gnttab);
1446			if (err || (mbufc == NULL))
1447				break;
1448
1449			/* Send the packet to the generic network stack */
1450			if_input(xnb->xnb_ifp, mbufc);
1451		}
1452
1453		RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(txb, notify);
1454		if (notify != 0)
1455			xen_intr_signal(xnb->xen_intr_handle);
1456
1457		txb->sring->req_event = txb->req_cons + 1;
1458		xen_mb();
1459	} while (txb->sring->req_prod != req_prod_local) ;
1460	mtx_unlock(&xnb->tx_lock);
1461
1462	xnb_start(ifp);
1463}
1464
1465/**
1466 * Build a struct xnb_pkt based on netif_tx_request's from a netif tx ring.
1467 * Will read exactly 0 or 1 packets from the ring; never a partial packet.
1468 * \param[out]	pkt	The returned packet.  If there is an error building
1469 * 			the packet, pkt.list_len will be set to 0.
1470 * \param[in]	tx_ring	Pointer to the Ring that is the input to this function
1471 * \param[in]	start	The ring index of the first potential request
1472 * \return		The number of requests consumed to build this packet
1473 */
1474static int
1475xnb_ring2pkt(struct xnb_pkt *pkt, const netif_tx_back_ring_t *tx_ring,
1476	     RING_IDX start)
1477{
1478	/*
1479	 * Outline:
1480	 * 1) Initialize pkt
1481	 * 2) Read the first request of the packet
1482	 * 3) Read the extras
1483	 * 4) Set cdr
1484	 * 5) Loop on the remainder of the packet
1485	 * 6) Finalize pkt (stuff like car_size and list_len)
1486	 */
1487	int idx = start;
1488	int discard = 0;	/* whether to discard the packet */
1489	int more_data = 0;	/* there are more request past the last one */
1490	uint16_t cdr_size = 0;	/* accumulated size of requests 2 through n */
1491
1492	xnb_pkt_initialize(pkt);
1493
1494	/* Read the first request */
1495	if (RING_HAS_UNCONSUMED_REQUESTS_2(tx_ring, idx)) {
1496		netif_tx_request_t *tx = RING_GET_REQUEST(tx_ring, idx);
1497		pkt->size = tx->size;
1498		pkt->flags = tx->flags & ~NETTXF_more_data;
1499		more_data = tx->flags & NETTXF_more_data;
1500		pkt->list_len++;
1501		pkt->car = idx;
1502		idx++;
1503	}
1504
1505	/* Read the extra info */
1506	if ((pkt->flags & NETTXF_extra_info) &&
1507	    RING_HAS_UNCONSUMED_REQUESTS_2(tx_ring, idx)) {
1508		netif_extra_info_t *ext =
1509		    (netif_extra_info_t*) RING_GET_REQUEST(tx_ring, idx);
1510		pkt->extra.type = ext->type;
1511		switch (pkt->extra.type) {
1512			case XEN_NETIF_EXTRA_TYPE_GSO:
1513				pkt->extra.u.gso = ext->u.gso;
1514				break;
1515			default:
1516				/*
1517				 * The reference Linux netfront driver will
1518				 * never set any other extra.type.  So we don't
1519				 * know what to do with it.  Let's print an
1520				 * error, then consume and discard the packet
1521				 */
1522				printf("xnb(%s:%d): Unknown extra info type %d."
1523				       "  Discarding packet\n",
1524				       __func__, __LINE__, pkt->extra.type);
1525				xnb_dump_txreq(start, RING_GET_REQUEST(tx_ring,
1526				    start));
1527				xnb_dump_txreq(idx, RING_GET_REQUEST(tx_ring,
1528				    idx));
1529				discard = 1;
1530				break;
1531		}
1532
1533		pkt->extra.flags = ext->flags;
1534		if (ext->flags & XEN_NETIF_EXTRA_FLAG_MORE) {
1535			/*
1536			 * The reference linux netfront driver never sets this
1537			 * flag (nor does any other known netfront).  So we
1538			 * will discard the packet.
1539			 */
1540			printf("xnb(%s:%d): Request sets "
1541			    "XEN_NETIF_EXTRA_FLAG_MORE, but we can't handle "
1542			    "that\n", __func__, __LINE__);
1543			xnb_dump_txreq(start, RING_GET_REQUEST(tx_ring, start));
1544			xnb_dump_txreq(idx, RING_GET_REQUEST(tx_ring, idx));
1545			discard = 1;
1546		}
1547
1548		idx++;
1549	}
1550
1551	/* Set cdr.  If there is not more data, cdr is invalid */
1552	pkt->cdr = idx;
1553
1554	/* Loop on remainder of packet */
1555	while (more_data && RING_HAS_UNCONSUMED_REQUESTS_2(tx_ring, idx)) {
1556		netif_tx_request_t *tx = RING_GET_REQUEST(tx_ring, idx);
1557		pkt->list_len++;
1558		cdr_size += tx->size;
1559		if (tx->flags & ~NETTXF_more_data) {
1560			/* There should be no other flags set at this point */
1561			printf("xnb(%s:%d): Request sets unknown flags %d "
1562			    "after the 1st request in the packet.\n",
1563			    __func__, __LINE__, tx->flags);
1564			xnb_dump_txreq(start, RING_GET_REQUEST(tx_ring, start));
1565			xnb_dump_txreq(idx, RING_GET_REQUEST(tx_ring, idx));
1566		}
1567
1568		more_data = tx->flags & NETTXF_more_data;
1569		idx++;
1570	}
1571
1572	/* Finalize packet */
1573	if (more_data != 0) {
1574		/* The ring ran out of requests before finishing the packet */
1575		xnb_pkt_invalidate(pkt);
1576		idx = start;	/* tell caller that we consumed no requests */
1577	} else {
1578		/* Calculate car_size */
1579		pkt->car_size = pkt->size - cdr_size;
1580	}
1581	if (discard != 0) {
1582		xnb_pkt_invalidate(pkt);
1583	}
1584
1585	return idx - start;
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 */
1596static void
1597xnb_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 */
1653static struct mbuf*
1654xnb_pkt2mbufc(const struct xnb_pkt *pkt, if_t 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 */
1697static int
1698xnb_txpkt2gnttab(const struct xnb_pkt *pkt, struct mbuf *mbufc,
1699		 gnttab_copy_table gnttab, const netif_tx_back_ring_t *txb,
1700		 domid_t otherend_id)
1701{
1702
1703	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 */
1764static void
1765xnb_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 */
1804static int
1805xnb_recv(netif_tx_back_ring_t *txb, domid_t otherend, struct mbuf **mbufc,
1806	 if_t 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	if_inc_counter(ifnet, IFCOUNTER_IPACKETS, 1);
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		if_inc_counter(ifnet, IFCOUNTER_IERRORS, 1);
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		if_inc_counter(ifnet, IFCOUNTER_IQDROPS, 1);
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 */
1876static int
1877xnb_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 = howmany(pkt->size, 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 */
1949static int
1950xnb_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 */
2024static int
2025xnb_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 */
2138static void
2139xnb_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
2187static void
2188xnb_stop(struct xnb_softc *xnb)
2189{
2190	if_t ifp;
2191
2192	mtx_assert(&xnb->sc_lock, MA_OWNED);
2193	ifp = xnb->xnb_ifp;
2194	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2195	if_link_state_change(ifp, LINK_STATE_DOWN);
2196}
2197
2198static int
2199xnb_ioctl(if_t ifp, u_long cmd, caddr_t data)
2200{
2201	struct xnb_softc *xnb = if_getsoftc(ifp);
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 (if_getflags(ifp) & IFF_UP) {
2212				xnb_ifinit_locked(xnb);
2213			} else {
2214				if (if_getdrvflags(ifp) & 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#ifdef INET
2226			mtx_lock(&xnb->sc_lock);
2227			if (ifa->ifa_addr->sa_family == AF_INET) {
2228				if_setflagbits(ifp, IFF_UP, 0);
2229				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
2230					if_setdrvflagbits(ifp, 0,
2231					    IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2232					if_link_state_change(ifp,
2233							LINK_STATE_DOWN);
2234					if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
2235					if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
2236					if_link_state_change(ifp,
2237					    LINK_STATE_UP);
2238				}
2239				arp_ifinit(ifp, ifa);
2240				mtx_unlock(&xnb->sc_lock);
2241			} else {
2242				mtx_unlock(&xnb->sc_lock);
2243#endif
2244				error = ether_ioctl(ifp, cmd, data);
2245#ifdef INET
2246			}
2247#endif
2248			break;
2249		case SIOCSIFCAP:
2250			mtx_lock(&xnb->sc_lock);
2251			if (ifr->ifr_reqcap & IFCAP_TXCSUM) {
2252				if_setcapenablebit(ifp, IFCAP_TXCSUM, 0);
2253				if_sethwassistbits(ifp, XNB_CSUM_FEATURES, 0);
2254			} else {
2255				if_setcapenablebit(ifp, 0, IFCAP_TXCSUM);
2256				if_sethwassistbits(ifp, 0, XNB_CSUM_FEATURES);
2257			}
2258			if ((ifr->ifr_reqcap & IFCAP_RXCSUM)) {
2259				if_setcapenablebit(ifp, IFCAP_RXCSUM, 0);
2260			} else {
2261				if_setcapenablebit(ifp, 0, IFCAP_RXCSUM);
2262			}
2263			/*
2264			 * TODO enable TSO4 and LRO once we no longer need
2265			 * to calculate checksums in software
2266			 */
2267#if 0
2268			if (ifr->if_reqcap |= IFCAP_TSO4) {
2269				if (IFCAP_TXCSUM & if_getcapenable(ifp)) {
2270					printf("xnb: Xen netif requires that "
2271						"TXCSUM be enabled in order "
2272						"to use TSO4\n");
2273					error = EINVAL;
2274				} else {
2275					if_setcapenablebit(ifp, IFCAP_TSO4, 0);
2276					if_sethwassistbits(ifp, CSUM_TSO, 0);
2277				}
2278			} else {
2279				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2280				if_sethwassistbits(ifp, 0, (CSUM_TSO));
2281			}
2282			if (ifr->ifreqcap |= IFCAP_LRO) {
2283				if_setcapenablebit(ifp, IFCAP_LRO, 0);
2284			} else {
2285				if_setcapenablebit(ifp, 0, IFCAP_LRO);
2286			}
2287#endif
2288			mtx_unlock(&xnb->sc_lock);
2289			break;
2290		case SIOCSIFMTU:
2291			if_setmtu(ifp, ifr->ifr_mtu);
2292			if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
2293			xnb_ifinit(xnb);
2294			break;
2295		case SIOCADDMULTI:
2296		case SIOCDELMULTI:
2297			break;
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
2309static void
2310xnb_start_locked(if_t 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 = if_getsoftc(ifp);
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			mbufc = if_dequeue(ifp);
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_sendq_prepend(ifp, 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					if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2355					/* FALLTHROUGH */
2356				default:
2357					/* Send succeeded, or packet had error.
2358					 * Free the packet */
2359					if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
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 */
2389static int
2390xnb_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;
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	xnb_rxpkt2rsp(&pkt, gnttab, n_entries, ring);
2410
2411	return 0;
2412}
2413
2414static void
2415xnb_start(if_t ifp)
2416{
2417	struct xnb_softc *xnb;
2418
2419	xnb = if_getsoftc(ifp);
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 */
2426static void
2427xnb_ifinit_locked(struct xnb_softc *xnb)
2428{
2429	if_t ifp;
2430
2431	ifp = xnb->xnb_ifp;
2432
2433	mtx_assert(&xnb->sc_lock, MA_OWNED);
2434
2435	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2436		return;
2437
2438	xnb_stop(xnb);
2439
2440	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
2441	if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
2442	if_link_state_change(ifp, LINK_STATE_UP);
2443}
2444
2445static void
2446xnb_ifinit(void *xsc)
2447{
2448	struct xnb_softc *xnb = xsc;
2449
2450	mtx_lock(&xnb->sc_lock);
2451	xnb_ifinit_locked(xnb);
2452	mtx_unlock(&xnb->sc_lock);
2453}
2454
2455/**
2456 * Callback used by the generic networking code to tell us when our carrier
2457 * state has changed.  Since we don't have a physical carrier, we don't care
2458 */
2459static int
2460xnb_ifmedia_upd(if_t ifp)
2461{
2462	return (0);
2463}
2464
2465/**
2466 * Callback used by the generic networking code to ask us what our carrier
2467 * state is.  Since we don't have a physical carrier, this is very simple
2468 */
2469static void
2470xnb_ifmedia_sts(if_t ifp, struct ifmediareq *ifmr)
2471{
2472	ifmr->ifm_status = IFM_AVALID|IFM_ACTIVE;
2473	ifmr->ifm_active = IFM_ETHER|IFM_MANUAL;
2474}
2475
2476/*---------------------------- NewBus Registration ---------------------------*/
2477static device_method_t xnb_methods[] = {
2478	/* Device interface */
2479	DEVMETHOD(device_probe,		xnb_probe),
2480	DEVMETHOD(device_attach,	xnb_attach),
2481	DEVMETHOD(device_detach,	xnb_detach),
2482	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
2483	DEVMETHOD(device_suspend,	xnb_suspend),
2484	DEVMETHOD(device_resume,	xnb_resume),
2485
2486	/* Xenbus interface */
2487	DEVMETHOD(xenbus_otherend_changed, xnb_frontend_changed),
2488
2489	DEVMETHOD_END
2490};
2491
2492static driver_t xnb_driver = {
2493	"xnb",
2494	xnb_methods,
2495	sizeof(struct xnb_softc),
2496};
2497
2498DRIVER_MODULE(xnb, xenbusb_back, xnb_driver, 0, 0);
2499
2500/*-------------------------- Unit Tests -------------------------------------*/
2501#ifdef XNB_DEBUG
2502#include "netback_unit_tests.c"
2503#endif
2504