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