xref: /freebsd/sys/dev/xen/netfront/netfront.c (revision 315ee00f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2004-2006 Kip Macy
5  * Copyright (c) 2015 Wei Liu <wei.liu2@citrix.com>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 
34 #include <sys/param.h>
35 #include <sys/sockio.h>
36 #include <sys/limits.h>
37 #include <sys/mbuf.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/kernel.h>
41 #include <sys/socket.h>
42 #include <sys/sysctl.h>
43 #include <sys/taskqueue.h>
44 
45 #include <net/if.h>
46 #include <net/if_var.h>
47 #include <net/if_arp.h>
48 #include <net/ethernet.h>
49 #include <net/if_media.h>
50 #include <net/bpf.h>
51 #include <net/if_types.h>
52 
53 #include <netinet/in.h>
54 #include <netinet/ip.h>
55 #include <netinet/if_ether.h>
56 #include <netinet/tcp.h>
57 #include <netinet/tcp_lro.h>
58 
59 #include <vm/vm.h>
60 #include <vm/pmap.h>
61 
62 #include <sys/bus.h>
63 
64 #include <xen/xen-os.h>
65 #include <xen/hypervisor.h>
66 #include <xen/xen_intr.h>
67 #include <xen/gnttab.h>
68 #include <contrib/xen/memory.h>
69 #include <contrib/xen/io/netif.h>
70 #include <xen/xenbus/xenbusvar.h>
71 
72 #include <machine/bus.h>
73 
74 #include "xenbus_if.h"
75 
76 /* Features supported by all backends.  TSO and LRO can be negotiated */
77 #define XN_CSUM_FEATURES	(CSUM_TCP | CSUM_UDP)
78 
79 #define NET_TX_RING_SIZE __CONST_RING_SIZE(netif_tx, PAGE_SIZE)
80 #define NET_RX_RING_SIZE __CONST_RING_SIZE(netif_rx, PAGE_SIZE)
81 
82 #define NET_RX_SLOTS_MIN (XEN_NETIF_NR_SLOTS_MIN + 1)
83 
84 /*
85  * Should the driver do LRO on the RX end
86  *  this can be toggled on the fly, but the
87  *  interface must be reset (down/up) for it
88  *  to take effect.
89  */
90 static int xn_enable_lro = 1;
91 TUNABLE_INT("hw.xn.enable_lro", &xn_enable_lro);
92 
93 /*
94  * Number of pairs of queues.
95  */
96 static unsigned long xn_num_queues = 4;
97 TUNABLE_ULONG("hw.xn.num_queues", &xn_num_queues);
98 
99 /**
100  * \brief The maximum allowed data fragments in a single transmit
101  *        request.
102  *
103  * This limit is imposed by the backend driver.  We assume here that
104  * we are dealing with a Linux driver domain and have set our limit
105  * to mirror the Linux MAX_SKB_FRAGS constant.
106  */
107 #define	MAX_TX_REQ_FRAGS (65536 / PAGE_SIZE + 2)
108 
109 #define RX_COPY_THRESHOLD 256
110 
111 #define net_ratelimit() 0
112 
113 struct netfront_rxq;
114 struct netfront_txq;
115 struct netfront_info;
116 struct netfront_rx_info;
117 
118 static void xn_txeof(struct netfront_txq *);
119 static void xn_rxeof(struct netfront_rxq *);
120 static void xn_alloc_rx_buffers(struct netfront_rxq *);
121 static void xn_alloc_rx_buffers_callout(void *arg);
122 
123 static void xn_release_rx_bufs(struct netfront_rxq *);
124 static void xn_release_tx_bufs(struct netfront_txq *);
125 
126 static void xn_rxq_intr(struct netfront_rxq *);
127 static void xn_txq_intr(struct netfront_txq *);
128 static void xn_intr(void *);
129 static int xn_assemble_tx_request(struct netfront_txq *, struct mbuf *);
130 static int xn_ioctl(if_t, u_long, caddr_t);
131 static void xn_ifinit_locked(struct netfront_info *);
132 static void xn_ifinit(void *);
133 static void xn_stop(struct netfront_info *);
134 static void xn_query_features(struct netfront_info *np);
135 static int xn_configure_features(struct netfront_info *np);
136 static void netif_free(struct netfront_info *info);
137 static int netfront_detach(device_t dev);
138 
139 static int xn_txq_mq_start_locked(struct netfront_txq *, struct mbuf *);
140 static int xn_txq_mq_start(if_t, struct mbuf *);
141 
142 static int talk_to_backend(device_t dev, struct netfront_info *info);
143 static int create_netdev(device_t dev);
144 static void netif_disconnect_backend(struct netfront_info *info);
145 static int setup_device(device_t dev, struct netfront_info *info,
146     unsigned long);
147 static int xn_ifmedia_upd(if_t ifp);
148 static void xn_ifmedia_sts(if_t ifp, struct ifmediareq *ifmr);
149 
150 static int xn_connect(struct netfront_info *);
151 static void xn_kick_rings(struct netfront_info *);
152 
153 static int xn_get_responses(struct netfront_rxq *,
154     struct netfront_rx_info *, RING_IDX, RING_IDX *,
155     struct mbuf **);
156 
157 #define virt_to_mfn(x) (vtophys(x) >> PAGE_SHIFT)
158 
159 #define INVALID_P2M_ENTRY (~0UL)
160 #define XN_QUEUE_NAME_LEN  8	/* xn{t,r}x_%u, allow for two digits */
161 struct netfront_rxq {
162 	struct netfront_info 	*info;
163 	u_int			id;
164 	char			name[XN_QUEUE_NAME_LEN];
165 	struct mtx		lock;
166 
167 	int			ring_ref;
168 	netif_rx_front_ring_t 	ring;
169 	xen_intr_handle_t	xen_intr_handle;
170 
171 	grant_ref_t 		gref_head;
172 	grant_ref_t 		grant_ref[NET_RX_RING_SIZE + 1];
173 
174 	struct mbuf		*mbufs[NET_RX_RING_SIZE + 1];
175 
176 	struct lro_ctrl		lro;
177 
178 	struct callout		rx_refill;
179 };
180 
181 struct netfront_txq {
182 	struct netfront_info 	*info;
183 	u_int 			id;
184 	char			name[XN_QUEUE_NAME_LEN];
185 	struct mtx		lock;
186 
187 	int			ring_ref;
188 	netif_tx_front_ring_t	ring;
189 	xen_intr_handle_t 	xen_intr_handle;
190 
191 	grant_ref_t		gref_head;
192 	grant_ref_t		grant_ref[NET_TX_RING_SIZE + 1];
193 
194 	struct mbuf		*mbufs[NET_TX_RING_SIZE + 1];
195 	int			mbufs_cnt;
196 	struct buf_ring		*br;
197 
198 	struct taskqueue 	*tq;
199 	struct task       	defrtask;
200 
201 	bus_dma_segment_t	segs[MAX_TX_REQ_FRAGS];
202 	struct mbuf_xennet {
203 		struct m_tag 	tag;
204 		bus_dma_tag_t	dma_tag;
205 		bus_dmamap_t	dma_map;
206 		struct netfront_txq *txq;
207 		SLIST_ENTRY(mbuf_xennet) next;
208 		u_int 		count;
209 	}			xennet_tag[NET_TX_RING_SIZE + 1];
210 	SLIST_HEAD(, mbuf_xennet) tags;
211 
212 	bool			full;
213 };
214 
215 struct netfront_info {
216 	if_t			xn_ifp;
217 
218 	struct mtx   		sc_lock;
219 
220 	u_int  num_queues;
221 	struct netfront_rxq 	*rxq;
222 	struct netfront_txq 	*txq;
223 
224 	u_int			carrier;
225 	u_int			maxfrags;
226 
227 	device_t		xbdev;
228 	uint8_t			mac[ETHER_ADDR_LEN];
229 
230 	int			xn_if_flags;
231 
232 	struct ifmedia		sc_media;
233 
234 	bus_dma_tag_t		dma_tag;
235 
236 	bool			xn_reset;
237 };
238 
239 struct netfront_rx_info {
240 	struct netif_rx_response rx;
241 	struct netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX - 1];
242 };
243 
244 #define XN_RX_LOCK(_q)         mtx_lock(&(_q)->lock)
245 #define XN_RX_UNLOCK(_q)       mtx_unlock(&(_q)->lock)
246 
247 #define XN_TX_LOCK(_q)         mtx_lock(&(_q)->lock)
248 #define XN_TX_TRYLOCK(_q)      mtx_trylock(&(_q)->lock)
249 #define XN_TX_UNLOCK(_q)       mtx_unlock(&(_q)->lock)
250 
251 #define XN_LOCK(_sc)           mtx_lock(&(_sc)->sc_lock);
252 #define XN_UNLOCK(_sc)         mtx_unlock(&(_sc)->sc_lock);
253 
254 #define XN_LOCK_ASSERT(_sc)    mtx_assert(&(_sc)->sc_lock, MA_OWNED);
255 #define XN_RX_LOCK_ASSERT(_q)  mtx_assert(&(_q)->lock, MA_OWNED);
256 #define XN_TX_LOCK_ASSERT(_q)  mtx_assert(&(_q)->lock, MA_OWNED);
257 
258 #define netfront_carrier_on(netif)	((netif)->carrier = 1)
259 #define netfront_carrier_off(netif)	((netif)->carrier = 0)
260 #define netfront_carrier_ok(netif)	((netif)->carrier)
261 
262 /* Access macros for acquiring freeing slots in xn_free_{tx,rx}_idxs[]. */
263 
264 static inline void
265 add_id_to_freelist(struct mbuf **list, uintptr_t id)
266 {
267 
268 	KASSERT(id != 0,
269 		("%s: the head item (0) must always be free.", __func__));
270 	list[id] = list[0];
271 	list[0]  = (struct mbuf *)id;
272 }
273 
274 static inline unsigned short
275 get_id_from_freelist(struct mbuf **list)
276 {
277 	uintptr_t id;
278 
279 	id = (uintptr_t)list[0];
280 	KASSERT(id != 0,
281 		("%s: the head item (0) must always remain free.", __func__));
282 	list[0] = list[id];
283 	return (id);
284 }
285 
286 static inline int
287 xn_rxidx(RING_IDX idx)
288 {
289 
290 	return idx & (NET_RX_RING_SIZE - 1);
291 }
292 
293 static inline struct mbuf *
294 xn_get_rx_mbuf(struct netfront_rxq *rxq, RING_IDX ri)
295 {
296 	int i;
297 	struct mbuf *m;
298 
299 	i = xn_rxidx(ri);
300 	m = rxq->mbufs[i];
301 	rxq->mbufs[i] = NULL;
302 	return (m);
303 }
304 
305 static inline grant_ref_t
306 xn_get_rx_ref(struct netfront_rxq *rxq, RING_IDX ri)
307 {
308 	int i = xn_rxidx(ri);
309 	grant_ref_t ref = rxq->grant_ref[i];
310 
311 	KASSERT(ref != GRANT_REF_INVALID, ("Invalid grant reference!\n"));
312 	rxq->grant_ref[i] = GRANT_REF_INVALID;
313 	return (ref);
314 }
315 
316 #define MTAG_COOKIE 1218492000
317 #define MTAG_XENNET 0
318 
319 static void mbuf_grab(struct mbuf *m)
320 {
321 	struct mbuf_xennet *ref;
322 
323 	ref = (struct mbuf_xennet *)m_tag_locate(m, MTAG_COOKIE,
324 	    MTAG_XENNET, NULL);
325 	KASSERT(ref != NULL, ("Cannot find refcount"));
326 	ref->count++;
327 }
328 
329 static void mbuf_release(struct mbuf *m)
330 {
331 	struct mbuf_xennet *ref;
332 
333 	ref = (struct mbuf_xennet *)m_tag_locate(m, MTAG_COOKIE,
334 	    MTAG_XENNET, NULL);
335 	KASSERT(ref != NULL, ("Cannot find refcount"));
336 	KASSERT(ref->count > 0, ("Invalid reference count"));
337 
338 	if (--ref->count == 0)
339 		m_freem(m);
340 }
341 
342 static void tag_free(struct m_tag *t)
343 {
344 	struct mbuf_xennet *ref = (struct mbuf_xennet *)t;
345 
346 	KASSERT(ref->count == 0, ("Free mbuf tag with pending refcnt"));
347 	bus_dmamap_sync(ref->dma_tag, ref->dma_map, BUS_DMASYNC_POSTWRITE);
348 	bus_dmamap_destroy(ref->dma_tag, ref->dma_map);
349 	SLIST_INSERT_HEAD(&ref->txq->tags, ref, next);
350 }
351 
352 #define IPRINTK(fmt, args...) \
353     printf("[XEN] " fmt, ##args)
354 #ifdef INVARIANTS
355 #define WPRINTK(fmt, args...) \
356     printf("[XEN] " fmt, ##args)
357 #else
358 #define WPRINTK(fmt, args...)
359 #endif
360 #ifdef DEBUG
361 #define DPRINTK(fmt, args...) \
362     printf("[XEN] %s: " fmt, __func__, ##args)
363 #else
364 #define DPRINTK(fmt, args...)
365 #endif
366 
367 /**
368  * Read the 'mac' node at the given device's node in the store, and parse that
369  * as colon-separated octets, placing result the given mac array.  mac must be
370  * a preallocated array of length ETH_ALEN (as declared in linux/if_ether.h).
371  * Return 0 on success, or errno on error.
372  */
373 static int
374 xen_net_read_mac(device_t dev, uint8_t mac[])
375 {
376 	int error, i;
377 	char *s, *e, *macstr;
378 	const char *path;
379 
380 	path = xenbus_get_node(dev);
381 	error = xs_read(XST_NIL, path, "mac", NULL, (void **) &macstr);
382 	if (error == ENOENT) {
383 		/*
384 		 * Deal with missing mac XenStore nodes on devices with
385 		 * HVM emulation (the 'ioemu' configuration attribute)
386 		 * enabled.
387 		 *
388 		 * The HVM emulator may execute in a stub device model
389 		 * domain which lacks the permission, only given to Dom0,
390 		 * to update the guest's XenStore tree.  For this reason,
391 		 * the HVM emulator doesn't even attempt to write the
392 		 * front-side mac node, even when operating in Dom0.
393 		 * However, there should always be a mac listed in the
394 		 * backend tree.  Fallback to this version if our query
395 		 * of the front side XenStore location doesn't find
396 		 * anything.
397 		 */
398 		path = xenbus_get_otherend_path(dev);
399 		error = xs_read(XST_NIL, path, "mac", NULL, (void **) &macstr);
400 	}
401 	if (error != 0) {
402 		xenbus_dev_fatal(dev, error, "parsing %s/mac", path);
403 		return (error);
404 	}
405 
406 	s = macstr;
407 	for (i = 0; i < ETHER_ADDR_LEN; i++) {
408 		mac[i] = strtoul(s, &e, 16);
409 		if (s == e || (e[0] != ':' && e[0] != 0)) {
410 			free(macstr, M_XENBUS);
411 			return (ENOENT);
412 		}
413 		s = &e[1];
414 	}
415 	free(macstr, M_XENBUS);
416 	return (0);
417 }
418 
419 /**
420  * Entry point to this code when a new device is created.  Allocate the basic
421  * structures and the ring buffers for communication with the backend, and
422  * inform the backend of the appropriate details for those.  Switch to
423  * Connected state.
424  */
425 static int
426 netfront_probe(device_t dev)
427 {
428 
429 	if (xen_pv_nics_disabled())
430 		return (ENXIO);
431 
432 	if (!strcmp(xenbus_get_type(dev), "vif")) {
433 		device_set_desc(dev, "Virtual Network Interface");
434 		return (0);
435 	}
436 
437 	return (ENXIO);
438 }
439 
440 static int
441 netfront_attach(device_t dev)
442 {
443 	int err;
444 
445 	err = create_netdev(dev);
446 	if (err != 0) {
447 		xenbus_dev_fatal(dev, err, "creating netdev");
448 		return (err);
449 	}
450 
451 	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
452 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
453 	    OID_AUTO, "enable_lro", CTLFLAG_RW,
454 	    &xn_enable_lro, 0, "Large Receive Offload");
455 
456 	SYSCTL_ADD_ULONG(device_get_sysctl_ctx(dev),
457 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
458 	    OID_AUTO, "num_queues", CTLFLAG_RD,
459 	    &xn_num_queues, "Number of pairs of queues");
460 
461 	return (0);
462 }
463 
464 static int
465 netfront_suspend(device_t dev)
466 {
467 	struct netfront_info *np = device_get_softc(dev);
468 	u_int i;
469 
470 	for (i = 0; i < np->num_queues; i++) {
471 		XN_RX_LOCK(&np->rxq[i]);
472 		XN_TX_LOCK(&np->txq[i]);
473 	}
474 	netfront_carrier_off(np);
475 	for (i = 0; i < np->num_queues; i++) {
476 		XN_RX_UNLOCK(&np->rxq[i]);
477 		XN_TX_UNLOCK(&np->txq[i]);
478 	}
479 	return (0);
480 }
481 
482 /**
483  * We are reconnecting to the backend, due to a suspend/resume, or a backend
484  * driver restart.  We tear down our netif structure and recreate it, but
485  * leave the device-layer structures intact so that this is transparent to the
486  * rest of the kernel.
487  */
488 static int
489 netfront_resume(device_t dev)
490 {
491 	struct netfront_info *info = device_get_softc(dev);
492 	u_int i;
493 
494 	if (xen_suspend_cancelled) {
495 		for (i = 0; i < info->num_queues; i++) {
496 			XN_RX_LOCK(&info->rxq[i]);
497 			XN_TX_LOCK(&info->txq[i]);
498 		}
499 		netfront_carrier_on(info);
500 		for (i = 0; i < info->num_queues; i++) {
501 			XN_RX_UNLOCK(&info->rxq[i]);
502 			XN_TX_UNLOCK(&info->txq[i]);
503 		}
504 		return (0);
505 	}
506 
507 	netif_disconnect_backend(info);
508 	return (0);
509 }
510 
511 static int
512 write_queue_xenstore_keys(device_t dev,
513     struct netfront_rxq *rxq,
514     struct netfront_txq *txq,
515     struct xs_transaction *xst, bool hierarchy)
516 {
517 	int err;
518 	const char *message;
519 	const char *node = xenbus_get_node(dev);
520 	char *path;
521 	size_t path_size;
522 
523 	KASSERT(rxq->id == txq->id, ("Mismatch between RX and TX queue ids"));
524 	/* Split event channel support is not yet there. */
525 	KASSERT(rxq->xen_intr_handle == txq->xen_intr_handle,
526 	    ("Split event channels are not supported"));
527 
528 	if (hierarchy) {
529 		path_size = strlen(node) + 10;
530 		path = malloc(path_size, M_DEVBUF, M_WAITOK|M_ZERO);
531 		snprintf(path, path_size, "%s/queue-%u", node, rxq->id);
532 	} else {
533 		path_size = strlen(node) + 1;
534 		path = malloc(path_size, M_DEVBUF, M_WAITOK|M_ZERO);
535 		snprintf(path, path_size, "%s", node);
536 	}
537 
538 	err = xs_printf(*xst, path, "tx-ring-ref","%u", txq->ring_ref);
539 	if (err != 0) {
540 		message = "writing tx ring-ref";
541 		goto error;
542 	}
543 	err = xs_printf(*xst, path, "rx-ring-ref","%u", rxq->ring_ref);
544 	if (err != 0) {
545 		message = "writing rx ring-ref";
546 		goto error;
547 	}
548 	err = xs_printf(*xst, path, "event-channel", "%u",
549 	    xen_intr_port(rxq->xen_intr_handle));
550 	if (err != 0) {
551 		message = "writing event-channel";
552 		goto error;
553 	}
554 
555 	free(path, M_DEVBUF);
556 
557 	return (0);
558 
559 error:
560 	free(path, M_DEVBUF);
561 	xenbus_dev_fatal(dev, err, "%s", message);
562 
563 	return (err);
564 }
565 
566 /* Common code used when first setting up, and when resuming. */
567 static int
568 talk_to_backend(device_t dev, struct netfront_info *info)
569 {
570 	const char *message;
571 	struct xs_transaction xst;
572 	const char *node = xenbus_get_node(dev);
573 	int err;
574 	unsigned long num_queues, max_queues = 0;
575 	unsigned int i;
576 
577 	err = xen_net_read_mac(dev, info->mac);
578 	if (err != 0) {
579 		xenbus_dev_fatal(dev, err, "parsing %s/mac", node);
580 		goto out;
581 	}
582 
583 	err = xs_scanf(XST_NIL, xenbus_get_otherend_path(info->xbdev),
584 	    "multi-queue-max-queues", NULL, "%lu", &max_queues);
585 	if (err != 0)
586 		max_queues = 1;
587 	num_queues = xn_num_queues;
588 	if (num_queues > max_queues)
589 		num_queues = max_queues;
590 
591 	err = setup_device(dev, info, num_queues);
592 	if (err != 0)
593 		goto out;
594 
595  again:
596 	err = xs_transaction_start(&xst);
597 	if (err != 0) {
598 		xenbus_dev_fatal(dev, err, "starting transaction");
599 		goto free;
600 	}
601 
602 	if (info->num_queues == 1) {
603 		err = write_queue_xenstore_keys(dev, &info->rxq[0],
604 		    &info->txq[0], &xst, false);
605 		if (err != 0)
606 			goto abort_transaction_no_def_error;
607 	} else {
608 		err = xs_printf(xst, node, "multi-queue-num-queues",
609 		    "%u", info->num_queues);
610 		if (err != 0) {
611 			message = "writing multi-queue-num-queues";
612 			goto abort_transaction;
613 		}
614 
615 		for (i = 0; i < info->num_queues; i++) {
616 			err = write_queue_xenstore_keys(dev, &info->rxq[i],
617 			    &info->txq[i], &xst, true);
618 			if (err != 0)
619 				goto abort_transaction_no_def_error;
620 		}
621 	}
622 
623 	err = xs_printf(xst, node, "request-rx-copy", "%u", 1);
624 	if (err != 0) {
625 		message = "writing request-rx-copy";
626 		goto abort_transaction;
627 	}
628 	err = xs_printf(xst, node, "feature-rx-notify", "%d", 1);
629 	if (err != 0) {
630 		message = "writing feature-rx-notify";
631 		goto abort_transaction;
632 	}
633 	err = xs_printf(xst, node, "feature-sg", "%d", 1);
634 	if (err != 0) {
635 		message = "writing feature-sg";
636 		goto abort_transaction;
637 	}
638 	if ((if_getcapenable(info->xn_ifp) & IFCAP_LRO) != 0) {
639 		err = xs_printf(xst, node, "feature-gso-tcpv4", "%d", 1);
640 		if (err != 0) {
641 			message = "writing feature-gso-tcpv4";
642 			goto abort_transaction;
643 		}
644 	}
645 	if ((if_getcapenable(info->xn_ifp) & IFCAP_RXCSUM) == 0) {
646 		err = xs_printf(xst, node, "feature-no-csum-offload", "%d", 1);
647 		if (err != 0) {
648 			message = "writing feature-no-csum-offload";
649 			goto abort_transaction;
650 		}
651 	}
652 
653 	err = xs_transaction_end(xst, 0);
654 	if (err != 0) {
655 		if (err == EAGAIN)
656 			goto again;
657 		xenbus_dev_fatal(dev, err, "completing transaction");
658 		goto free;
659 	}
660 
661 	return 0;
662 
663  abort_transaction:
664 	xenbus_dev_fatal(dev, err, "%s", message);
665  abort_transaction_no_def_error:
666 	xs_transaction_end(xst, 1);
667  free:
668 	netif_free(info);
669  out:
670 	return (err);
671 }
672 
673 static void
674 xn_rxq_intr(struct netfront_rxq *rxq)
675 {
676 
677 	XN_RX_LOCK(rxq);
678 	xn_rxeof(rxq);
679 	XN_RX_UNLOCK(rxq);
680 }
681 
682 static void
683 xn_txq_start(struct netfront_txq *txq)
684 {
685 	struct netfront_info *np = txq->info;
686 	if_t ifp = np->xn_ifp;
687 
688 	XN_TX_LOCK_ASSERT(txq);
689 	if (!drbr_empty(ifp, txq->br))
690 		xn_txq_mq_start_locked(txq, NULL);
691 }
692 
693 static void
694 xn_txq_intr(struct netfront_txq *txq)
695 {
696 
697 	XN_TX_LOCK(txq);
698 	if (RING_HAS_UNCONSUMED_RESPONSES(&txq->ring))
699 		xn_txeof(txq);
700 	xn_txq_start(txq);
701 	XN_TX_UNLOCK(txq);
702 }
703 
704 static void
705 xn_txq_tq_deferred(void *xtxq, int pending)
706 {
707 	struct netfront_txq *txq = xtxq;
708 
709 	XN_TX_LOCK(txq);
710 	xn_txq_start(txq);
711 	XN_TX_UNLOCK(txq);
712 }
713 
714 static void
715 disconnect_rxq(struct netfront_rxq *rxq)
716 {
717 
718 	xn_release_rx_bufs(rxq);
719 	gnttab_free_grant_references(rxq->gref_head);
720 	gnttab_end_foreign_access(rxq->ring_ref, NULL);
721 	/*
722 	 * No split event channel support at the moment, handle will
723 	 * be unbound in tx. So no need to call xen_intr_unbind here,
724 	 * but we do want to reset the handler to 0.
725 	 */
726 	rxq->xen_intr_handle = 0;
727 }
728 
729 static void
730 destroy_rxq(struct netfront_rxq *rxq)
731 {
732 
733 	callout_drain(&rxq->rx_refill);
734 	free(rxq->ring.sring, M_DEVBUF);
735 }
736 
737 static void
738 destroy_rxqs(struct netfront_info *np)
739 {
740 	int i;
741 
742 	for (i = 0; i < np->num_queues; i++)
743 		destroy_rxq(&np->rxq[i]);
744 
745 	free(np->rxq, M_DEVBUF);
746 	np->rxq = NULL;
747 }
748 
749 static int
750 setup_rxqs(device_t dev, struct netfront_info *info,
751 	   unsigned long num_queues)
752 {
753 	int q, i;
754 	int error;
755 	netif_rx_sring_t *rxs;
756 	struct netfront_rxq *rxq;
757 
758 	info->rxq = malloc(sizeof(struct netfront_rxq) * num_queues,
759 	    M_DEVBUF, M_WAITOK|M_ZERO);
760 
761 	for (q = 0; q < num_queues; q++) {
762 		rxq = &info->rxq[q];
763 
764 		rxq->id = q;
765 		rxq->info = info;
766 		rxq->ring_ref = GRANT_REF_INVALID;
767 		rxq->ring.sring = NULL;
768 		snprintf(rxq->name, XN_QUEUE_NAME_LEN, "xnrx_%u", q);
769 		mtx_init(&rxq->lock, rxq->name, "netfront receive lock",
770 		    MTX_DEF);
771 
772 		for (i = 0; i <= NET_RX_RING_SIZE; i++) {
773 			rxq->mbufs[i] = NULL;
774 			rxq->grant_ref[i] = GRANT_REF_INVALID;
775 		}
776 
777 		/* Start resources allocation */
778 
779 		if (gnttab_alloc_grant_references(NET_RX_RING_SIZE,
780 		    &rxq->gref_head) != 0) {
781 			device_printf(dev, "allocating rx gref");
782 			error = ENOMEM;
783 			goto fail;
784 		}
785 
786 		rxs = (netif_rx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF,
787 		    M_WAITOK|M_ZERO);
788 		SHARED_RING_INIT(rxs);
789 		FRONT_RING_INIT(&rxq->ring, rxs, PAGE_SIZE);
790 
791 		error = xenbus_grant_ring(dev, virt_to_mfn(rxs),
792 		    &rxq->ring_ref);
793 		if (error != 0) {
794 			device_printf(dev, "granting rx ring page");
795 			goto fail_grant_ring;
796 		}
797 
798 		callout_init(&rxq->rx_refill, 1);
799 	}
800 
801 	return (0);
802 
803 fail_grant_ring:
804 	gnttab_free_grant_references(rxq->gref_head);
805 	free(rxq->ring.sring, M_DEVBUF);
806 fail:
807 	for (; q >= 0; q--) {
808 		disconnect_rxq(&info->rxq[q]);
809 		destroy_rxq(&info->rxq[q]);
810 	}
811 
812 	free(info->rxq, M_DEVBUF);
813 	return (error);
814 }
815 
816 static void
817 disconnect_txq(struct netfront_txq *txq)
818 {
819 
820 	xn_release_tx_bufs(txq);
821 	gnttab_free_grant_references(txq->gref_head);
822 	gnttab_end_foreign_access(txq->ring_ref, NULL);
823 	xen_intr_unbind(&txq->xen_intr_handle);
824 }
825 
826 static void
827 destroy_txq(struct netfront_txq *txq)
828 {
829 	unsigned int i;
830 
831 	free(txq->ring.sring, M_DEVBUF);
832 	buf_ring_free(txq->br, M_DEVBUF);
833 	taskqueue_drain_all(txq->tq);
834 	taskqueue_free(txq->tq);
835 
836 	for (i = 0; i <= NET_TX_RING_SIZE; i++) {
837 		bus_dmamap_destroy(txq->info->dma_tag,
838 		    txq->xennet_tag[i].dma_map);
839 		txq->xennet_tag[i].dma_map = NULL;
840 	}
841 }
842 
843 static void
844 destroy_txqs(struct netfront_info *np)
845 {
846 	int i;
847 
848 	for (i = 0; i < np->num_queues; i++)
849 		destroy_txq(&np->txq[i]);
850 
851 	free(np->txq, M_DEVBUF);
852 	np->txq = NULL;
853 }
854 
855 static int
856 setup_txqs(device_t dev, struct netfront_info *info,
857 	   unsigned long num_queues)
858 {
859 	int q, i;
860 	int error;
861 	netif_tx_sring_t *txs;
862 	struct netfront_txq *txq;
863 
864 	info->txq = malloc(sizeof(struct netfront_txq) * num_queues,
865 	    M_DEVBUF, M_WAITOK|M_ZERO);
866 
867 	for (q = 0; q < num_queues; q++) {
868 		txq = &info->txq[q];
869 
870 		txq->id = q;
871 		txq->info = info;
872 
873 		txq->ring_ref = GRANT_REF_INVALID;
874 		txq->ring.sring = NULL;
875 
876 		snprintf(txq->name, XN_QUEUE_NAME_LEN, "xntx_%u", q);
877 
878 		mtx_init(&txq->lock, txq->name, "netfront transmit lock",
879 		    MTX_DEF);
880 		SLIST_INIT(&txq->tags);
881 
882 		for (i = 0; i <= NET_TX_RING_SIZE; i++) {
883 			txq->mbufs[i] = (void *) ((u_long) i+1);
884 			txq->grant_ref[i] = GRANT_REF_INVALID;
885 			txq->xennet_tag[i].txq = txq;
886 			txq->xennet_tag[i].dma_tag = info->dma_tag;
887 			error = bus_dmamap_create(info->dma_tag, 0,
888 			    &txq->xennet_tag[i].dma_map);
889 			if (error != 0) {
890 				device_printf(dev,
891 				    "failed to allocate dma map\n");
892 				goto fail;
893 			}
894 			m_tag_setup(&txq->xennet_tag[i].tag,
895 			    MTAG_COOKIE, MTAG_XENNET,
896 			    sizeof(txq->xennet_tag[i]) -
897 			    sizeof(txq->xennet_tag[i].tag));
898 			txq->xennet_tag[i].tag.m_tag_free = &tag_free;
899 			SLIST_INSERT_HEAD(&txq->tags, &txq->xennet_tag[i],
900 			    next);
901 		}
902 		txq->mbufs[NET_TX_RING_SIZE] = (void *)0;
903 
904 		/* Start resources allocation. */
905 
906 		if (gnttab_alloc_grant_references(NET_TX_RING_SIZE,
907 		    &txq->gref_head) != 0) {
908 			device_printf(dev, "failed to allocate tx grant refs\n");
909 			error = ENOMEM;
910 			goto fail;
911 		}
912 
913 		txs = (netif_tx_sring_t *)malloc(PAGE_SIZE, M_DEVBUF,
914 		    M_WAITOK|M_ZERO);
915 		SHARED_RING_INIT(txs);
916 		FRONT_RING_INIT(&txq->ring, txs, PAGE_SIZE);
917 
918 		error = xenbus_grant_ring(dev, virt_to_mfn(txs),
919 		    &txq->ring_ref);
920 		if (error != 0) {
921 			device_printf(dev, "failed to grant tx ring\n");
922 			goto fail_grant_ring;
923 		}
924 
925 		txq->br = buf_ring_alloc(NET_TX_RING_SIZE, M_DEVBUF,
926 		    M_WAITOK, &txq->lock);
927 		TASK_INIT(&txq->defrtask, 0, xn_txq_tq_deferred, txq);
928 
929 		txq->tq = taskqueue_create(txq->name, M_WAITOK,
930 		    taskqueue_thread_enqueue, &txq->tq);
931 
932 		error = taskqueue_start_threads(&txq->tq, 1, PI_NET,
933 		    "%s txq %d", device_get_nameunit(dev), txq->id);
934 		if (error != 0) {
935 			device_printf(dev, "failed to start tx taskq %d\n",
936 			    txq->id);
937 			goto fail_start_thread;
938 		}
939 
940 		error = xen_intr_alloc_and_bind_local_port(dev,
941 		    xenbus_get_otherend_id(dev), /* filter */ NULL, xn_intr,
942 		    &info->txq[q], INTR_TYPE_NET | INTR_MPSAFE | INTR_ENTROPY,
943 		    &txq->xen_intr_handle);
944 
945 		if (error != 0) {
946 			device_printf(dev, "xen_intr_alloc_and_bind_local_port failed\n");
947 			goto fail_bind_port;
948 		}
949 	}
950 
951 	return (0);
952 
953 fail_bind_port:
954 	taskqueue_drain_all(txq->tq);
955 fail_start_thread:
956 	buf_ring_free(txq->br, M_DEVBUF);
957 	taskqueue_free(txq->tq);
958 	gnttab_end_foreign_access(txq->ring_ref, NULL);
959 fail_grant_ring:
960 	gnttab_free_grant_references(txq->gref_head);
961 	free(txq->ring.sring, M_DEVBUF);
962 fail:
963 	for (; q >= 0; q--) {
964 		disconnect_txq(&info->txq[q]);
965 		destroy_txq(&info->txq[q]);
966 	}
967 
968 	free(info->txq, M_DEVBUF);
969 	return (error);
970 }
971 
972 static int
973 setup_device(device_t dev, struct netfront_info *info,
974     unsigned long num_queues)
975 {
976 	int error;
977 	int q;
978 
979 	if (info->txq)
980 		destroy_txqs(info);
981 
982 	if (info->rxq)
983 		destroy_rxqs(info);
984 
985 	info->num_queues = 0;
986 
987 	error = setup_rxqs(dev, info, num_queues);
988 	if (error != 0)
989 		goto out;
990 	error = setup_txqs(dev, info, num_queues);
991 	if (error != 0)
992 		goto out;
993 
994 	info->num_queues = num_queues;
995 
996 	/* No split event channel at the moment. */
997 	for (q = 0; q < num_queues; q++)
998 		info->rxq[q].xen_intr_handle = info->txq[q].xen_intr_handle;
999 
1000 	return (0);
1001 
1002 out:
1003 	KASSERT(error != 0, ("Error path taken without providing an error code"));
1004 	return (error);
1005 }
1006 
1007 #ifdef INET
1008 static u_int
1009 netfront_addr_cb(void *arg, struct ifaddr *a, u_int count)
1010 {
1011 	arp_ifinit((if_t)arg, a);
1012 	return (1);
1013 }
1014 /**
1015  * If this interface has an ipv4 address, send an arp for it. This
1016  * helps to get the network going again after migrating hosts.
1017  */
1018 static void
1019 netfront_send_fake_arp(device_t dev, struct netfront_info *info)
1020 {
1021 	if_t ifp;
1022 
1023 	ifp = info->xn_ifp;
1024 	if_foreach_addr_type(ifp, AF_INET, netfront_addr_cb, ifp);
1025 }
1026 #endif
1027 
1028 /**
1029  * Callback received when the backend's state changes.
1030  */
1031 static void
1032 netfront_backend_changed(device_t dev, XenbusState newstate)
1033 {
1034 	struct netfront_info *sc = device_get_softc(dev);
1035 
1036 	DPRINTK("newstate=%d\n", newstate);
1037 
1038 	CURVNET_SET(if_getvnet(sc->xn_ifp));
1039 
1040 	switch (newstate) {
1041 	case XenbusStateInitialising:
1042 	case XenbusStateInitialised:
1043 	case XenbusStateUnknown:
1044 	case XenbusStateReconfigured:
1045 	case XenbusStateReconfiguring:
1046 		break;
1047 	case XenbusStateInitWait:
1048 		if (xenbus_get_state(dev) != XenbusStateInitialising)
1049 			break;
1050 		if (xn_connect(sc) != 0)
1051 			break;
1052 		/* Switch to connected state before kicking the rings. */
1053 		xenbus_set_state(sc->xbdev, XenbusStateConnected);
1054 		xn_kick_rings(sc);
1055 		break;
1056 	case XenbusStateClosing:
1057 		xenbus_set_state(dev, XenbusStateClosed);
1058 		break;
1059 	case XenbusStateClosed:
1060 		if (sc->xn_reset) {
1061 			netif_disconnect_backend(sc);
1062 			xenbus_set_state(dev, XenbusStateInitialising);
1063 			sc->xn_reset = false;
1064 		}
1065 		break;
1066 	case XenbusStateConnected:
1067 #ifdef INET
1068 		netfront_send_fake_arp(dev, sc);
1069 #endif
1070 		break;
1071 	}
1072 
1073 	CURVNET_RESTORE();
1074 }
1075 
1076 /**
1077  * \brief Verify that there is sufficient space in the Tx ring
1078  *        buffer for a maximally sized request to be enqueued.
1079  *
1080  * A transmit request requires a transmit descriptor for each packet
1081  * fragment, plus up to 2 entries for "options" (e.g. TSO).
1082  */
1083 static inline int
1084 xn_tx_slot_available(struct netfront_txq *txq)
1085 {
1086 
1087 	return (RING_FREE_REQUESTS(&txq->ring) > (MAX_TX_REQ_FRAGS + 2));
1088 }
1089 
1090 static void
1091 xn_release_tx_bufs(struct netfront_txq *txq)
1092 {
1093 	int i;
1094 
1095 	for (i = 1; i <= NET_TX_RING_SIZE; i++) {
1096 		struct mbuf *m;
1097 
1098 		m = txq->mbufs[i];
1099 
1100 		/*
1101 		 * We assume that no kernel addresses are
1102 		 * less than NET_TX_RING_SIZE.  Any entry
1103 		 * in the table that is below this number
1104 		 * must be an index from free-list tracking.
1105 		 */
1106 		if (((uintptr_t)m) <= NET_TX_RING_SIZE)
1107 			continue;
1108 		gnttab_end_foreign_access_ref(txq->grant_ref[i]);
1109 		gnttab_release_grant_reference(&txq->gref_head,
1110 		    txq->grant_ref[i]);
1111 		txq->grant_ref[i] = GRANT_REF_INVALID;
1112 		add_id_to_freelist(txq->mbufs, i);
1113 		txq->mbufs_cnt--;
1114 		if (txq->mbufs_cnt < 0) {
1115 			panic("%s: tx_chain_cnt must be >= 0", __func__);
1116 		}
1117 		mbuf_release(m);
1118 	}
1119 }
1120 
1121 static struct mbuf *
1122 xn_alloc_one_rx_buffer(struct netfront_rxq *rxq)
1123 {
1124 	struct mbuf *m;
1125 
1126 	m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
1127 	if (m == NULL)
1128 		return NULL;
1129 	m->m_len = m->m_pkthdr.len = MJUMPAGESIZE;
1130 
1131 	return (m);
1132 }
1133 
1134 static void
1135 xn_alloc_rx_buffers(struct netfront_rxq *rxq)
1136 {
1137 	RING_IDX req_prod;
1138 	int notify;
1139 
1140 	XN_RX_LOCK_ASSERT(rxq);
1141 
1142 	if (__predict_false(rxq->info->carrier == 0))
1143 		return;
1144 
1145 	for (req_prod = rxq->ring.req_prod_pvt;
1146 	     req_prod - rxq->ring.rsp_cons < NET_RX_RING_SIZE;
1147 	     req_prod++) {
1148 		struct mbuf *m;
1149 		unsigned short id;
1150 		grant_ref_t ref;
1151 		struct netif_rx_request *req;
1152 		unsigned long pfn;
1153 
1154 		m = xn_alloc_one_rx_buffer(rxq);
1155 		if (m == NULL)
1156 			break;
1157 
1158 		id = xn_rxidx(req_prod);
1159 
1160 		KASSERT(rxq->mbufs[id] == NULL, ("non-NULL xn_rx_chain"));
1161 		rxq->mbufs[id] = m;
1162 
1163 		ref = gnttab_claim_grant_reference(&rxq->gref_head);
1164 		KASSERT(ref != GNTTAB_LIST_END,
1165 		    ("reserved grant references exhuasted"));
1166 		rxq->grant_ref[id] = ref;
1167 
1168 		pfn = atop(vtophys(mtod(m, vm_offset_t)));
1169 		req = RING_GET_REQUEST(&rxq->ring, req_prod);
1170 
1171 		gnttab_grant_foreign_access_ref(ref,
1172 		    xenbus_get_otherend_id(rxq->info->xbdev), pfn, 0);
1173 		req->id = id;
1174 		req->gref = ref;
1175 	}
1176 
1177 	rxq->ring.req_prod_pvt = req_prod;
1178 
1179 	/* Not enough requests? Try again later. */
1180 	if (req_prod - rxq->ring.rsp_cons < NET_RX_SLOTS_MIN) {
1181 		callout_reset_curcpu(&rxq->rx_refill, hz/10,
1182 		    xn_alloc_rx_buffers_callout, rxq);
1183 		return;
1184 	}
1185 
1186 	wmb();		/* barrier so backend seens requests */
1187 
1188 	RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&rxq->ring, notify);
1189 	if (notify)
1190 		xen_intr_signal(rxq->xen_intr_handle);
1191 }
1192 
1193 static void xn_alloc_rx_buffers_callout(void *arg)
1194 {
1195 	struct netfront_rxq *rxq;
1196 
1197 	rxq = (struct netfront_rxq *)arg;
1198 	XN_RX_LOCK(rxq);
1199 	xn_alloc_rx_buffers(rxq);
1200 	XN_RX_UNLOCK(rxq);
1201 }
1202 
1203 static void
1204 xn_release_rx_bufs(struct netfront_rxq *rxq)
1205 {
1206 	int i,  ref;
1207 	struct mbuf *m;
1208 
1209 	for (i = 0; i < NET_RX_RING_SIZE; i++) {
1210 		m = rxq->mbufs[i];
1211 
1212 		if (m == NULL)
1213 			continue;
1214 
1215 		ref = rxq->grant_ref[i];
1216 		if (ref == GRANT_REF_INVALID)
1217 			continue;
1218 
1219 		gnttab_end_foreign_access_ref(ref);
1220 		gnttab_release_grant_reference(&rxq->gref_head, ref);
1221 		rxq->mbufs[i] = NULL;
1222 		rxq->grant_ref[i] = GRANT_REF_INVALID;
1223 		m_freem(m);
1224 	}
1225 }
1226 
1227 static void
1228 xn_rxeof(struct netfront_rxq *rxq)
1229 {
1230 	if_t ifp;
1231 	struct netfront_info *np = rxq->info;
1232 #if (defined(INET) || defined(INET6))
1233 	struct lro_ctrl *lro = &rxq->lro;
1234 #endif
1235 	struct netfront_rx_info rinfo;
1236 	struct netif_rx_response *rx = &rinfo.rx;
1237 	struct netif_extra_info *extras = rinfo.extras;
1238 	RING_IDX i, rp;
1239 	struct mbuf *m;
1240 	struct mbufq mbufq_rxq, mbufq_errq;
1241 	int err, work_to_do;
1242 
1243 	XN_RX_LOCK_ASSERT(rxq);
1244 
1245 	if (!netfront_carrier_ok(np))
1246 		return;
1247 
1248 	/* XXX: there should be some sane limit. */
1249 	mbufq_init(&mbufq_errq, INT_MAX);
1250 	mbufq_init(&mbufq_rxq, INT_MAX);
1251 
1252 	ifp = np->xn_ifp;
1253 
1254 	do {
1255 		rp = rxq->ring.sring->rsp_prod;
1256 		rmb();	/* Ensure we see queued responses up to 'rp'. */
1257 
1258 		i = rxq->ring.rsp_cons;
1259 		while ((i != rp)) {
1260 			memcpy(rx, RING_GET_RESPONSE(&rxq->ring, i), sizeof(*rx));
1261 			memset(extras, 0, sizeof(rinfo.extras));
1262 
1263 			m = NULL;
1264 			err = xn_get_responses(rxq, &rinfo, rp, &i, &m);
1265 
1266 			if (__predict_false(err)) {
1267 				if (m)
1268 					(void )mbufq_enqueue(&mbufq_errq, m);
1269 				if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1270 				continue;
1271 			}
1272 
1273 			m->m_pkthdr.rcvif = ifp;
1274 			if (rx->flags & NETRXF_data_validated) {
1275 				/*
1276 				 * According to mbuf(9) the correct way to tell
1277 				 * the stack that the checksum of an inbound
1278 				 * packet is correct, without it actually being
1279 				 * present (because the underlying interface
1280 				 * doesn't provide it), is to set the
1281 				 * CSUM_DATA_VALID and CSUM_PSEUDO_HDR flags,
1282 				 * and the csum_data field to 0xffff.
1283 				 */
1284 				m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID
1285 				    | CSUM_PSEUDO_HDR);
1286 				m->m_pkthdr.csum_data = 0xffff;
1287 			}
1288 			if ((rx->flags & NETRXF_extra_info) != 0 &&
1289 			    (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type ==
1290 			    XEN_NETIF_EXTRA_TYPE_GSO)) {
1291 				m->m_pkthdr.tso_segsz =
1292 				extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].u.gso.size;
1293 				m->m_pkthdr.csum_flags |= CSUM_TSO;
1294 			}
1295 
1296 			(void )mbufq_enqueue(&mbufq_rxq, m);
1297 		}
1298 
1299 		rxq->ring.rsp_cons = i;
1300 
1301 		xn_alloc_rx_buffers(rxq);
1302 
1303 		RING_FINAL_CHECK_FOR_RESPONSES(&rxq->ring, work_to_do);
1304 	} while (work_to_do);
1305 
1306 	mbufq_drain(&mbufq_errq);
1307 	/*
1308 	 * Process all the mbufs after the remapping is complete.
1309 	 * Break the mbuf chain first though.
1310 	 */
1311 	while ((m = mbufq_dequeue(&mbufq_rxq)) != NULL) {
1312 		if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
1313 #if (defined(INET) || defined(INET6))
1314 		/* Use LRO if possible */
1315 		if ((if_getcapenable(ifp) & IFCAP_LRO) == 0 ||
1316 		    lro->lro_cnt == 0 || tcp_lro_rx(lro, m, 0)) {
1317 			/*
1318 			 * If LRO fails, pass up to the stack
1319 			 * directly.
1320 			 */
1321 			if_input(ifp, m);
1322 		}
1323 #else
1324 		if_input(ifp, m);
1325 #endif
1326 	}
1327 
1328 #if (defined(INET) || defined(INET6))
1329 	/*
1330 	 * Flush any outstanding LRO work
1331 	 */
1332 	tcp_lro_flush_all(lro);
1333 #endif
1334 }
1335 
1336 static void
1337 xn_txeof(struct netfront_txq *txq)
1338 {
1339 	RING_IDX i, prod;
1340 	unsigned short id;
1341 	if_t ifp;
1342 	netif_tx_response_t *txr;
1343 	struct mbuf *m;
1344 	struct netfront_info *np = txq->info;
1345 
1346 	XN_TX_LOCK_ASSERT(txq);
1347 
1348 	if (!netfront_carrier_ok(np))
1349 		return;
1350 
1351 	ifp = np->xn_ifp;
1352 
1353 	do {
1354 		prod = txq->ring.sring->rsp_prod;
1355 		rmb(); /* Ensure we see responses up to 'rp'. */
1356 
1357 		for (i = txq->ring.rsp_cons; i != prod; i++) {
1358 			txr = RING_GET_RESPONSE(&txq->ring, i);
1359 			if (txr->status == NETIF_RSP_NULL)
1360 				continue;
1361 
1362 			if (txr->status != NETIF_RSP_OKAY) {
1363 				printf("%s: WARNING: response is %d!\n",
1364 				       __func__, txr->status);
1365 			}
1366 			id = txr->id;
1367 			m = txq->mbufs[id];
1368 			KASSERT(m != NULL, ("mbuf not found in chain"));
1369 			KASSERT((uintptr_t)m > NET_TX_RING_SIZE,
1370 				("mbuf already on the free list, but we're "
1371 				"trying to free it again!"));
1372 			M_ASSERTVALID(m);
1373 
1374 			if (__predict_false(gnttab_query_foreign_access(
1375 			    txq->grant_ref[id]) != 0)) {
1376 				panic("%s: grant id %u still in use by the "
1377 				    "backend", __func__, id);
1378 			}
1379 			gnttab_end_foreign_access_ref(txq->grant_ref[id]);
1380 			gnttab_release_grant_reference(
1381 				&txq->gref_head, txq->grant_ref[id]);
1382 			txq->grant_ref[id] = GRANT_REF_INVALID;
1383 
1384 			txq->mbufs[id] = NULL;
1385 			add_id_to_freelist(txq->mbufs, id);
1386 			txq->mbufs_cnt--;
1387 			mbuf_release(m);
1388 			/* Only mark the txq active if we've freed up at least one slot to try */
1389 			if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
1390 		}
1391 		txq->ring.rsp_cons = prod;
1392 
1393 		/*
1394 		 * Set a new event, then check for race with update of
1395 		 * tx_cons. Note that it is essential to schedule a
1396 		 * callback, no matter how few buffers are pending. Even if
1397 		 * there is space in the transmit ring, higher layers may
1398 		 * be blocked because too much data is outstanding: in such
1399 		 * cases notification from Xen is likely to be the only kick
1400 		 * that we'll get.
1401 		 */
1402 		txq->ring.sring->rsp_event =
1403 		    prod + ((txq->ring.sring->req_prod - prod) >> 1) + 1;
1404 
1405 		mb();
1406 	} while (prod != txq->ring.sring->rsp_prod);
1407 
1408 	if (txq->full &&
1409 	    ((txq->ring.sring->req_prod - prod) < NET_TX_RING_SIZE)) {
1410 		txq->full = false;
1411 		xn_txq_start(txq);
1412 	}
1413 }
1414 
1415 static void
1416 xn_intr(void *xsc)
1417 {
1418 	struct netfront_txq *txq = xsc;
1419 	struct netfront_info *np = txq->info;
1420 	struct netfront_rxq *rxq = &np->rxq[txq->id];
1421 
1422 	/* kick both tx and rx */
1423 	xn_rxq_intr(rxq);
1424 	xn_txq_intr(txq);
1425 }
1426 
1427 static void
1428 xn_move_rx_slot(struct netfront_rxq *rxq, struct mbuf *m,
1429     grant_ref_t ref)
1430 {
1431 	int new = xn_rxidx(rxq->ring.req_prod_pvt);
1432 
1433 	KASSERT(rxq->mbufs[new] == NULL, ("mbufs != NULL"));
1434 	rxq->mbufs[new] = m;
1435 	rxq->grant_ref[new] = ref;
1436 	RING_GET_REQUEST(&rxq->ring, rxq->ring.req_prod_pvt)->id = new;
1437 	RING_GET_REQUEST(&rxq->ring, rxq->ring.req_prod_pvt)->gref = ref;
1438 	rxq->ring.req_prod_pvt++;
1439 }
1440 
1441 static int
1442 xn_get_extras(struct netfront_rxq *rxq,
1443     struct netif_extra_info *extras, RING_IDX rp, RING_IDX *cons)
1444 {
1445 	struct netif_extra_info *extra;
1446 
1447 	int err = 0;
1448 
1449 	do {
1450 		struct mbuf *m;
1451 		grant_ref_t ref;
1452 
1453 		if (__predict_false(*cons + 1 == rp)) {
1454 			err = EINVAL;
1455 			break;
1456 		}
1457 
1458 		extra = (struct netif_extra_info *)
1459 		RING_GET_RESPONSE(&rxq->ring, ++(*cons));
1460 
1461 		if (__predict_false(!extra->type ||
1462 			extra->type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
1463 			err = EINVAL;
1464 		} else {
1465 			memcpy(&extras[extra->type - 1], extra, sizeof(*extra));
1466 		}
1467 
1468 		m = xn_get_rx_mbuf(rxq, *cons);
1469 		ref = xn_get_rx_ref(rxq,  *cons);
1470 		xn_move_rx_slot(rxq, m, ref);
1471 	} while (extra->flags & XEN_NETIF_EXTRA_FLAG_MORE);
1472 
1473 	return err;
1474 }
1475 
1476 static int
1477 xn_get_responses(struct netfront_rxq *rxq,
1478     struct netfront_rx_info *rinfo, RING_IDX rp, RING_IDX *cons,
1479     struct mbuf  **list)
1480 {
1481 	struct netif_rx_response *rx = &rinfo->rx;
1482 	struct netif_extra_info *extras = rinfo->extras;
1483 	struct mbuf *m, *m0, *m_prev;
1484 	grant_ref_t ref = xn_get_rx_ref(rxq, *cons);
1485 	int frags = 1;
1486 	int err = 0;
1487 	u_long ret __diagused;
1488 
1489 	m0 = m = m_prev = xn_get_rx_mbuf(rxq, *cons);
1490 
1491 	if (rx->flags & NETRXF_extra_info) {
1492 		err = xn_get_extras(rxq, extras, rp, cons);
1493 	}
1494 
1495 	if (m0 != NULL) {
1496 		m0->m_pkthdr.len = 0;
1497 		m0->m_next = NULL;
1498 	}
1499 
1500 	for (;;) {
1501 #if 0
1502 		DPRINTK("rx->status=%hd rx->offset=%hu frags=%u\n",
1503 			rx->status, rx->offset, frags);
1504 #endif
1505 		if (__predict_false(rx->status < 0 ||
1506 			rx->offset + rx->status > PAGE_SIZE)) {
1507 			xn_move_rx_slot(rxq, m, ref);
1508 			if (m0 == m)
1509 				m0 = NULL;
1510 			m = NULL;
1511 			err = EINVAL;
1512 			goto next_skip_queue;
1513 		}
1514 
1515 		/*
1516 		 * This definitely indicates a bug, either in this driver or in
1517 		 * the backend driver. In future this should flag the bad
1518 		 * situation to the system controller to reboot the backed.
1519 		 */
1520 		if (ref == GRANT_REF_INVALID) {
1521 			printf("%s: Bad rx response id %d.\n", __func__, rx->id);
1522 			err = EINVAL;
1523 			goto next;
1524 		}
1525 
1526 		ret = gnttab_end_foreign_access_ref(ref);
1527 		KASSERT(ret, ("Unable to end access to grant references"));
1528 
1529 		gnttab_release_grant_reference(&rxq->gref_head, ref);
1530 
1531 next:
1532 		if (m == NULL)
1533 			break;
1534 
1535 		m->m_len = rx->status;
1536 		m->m_data += rx->offset;
1537 		m0->m_pkthdr.len += rx->status;
1538 
1539 next_skip_queue:
1540 		if (!(rx->flags & NETRXF_more_data))
1541 			break;
1542 
1543 		if (*cons + frags == rp) {
1544 			if (net_ratelimit())
1545 				WPRINTK("Need more frags\n");
1546 			err = ENOENT;
1547 			printf("%s: cons %u frags %u rp %u, not enough frags\n",
1548 			       __func__, *cons, frags, rp);
1549 			break;
1550 		}
1551 		/*
1552 		 * Note that m can be NULL, if rx->status < 0 or if
1553 		 * rx->offset + rx->status > PAGE_SIZE above.
1554 		 */
1555 		m_prev = m;
1556 
1557 		rx = RING_GET_RESPONSE(&rxq->ring, *cons + frags);
1558 		m = xn_get_rx_mbuf(rxq, *cons + frags);
1559 
1560 		/*
1561 		 * m_prev == NULL can happen if rx->status < 0 or if
1562 		 * rx->offset + * rx->status > PAGE_SIZE above.
1563 		 */
1564 		if (m_prev != NULL)
1565 			m_prev->m_next = m;
1566 
1567 		/*
1568 		 * m0 can be NULL if rx->status < 0 or if * rx->offset +
1569 		 * rx->status > PAGE_SIZE above.
1570 		 */
1571 		if (m0 == NULL)
1572 			m0 = m;
1573 		m->m_next = NULL;
1574 		ref = xn_get_rx_ref(rxq, *cons + frags);
1575 		frags++;
1576 	}
1577 	*list = m0;
1578 	*cons += frags;
1579 
1580 	return (err);
1581 }
1582 
1583 /**
1584  * Given an mbuf chain, make sure we have enough room and then push
1585  * it onto the transmit ring.
1586  */
1587 static int
1588 xn_assemble_tx_request(struct netfront_txq *txq, struct mbuf *m_head)
1589 {
1590 	struct netfront_info *np = txq->info;
1591 	if_t ifp = np->xn_ifp;
1592 	int otherend_id, error, nfrags;
1593 	bus_dma_segment_t *segs = txq->segs;
1594 	struct mbuf_xennet *tag;
1595 	bus_dmamap_t map;
1596 	unsigned int i;
1597 
1598 	KASSERT(!SLIST_EMPTY(&txq->tags), ("no tags available"));
1599 	tag = SLIST_FIRST(&txq->tags);
1600 	SLIST_REMOVE_HEAD(&txq->tags, next);
1601 	KASSERT(tag->count == 0, ("tag already in-use"));
1602 	map = tag->dma_map;
1603 	error = bus_dmamap_load_mbuf_sg(np->dma_tag, map, m_head, segs,
1604 	    &nfrags, 0);
1605 	if (error == EFBIG || nfrags > np->maxfrags) {
1606 		struct mbuf *m;
1607 
1608 		bus_dmamap_unload(np->dma_tag, map);
1609 		m = m_defrag(m_head, M_NOWAIT);
1610 		if (!m) {
1611 			/*
1612 			 * Defrag failed, so free the mbuf and
1613 			 * therefore drop the packet.
1614 			 */
1615 			SLIST_INSERT_HEAD(&txq->tags, tag, next);
1616 			m_freem(m_head);
1617 			return (EMSGSIZE);
1618 		}
1619 		m_head = m;
1620 		error = bus_dmamap_load_mbuf_sg(np->dma_tag, map, m_head, segs,
1621 		    &nfrags, 0);
1622 		if (error != 0 || nfrags > np->maxfrags) {
1623 			bus_dmamap_unload(np->dma_tag, map);
1624 			SLIST_INSERT_HEAD(&txq->tags, tag, next);
1625 			m_freem(m_head);
1626 			return (error ?: EFBIG);
1627 		}
1628 	} else if (error != 0) {
1629 		SLIST_INSERT_HEAD(&txq->tags, tag, next);
1630 		m_freem(m_head);
1631 		return (error);
1632 	}
1633 
1634 	/**
1635 	 * The FreeBSD TCP stack, with TSO enabled, can produce a chain
1636 	 * of mbufs longer than Linux can handle.  Make sure we don't
1637 	 * pass a too-long chain over to the other side by dropping the
1638 	 * packet.  It doesn't look like there is currently a way to
1639 	 * tell the TCP stack to generate a shorter chain of packets.
1640 	 */
1641 	if (nfrags > MAX_TX_REQ_FRAGS) {
1642 #ifdef DEBUG
1643 		printf("%s: nfrags %d > MAX_TX_REQ_FRAGS %d, netback "
1644 		       "won't be able to handle it, dropping\n",
1645 		       __func__, nfrags, MAX_TX_REQ_FRAGS);
1646 #endif
1647 		SLIST_INSERT_HEAD(&txq->tags, tag, next);
1648 		bus_dmamap_unload(np->dma_tag, map);
1649 		m_freem(m_head);
1650 		return (EMSGSIZE);
1651 	}
1652 
1653 	/*
1654 	 * This check should be redundant.  We've already verified that we
1655 	 * have enough slots in the ring to handle a packet of maximum
1656 	 * size, and that our packet is less than the maximum size.  Keep
1657 	 * it in here as an assert for now just to make certain that
1658 	 * chain_cnt is accurate.
1659 	 */
1660 	KASSERT((txq->mbufs_cnt + nfrags) <= NET_TX_RING_SIZE,
1661 		("%s: chain_cnt (%d) + nfrags (%d) > NET_TX_RING_SIZE "
1662 		 "(%d)!", __func__, (int) txq->mbufs_cnt,
1663                     (int) nfrags, (int) NET_TX_RING_SIZE));
1664 
1665 	/*
1666 	 * Start packing the mbufs in this chain into
1667 	 * the fragment pointers. Stop when we run out
1668 	 * of fragments or hit the end of the mbuf chain.
1669 	 */
1670 	otherend_id = xenbus_get_otherend_id(np->xbdev);
1671 	m_tag_prepend(m_head, &tag->tag);
1672 	for (i = 0; i < nfrags; i++) {
1673 		netif_tx_request_t *tx;
1674 		uintptr_t id;
1675 		grant_ref_t ref;
1676 		u_long mfn; /* XXX Wrong type? */
1677 
1678 		tx = RING_GET_REQUEST(&txq->ring, txq->ring.req_prod_pvt);
1679 		id = get_id_from_freelist(txq->mbufs);
1680 		if (id == 0)
1681 			panic("%s: was allocated the freelist head!\n",
1682 			    __func__);
1683 		txq->mbufs_cnt++;
1684 		if (txq->mbufs_cnt > NET_TX_RING_SIZE)
1685 			panic("%s: tx_chain_cnt must be <= NET_TX_RING_SIZE\n",
1686 			    __func__);
1687 		mbuf_grab(m_head);
1688 		txq->mbufs[id] = m_head;
1689 		tx->id = id;
1690 		ref = gnttab_claim_grant_reference(&txq->gref_head);
1691 		KASSERT((short)ref >= 0, ("Negative ref"));
1692 		mfn = atop(segs[i].ds_addr);
1693 		gnttab_grant_foreign_access_ref(ref, otherend_id,
1694 		    mfn, GNTMAP_readonly);
1695 		tx->gref = txq->grant_ref[id] = ref;
1696 		tx->offset = segs[i].ds_addr & PAGE_MASK;
1697 		KASSERT(tx->offset + segs[i].ds_len <= PAGE_SIZE,
1698 		    ("mbuf segment crosses a page boundary"));
1699 		tx->flags = 0;
1700 		if (i == 0) {
1701 			/*
1702 			 * The first fragment has the entire packet
1703 			 * size, subsequent fragments have just the
1704 			 * fragment size. The backend works out the
1705 			 * true size of the first fragment by
1706 			 * subtracting the sizes of the other
1707 			 * fragments.
1708 			 */
1709 			tx->size = m_head->m_pkthdr.len;
1710 
1711 			/*
1712 			 * The first fragment contains the checksum flags
1713 			 * and is optionally followed by extra data for
1714 			 * TSO etc.
1715 			 */
1716 			/**
1717 			 * CSUM_TSO requires checksum offloading.
1718 			 * Some versions of FreeBSD fail to
1719 			 * set CSUM_TCP in the CSUM_TSO case,
1720 			 * so we have to test for CSUM_TSO
1721 			 * explicitly.
1722 			 */
1723 			if (m_head->m_pkthdr.csum_flags
1724 			    & (CSUM_DELAY_DATA | CSUM_TSO)) {
1725 				tx->flags |= (NETTXF_csum_blank
1726 				    | NETTXF_data_validated);
1727 			}
1728 			if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
1729 				struct netif_extra_info *gso =
1730 					(struct netif_extra_info *)
1731 					RING_GET_REQUEST(&txq->ring,
1732 							 ++txq->ring.req_prod_pvt);
1733 
1734 				tx->flags |= NETTXF_extra_info;
1735 
1736 				gso->u.gso.size = m_head->m_pkthdr.tso_segsz;
1737 				gso->u.gso.type =
1738 					XEN_NETIF_GSO_TYPE_TCPV4;
1739 				gso->u.gso.pad = 0;
1740 				gso->u.gso.features = 0;
1741 
1742 				gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
1743 				gso->flags = 0;
1744 			}
1745 		} else {
1746 			tx->size = segs[i].ds_len;
1747 		}
1748 		if (i != nfrags - 1)
1749 			tx->flags |= NETTXF_more_data;
1750 
1751 		txq->ring.req_prod_pvt++;
1752 	}
1753 	bus_dmamap_sync(np->dma_tag, map, BUS_DMASYNC_PREWRITE);
1754 	BPF_MTAP(ifp, m_head);
1755 
1756 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1757 	if_inc_counter(ifp, IFCOUNTER_OBYTES, m_head->m_pkthdr.len);
1758 	if (m_head->m_flags & M_MCAST)
1759 		if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
1760 
1761 	xn_txeof(txq);
1762 
1763 	return (0);
1764 }
1765 
1766 /* equivalent of network_open() in Linux */
1767 static void
1768 xn_ifinit_locked(struct netfront_info *np)
1769 {
1770 	if_t ifp;
1771 	int i;
1772 	struct netfront_rxq *rxq;
1773 
1774 	XN_LOCK_ASSERT(np);
1775 
1776 	ifp = np->xn_ifp;
1777 
1778 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING || !netfront_carrier_ok(np))
1779 		return;
1780 
1781 	xn_stop(np);
1782 
1783 	for (i = 0; i < np->num_queues; i++) {
1784 		rxq = &np->rxq[i];
1785 		XN_RX_LOCK(rxq);
1786 		xn_alloc_rx_buffers(rxq);
1787 		rxq->ring.sring->rsp_event = rxq->ring.rsp_cons + 1;
1788 		if (RING_HAS_UNCONSUMED_RESPONSES(&rxq->ring))
1789 			xn_rxeof(rxq);
1790 		XN_RX_UNLOCK(rxq);
1791 	}
1792 
1793 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
1794 	if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
1795 	if_link_state_change(ifp, LINK_STATE_UP);
1796 }
1797 
1798 static void
1799 xn_ifinit(void *xsc)
1800 {
1801 	struct netfront_info *sc = xsc;
1802 
1803 	XN_LOCK(sc);
1804 	xn_ifinit_locked(sc);
1805 	XN_UNLOCK(sc);
1806 }
1807 
1808 static int
1809 xn_ioctl(if_t ifp, u_long cmd, caddr_t data)
1810 {
1811 	struct netfront_info *sc = if_getsoftc(ifp);
1812 	struct ifreq *ifr = (struct ifreq *) data;
1813 	device_t dev;
1814 #ifdef INET
1815 	struct ifaddr *ifa = (struct ifaddr *)data;
1816 #endif
1817 	int mask, error = 0, reinit;
1818 
1819 	dev = sc->xbdev;
1820 
1821 	switch(cmd) {
1822 	case SIOCSIFADDR:
1823 #ifdef INET
1824 		XN_LOCK(sc);
1825 		if (ifa->ifa_addr->sa_family == AF_INET) {
1826 			if_setflagbits(ifp, IFF_UP, 0);
1827 			if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
1828 				xn_ifinit_locked(sc);
1829 			arp_ifinit(ifp, ifa);
1830 			XN_UNLOCK(sc);
1831 		} else {
1832 			XN_UNLOCK(sc);
1833 #endif
1834 			error = ether_ioctl(ifp, cmd, data);
1835 #ifdef INET
1836 		}
1837 #endif
1838 		break;
1839 	case SIOCSIFMTU:
1840 		if (if_getmtu(ifp) == ifr->ifr_mtu)
1841 			break;
1842 
1843 		if_setmtu(ifp, ifr->ifr_mtu);
1844 		if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
1845 		xn_ifinit(sc);
1846 		break;
1847 	case SIOCSIFFLAGS:
1848 		XN_LOCK(sc);
1849 		if (if_getflags(ifp) & IFF_UP) {
1850 			/*
1851 			 * If only the state of the PROMISC flag changed,
1852 			 * then just use the 'set promisc mode' command
1853 			 * instead of reinitializing the entire NIC. Doing
1854 			 * a full re-init means reloading the firmware and
1855 			 * waiting for it to start up, which may take a
1856 			 * second or two.
1857 			 */
1858 			xn_ifinit_locked(sc);
1859 		} else {
1860 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
1861 				xn_stop(sc);
1862 			}
1863 		}
1864 		sc->xn_if_flags = if_getflags(ifp);
1865 		XN_UNLOCK(sc);
1866 		break;
1867 	case SIOCSIFCAP:
1868 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
1869 		reinit = 0;
1870 
1871 		if (mask & IFCAP_TXCSUM) {
1872 			if_togglecapenable(ifp, IFCAP_TXCSUM);
1873 			if_togglehwassist(ifp, XN_CSUM_FEATURES);
1874 		}
1875 		if (mask & IFCAP_TSO4) {
1876 			if_togglecapenable(ifp, IFCAP_TSO4);
1877 			if_togglehwassist(ifp, CSUM_TSO);
1878 		}
1879 
1880 		if (mask & (IFCAP_RXCSUM | IFCAP_LRO)) {
1881 			/* These Rx features require us to renegotiate. */
1882 			reinit = 1;
1883 
1884 			if (mask & IFCAP_RXCSUM)
1885 				if_togglecapenable(ifp, IFCAP_RXCSUM);
1886 			if (mask & IFCAP_LRO)
1887 				if_togglecapenable(ifp, IFCAP_LRO);
1888 		}
1889 
1890 		if (reinit == 0)
1891 			break;
1892 
1893 		/*
1894 		 * We must reset the interface so the backend picks up the
1895 		 * new features.
1896 		 */
1897 		device_printf(sc->xbdev,
1898 		    "performing interface reset due to feature change\n");
1899 		XN_LOCK(sc);
1900 		netfront_carrier_off(sc);
1901 		sc->xn_reset = true;
1902 		/*
1903 		 * NB: the pending packet queue is not flushed, since
1904 		 * the interface should still support the old options.
1905 		 */
1906 		XN_UNLOCK(sc);
1907 		/*
1908 		 * Delete the xenstore nodes that export features.
1909 		 *
1910 		 * NB: There's a xenbus state called
1911 		 * "XenbusStateReconfiguring", which is what we should set
1912 		 * here. Sadly none of the backends know how to handle it,
1913 		 * and simply disconnect from the frontend, so we will just
1914 		 * switch back to XenbusStateInitialising in order to force
1915 		 * a reconnection.
1916 		 */
1917 		xs_rm(XST_NIL, xenbus_get_node(dev), "feature-gso-tcpv4");
1918 		xs_rm(XST_NIL, xenbus_get_node(dev), "feature-no-csum-offload");
1919 		xenbus_set_state(dev, XenbusStateClosing);
1920 
1921 		/*
1922 		 * Wait for the frontend to reconnect before returning
1923 		 * from the ioctl. 30s should be more than enough for any
1924 		 * sane backend to reconnect.
1925 		 */
1926 		error = tsleep(sc, 0, "xn_rst", 30*hz);
1927 		break;
1928 	case SIOCADDMULTI:
1929 	case SIOCDELMULTI:
1930 		break;
1931 	case SIOCSIFMEDIA:
1932 	case SIOCGIFMEDIA:
1933 		error = ifmedia_ioctl(ifp, ifr, &sc->sc_media, cmd);
1934 		break;
1935 	default:
1936 		error = ether_ioctl(ifp, cmd, data);
1937 	}
1938 
1939 	return (error);
1940 }
1941 
1942 static void
1943 xn_stop(struct netfront_info *sc)
1944 {
1945 	if_t ifp;
1946 
1947 	XN_LOCK_ASSERT(sc);
1948 
1949 	ifp = sc->xn_ifp;
1950 
1951 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1952 	if_link_state_change(ifp, LINK_STATE_DOWN);
1953 }
1954 
1955 static void
1956 xn_rebuild_rx_bufs(struct netfront_rxq *rxq)
1957 {
1958 	int requeue_idx, i;
1959 	grant_ref_t ref;
1960 	netif_rx_request_t *req;
1961 
1962 	for (requeue_idx = 0, i = 0; i < NET_RX_RING_SIZE; i++) {
1963 		struct mbuf *m;
1964 		u_long pfn;
1965 
1966 		if (rxq->mbufs[i] == NULL)
1967 			continue;
1968 
1969 		m = rxq->mbufs[requeue_idx] = xn_get_rx_mbuf(rxq, i);
1970 		ref = rxq->grant_ref[requeue_idx] = xn_get_rx_ref(rxq, i);
1971 
1972 		req = RING_GET_REQUEST(&rxq->ring, requeue_idx);
1973 		pfn = vtophys(mtod(m, vm_offset_t)) >> PAGE_SHIFT;
1974 
1975 		gnttab_grant_foreign_access_ref(ref,
1976 		    xenbus_get_otherend_id(rxq->info->xbdev),
1977 		    pfn, 0);
1978 
1979 		req->gref = ref;
1980 		req->id   = requeue_idx;
1981 
1982 		requeue_idx++;
1983 	}
1984 
1985 	rxq->ring.req_prod_pvt = requeue_idx;
1986 }
1987 
1988 /* START of Xenolinux helper functions adapted to FreeBSD */
1989 static int
1990 xn_connect(struct netfront_info *np)
1991 {
1992 	int i, error;
1993 	u_int feature_rx_copy;
1994 	struct netfront_rxq *rxq;
1995 	struct netfront_txq *txq;
1996 
1997 	error = xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
1998 	    "feature-rx-copy", NULL, "%u", &feature_rx_copy);
1999 	if (error != 0)
2000 		feature_rx_copy = 0;
2001 
2002 	/* We only support rx copy. */
2003 	if (!feature_rx_copy)
2004 		return (EPROTONOSUPPORT);
2005 
2006 	/* Recovery procedure: */
2007 	error = talk_to_backend(np->xbdev, np);
2008 	if (error != 0)
2009 		return (error);
2010 
2011 	/* Step 1: Reinitialise variables. */
2012 	xn_query_features(np);
2013 	xn_configure_features(np);
2014 
2015 	/* Step 2: Release TX buffer */
2016 	for (i = 0; i < np->num_queues; i++) {
2017 		txq = &np->txq[i];
2018 		xn_release_tx_bufs(txq);
2019 	}
2020 
2021 	/* Step 3: Rebuild the RX buffer freelist and the RX ring itself. */
2022 	for (i = 0; i < np->num_queues; i++) {
2023 		rxq = &np->rxq[i];
2024 		xn_rebuild_rx_bufs(rxq);
2025 	}
2026 
2027 	/* Step 4: All public and private state should now be sane.  Get
2028 	 * ready to start sending and receiving packets and give the driver
2029 	 * domain a kick because we've probably just requeued some
2030 	 * packets.
2031 	 */
2032 	netfront_carrier_on(np);
2033 	wakeup(np);
2034 
2035 	return (0);
2036 }
2037 
2038 static void
2039 xn_kick_rings(struct netfront_info *np)
2040 {
2041 	struct netfront_rxq *rxq;
2042 	struct netfront_txq *txq;
2043 	int i;
2044 
2045 	for (i = 0; i < np->num_queues; i++) {
2046 		txq = &np->txq[i];
2047 		rxq = &np->rxq[i];
2048 		xen_intr_signal(txq->xen_intr_handle);
2049 		XN_TX_LOCK(txq);
2050 		xn_txeof(txq);
2051 		XN_TX_UNLOCK(txq);
2052 		XN_RX_LOCK(rxq);
2053 		xn_alloc_rx_buffers(rxq);
2054 		XN_RX_UNLOCK(rxq);
2055 	}
2056 }
2057 
2058 static void
2059 xn_query_features(struct netfront_info *np)
2060 {
2061 	int val;
2062 
2063 	device_printf(np->xbdev, "backend features:");
2064 
2065 	if (xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
2066 		"feature-sg", NULL, "%d", &val) != 0)
2067 		val = 0;
2068 
2069 	np->maxfrags = 1;
2070 	if (val) {
2071 		np->maxfrags = MAX_TX_REQ_FRAGS;
2072 		printf(" feature-sg");
2073 	}
2074 
2075 	if (xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
2076 		"feature-gso-tcpv4", NULL, "%d", &val) != 0)
2077 		val = 0;
2078 
2079 	if_setcapabilitiesbit(np->xn_ifp, 0, IFCAP_TSO4 | IFCAP_LRO);
2080 	if (val) {
2081 		if_setcapabilitiesbit(np->xn_ifp, IFCAP_TSO4 | IFCAP_LRO, 0);
2082 		printf(" feature-gso-tcp4");
2083 	}
2084 
2085 	/*
2086 	 * HW CSUM offload is assumed to be available unless
2087 	 * feature-no-csum-offload is set in xenstore.
2088 	 */
2089 	if (xs_scanf(XST_NIL, xenbus_get_otherend_path(np->xbdev),
2090 		"feature-no-csum-offload", NULL, "%d", &val) != 0)
2091 		val = 0;
2092 
2093 	if_setcapabilitiesbit(np->xn_ifp, IFCAP_HWCSUM, 0);
2094 	if (val) {
2095 		if_setcapabilitiesbit(np->xn_ifp, 0, IFCAP_HWCSUM);
2096 		printf(" feature-no-csum-offload");
2097 	}
2098 
2099 	printf("\n");
2100 }
2101 
2102 static int
2103 xn_configure_features(struct netfront_info *np)
2104 {
2105 	int err, cap_enabled;
2106 #if (defined(INET) || defined(INET6))
2107 	int i;
2108 #endif
2109 	if_t ifp;
2110 
2111 	ifp = np->xn_ifp;
2112 	err = 0;
2113 
2114 	if ((if_getcapenable(ifp) & if_getcapabilities(ifp)) == if_getcapenable(ifp)) {
2115 		/* Current options are available, no need to do anything. */
2116 		return (0);
2117 	}
2118 
2119 	/* Try to preserve as many options as possible. */
2120 	cap_enabled = if_getcapenable(ifp);
2121 	if_setcapenable(ifp, 0);
2122 	if_sethwassist(ifp, 0);
2123 
2124 #if (defined(INET) || defined(INET6))
2125 	if ((cap_enabled & IFCAP_LRO) != 0)
2126 		for (i = 0; i < np->num_queues; i++)
2127 			tcp_lro_free(&np->rxq[i].lro);
2128 	if (xn_enable_lro &&
2129 	    (if_getcapabilities(ifp) & cap_enabled & IFCAP_LRO) != 0) {
2130 	    	if_setcapenablebit(ifp, IFCAP_LRO, 0);
2131 		for (i = 0; i < np->num_queues; i++) {
2132 			err = tcp_lro_init(&np->rxq[i].lro);
2133 			if (err != 0) {
2134 				device_printf(np->xbdev,
2135 				    "LRO initialization failed\n");
2136 				if_setcapenablebit(ifp, 0, IFCAP_LRO);
2137 				break;
2138 			}
2139 			np->rxq[i].lro.ifp = ifp;
2140 		}
2141 	}
2142 	if ((if_getcapabilities(ifp) & cap_enabled & IFCAP_TSO4) != 0) {
2143 		if_setcapenablebit(ifp, IFCAP_TSO4, 0);
2144 		if_sethwassistbits(ifp, CSUM_TSO, 0);
2145 	}
2146 #endif
2147 	if ((if_getcapabilities(ifp) & cap_enabled & IFCAP_TXCSUM) != 0) {
2148 		if_setcapenablebit(ifp, IFCAP_TXCSUM, 0);
2149 		if_sethwassistbits(ifp, XN_CSUM_FEATURES, 0);
2150 	}
2151 	if ((if_getcapabilities(ifp) & cap_enabled & IFCAP_RXCSUM) != 0)
2152 		if_setcapenablebit(ifp, IFCAP_RXCSUM, 0);
2153 
2154 	return (err);
2155 }
2156 
2157 static int
2158 xn_txq_mq_start_locked(struct netfront_txq *txq, struct mbuf *m)
2159 {
2160 	struct netfront_info *np;
2161 	if_t ifp;
2162 	struct buf_ring *br;
2163 	int error, notify;
2164 
2165 	np = txq->info;
2166 	br = txq->br;
2167 	ifp = np->xn_ifp;
2168 	error = 0;
2169 
2170 	XN_TX_LOCK_ASSERT(txq);
2171 
2172 	if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0 ||
2173 	    !netfront_carrier_ok(np)) {
2174 		if (m != NULL)
2175 			error = drbr_enqueue(ifp, br, m);
2176 		return (error);
2177 	}
2178 
2179 	if (m != NULL) {
2180 		error = drbr_enqueue(ifp, br, m);
2181 		if (error != 0)
2182 			return (error);
2183 	}
2184 
2185 	while ((m = drbr_peek(ifp, br)) != NULL) {
2186 		if (!xn_tx_slot_available(txq)) {
2187 			drbr_putback(ifp, br, m);
2188 			break;
2189 		}
2190 
2191 		error = xn_assemble_tx_request(txq, m);
2192 		/* xn_assemble_tx_request always consumes the mbuf*/
2193 		if (error != 0) {
2194 			drbr_advance(ifp, br);
2195 			break;
2196 		}
2197 
2198 		RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&txq->ring, notify);
2199 		if (notify)
2200 			xen_intr_signal(txq->xen_intr_handle);
2201 
2202 		drbr_advance(ifp, br);
2203 	}
2204 
2205 	if (RING_FULL(&txq->ring))
2206 		txq->full = true;
2207 
2208 	return (0);
2209 }
2210 
2211 static int
2212 xn_txq_mq_start(if_t ifp, struct mbuf *m)
2213 {
2214 	struct netfront_info *np;
2215 	struct netfront_txq *txq;
2216 	int i, npairs, error;
2217 
2218 	np = if_getsoftc(ifp);
2219 	npairs = np->num_queues;
2220 
2221 	if (!netfront_carrier_ok(np))
2222 		return (ENOBUFS);
2223 
2224 	KASSERT(npairs != 0, ("called with 0 available queues"));
2225 
2226 	/* check if flowid is set */
2227 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2228 		i = m->m_pkthdr.flowid % npairs;
2229 	else
2230 		i = curcpu % npairs;
2231 
2232 	txq = &np->txq[i];
2233 
2234 	if (XN_TX_TRYLOCK(txq) != 0) {
2235 		error = xn_txq_mq_start_locked(txq, m);
2236 		XN_TX_UNLOCK(txq);
2237 	} else {
2238 		error = drbr_enqueue(ifp, txq->br, m);
2239 		taskqueue_enqueue(txq->tq, &txq->defrtask);
2240 	}
2241 
2242 	return (error);
2243 }
2244 
2245 static void
2246 xn_qflush(if_t ifp)
2247 {
2248 	struct netfront_info *np;
2249 	struct netfront_txq *txq;
2250 	struct mbuf *m;
2251 	int i;
2252 
2253 	np = if_getsoftc(ifp);
2254 
2255 	for (i = 0; i < np->num_queues; i++) {
2256 		txq = &np->txq[i];
2257 
2258 		XN_TX_LOCK(txq);
2259 		while ((m = buf_ring_dequeue_sc(txq->br)) != NULL)
2260 			m_freem(m);
2261 		XN_TX_UNLOCK(txq);
2262 	}
2263 
2264 	if_qflush(ifp);
2265 }
2266 
2267 /**
2268  * Create a network device.
2269  * @param dev  Newbus device representing this virtual NIC.
2270  */
2271 int
2272 create_netdev(device_t dev)
2273 {
2274 	struct netfront_info *np;
2275 	int err;
2276 	if_t ifp;
2277 
2278 	np = device_get_softc(dev);
2279 
2280 	np->xbdev         = dev;
2281 
2282 	mtx_init(&np->sc_lock, "xnsc", "netfront softc lock", MTX_DEF);
2283 
2284 	ifmedia_init(&np->sc_media, 0, xn_ifmedia_upd, xn_ifmedia_sts);
2285 	ifmedia_add(&np->sc_media, IFM_ETHER|IFM_MANUAL, 0, NULL);
2286 	ifmedia_set(&np->sc_media, IFM_ETHER|IFM_MANUAL);
2287 
2288 	err = xen_net_read_mac(dev, np->mac);
2289 	if (err != 0)
2290 		goto error;
2291 
2292 	/* Set up ifnet structure */
2293 	ifp = np->xn_ifp = if_alloc(IFT_ETHER);
2294 	if_setsoftc(ifp, np);
2295 	if_initname(ifp, "xn",  device_get_unit(dev));
2296 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2297 	if_setioctlfn(ifp, xn_ioctl);
2298 
2299 	if_settransmitfn(ifp, xn_txq_mq_start);
2300 	if_setqflushfn(ifp, xn_qflush);
2301 
2302 	if_setinitfn(ifp, xn_ifinit);
2303 
2304 	if_sethwassist(ifp, XN_CSUM_FEATURES);
2305 	/* Enable all supported features at device creation. */
2306 	if_setcapabilities(ifp, IFCAP_HWCSUM|IFCAP_TSO4|IFCAP_LRO);
2307 	if_setcapenable(ifp, if_getcapabilities(ifp));
2308 
2309 	if_sethwtsomax(ifp, 65536 - (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN));
2310 	if_sethwtsomaxsegcount(ifp, MAX_TX_REQ_FRAGS);
2311 	if_sethwtsomaxsegsize(ifp, PAGE_SIZE);
2312 
2313 	ether_ifattach(ifp, np->mac);
2314 	netfront_carrier_off(np);
2315 
2316 	err = bus_dma_tag_create(
2317 	    bus_get_dma_tag(dev),		/* parent */
2318 	    1, PAGE_SIZE,			/* algnmnt, boundary */
2319 	    BUS_SPACE_MAXADDR,			/* lowaddr */
2320 	    BUS_SPACE_MAXADDR,			/* highaddr */
2321 	    NULL, NULL,				/* filter, filterarg */
2322 	    PAGE_SIZE * MAX_TX_REQ_FRAGS,	/* max request size */
2323 	    MAX_TX_REQ_FRAGS,			/* max segments */
2324 	    PAGE_SIZE,				/* maxsegsize */
2325 	    BUS_DMA_ALLOCNOW,			/* flags */
2326 	    NULL, NULL,				/* lockfunc, lockarg */
2327 	    &np->dma_tag);
2328 
2329 	return (err);
2330 
2331 error:
2332 	KASSERT(err != 0, ("Error path with no error code specified"));
2333 	return (err);
2334 }
2335 
2336 static int
2337 netfront_detach(device_t dev)
2338 {
2339 	struct netfront_info *info = device_get_softc(dev);
2340 
2341 	DPRINTK("%s\n", xenbus_get_node(dev));
2342 
2343 	netif_free(info);
2344 
2345 	return 0;
2346 }
2347 
2348 static void
2349 netif_free(struct netfront_info *np)
2350 {
2351 
2352 	XN_LOCK(np);
2353 	xn_stop(np);
2354 	XN_UNLOCK(np);
2355 	netif_disconnect_backend(np);
2356 	ether_ifdetach(np->xn_ifp);
2357 	free(np->rxq, M_DEVBUF);
2358 	free(np->txq, M_DEVBUF);
2359 	if_free(np->xn_ifp);
2360 	np->xn_ifp = NULL;
2361 	ifmedia_removeall(&np->sc_media);
2362 	bus_dma_tag_destroy(np->dma_tag);
2363 }
2364 
2365 static void
2366 netif_disconnect_backend(struct netfront_info *np)
2367 {
2368 	u_int i;
2369 
2370 	for (i = 0; i < np->num_queues; i++) {
2371 		XN_RX_LOCK(&np->rxq[i]);
2372 		XN_TX_LOCK(&np->txq[i]);
2373 	}
2374 	netfront_carrier_off(np);
2375 	for (i = 0; i < np->num_queues; i++) {
2376 		XN_RX_UNLOCK(&np->rxq[i]);
2377 		XN_TX_UNLOCK(&np->txq[i]);
2378 	}
2379 
2380 	for (i = 0; i < np->num_queues; i++) {
2381 		disconnect_rxq(&np->rxq[i]);
2382 		disconnect_txq(&np->txq[i]);
2383 	}
2384 }
2385 
2386 static int
2387 xn_ifmedia_upd(if_t ifp)
2388 {
2389 
2390 	return (0);
2391 }
2392 
2393 static void
2394 xn_ifmedia_sts(if_t ifp, struct ifmediareq *ifmr)
2395 {
2396 
2397 	ifmr->ifm_status = IFM_AVALID|IFM_ACTIVE;
2398 	ifmr->ifm_active = IFM_ETHER|IFM_MANUAL;
2399 }
2400 
2401 /* ** Driver registration ** */
2402 static device_method_t netfront_methods[] = {
2403 	/* Device interface */
2404 	DEVMETHOD(device_probe,         netfront_probe),
2405 	DEVMETHOD(device_attach,        netfront_attach),
2406 	DEVMETHOD(device_detach,        netfront_detach),
2407 	DEVMETHOD(device_shutdown,      bus_generic_shutdown),
2408 	DEVMETHOD(device_suspend,       netfront_suspend),
2409 	DEVMETHOD(device_resume,        netfront_resume),
2410 
2411 	/* Xenbus interface */
2412 	DEVMETHOD(xenbus_otherend_changed, netfront_backend_changed),
2413 
2414 	DEVMETHOD_END
2415 };
2416 
2417 static driver_t netfront_driver = {
2418 	"xn",
2419 	netfront_methods,
2420 	sizeof(struct netfront_info),
2421 };
2422 
2423 DRIVER_MODULE(xe, xenbusb_front, netfront_driver, NULL, NULL);
2424