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