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