xref: /freebsd/sys/net/if_epair.c (revision 7442b632)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2008 The FreeBSD Foundation
5  * Copyright (c) 2009-2021 Bjoern A. Zeeb <bz@FreeBSD.org>
6  *
7  * This software was developed by CK Software GmbH under sponsorship
8  * from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in the
17  * documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * A pair of virtual back-to-back connected ethernet like interfaces
34  * (``two interfaces with a virtual cross-over cable'').
35  *
36  * This is mostly intended to be used to provide connectivity between
37  * different virtual network stack instances.
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #include "opt_rss.h"
44 
45 #include <sys/param.h>
46 #include <sys/hash.h>
47 #include <sys/jail.h>
48 #include <sys/kernel.h>
49 #include <sys/libkern.h>
50 #include <sys/malloc.h>
51 #include <sys/mbuf.h>
52 #include <sys/module.h>
53 #include <sys/proc.h>
54 #include <sys/queue.h>
55 #include <sys/sched.h>
56 #include <sys/smp.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/taskqueue.h>
60 #include <sys/types.h>
61 #include <sys/buf_ring.h>
62 #include <sys/bus.h>
63 #include <sys/interrupt.h>
64 
65 #include <net/bpf.h>
66 #include <net/ethernet.h>
67 #include <net/if.h>
68 #include <net/if_var.h>
69 #include <net/if_clone.h>
70 #include <net/if_media.h>
71 #include <net/if_var.h>
72 #include <net/if_types.h>
73 #include <net/netisr.h>
74 #ifdef RSS
75 #include <net/rss_config.h>
76 #include <netinet/in_rss.h>
77 #include <netinet6/in6_rss.h>
78 #endif
79 #include <net/vnet.h>
80 
81 static int epair_clone_match(struct if_clone *, const char *);
82 static int epair_clone_create(struct if_clone *, char *, size_t, caddr_t);
83 static int epair_clone_destroy(struct if_clone *, struct ifnet *);
84 
85 static const char epairname[] = "epair";
86 #define	RXRSIZE	4096	/* Probably overkill by 4-8x. */
87 
88 static MALLOC_DEFINE(M_EPAIR, epairname,
89     "Pair of virtual cross-over connected Ethernet-like interfaces");
90 
91 VNET_DEFINE_STATIC(struct if_clone *, epair_cloner);
92 #define	V_epair_cloner	VNET(epair_cloner)
93 
94 static unsigned int next_index = 0;
95 #define	EPAIR_LOCK_INIT()		mtx_init(&epair_n_index_mtx, "epairidx", \
96 					    NULL, MTX_DEF)
97 #define	EPAIR_LOCK_DESTROY()		mtx_destroy(&epair_n_index_mtx)
98 #define	EPAIR_LOCK()			mtx_lock(&epair_n_index_mtx)
99 #define	EPAIR_UNLOCK()			mtx_unlock(&epair_n_index_mtx)
100 
101 struct epair_softc;
102 struct epair_queue {
103 	int			 id;
104 	struct buf_ring		*rxring[2];
105 	volatile int		 ridx;		/* 0 || 1 */
106 	struct task		 tx_task;
107 	struct epair_softc	*sc;
108 };
109 
110 static struct mtx epair_n_index_mtx;
111 struct epair_softc {
112 	struct ifnet		*ifp;		/* This ifp. */
113 	struct ifnet		*oifp;		/* other ifp of pair. */
114 	int			 num_queues;
115 	struct epair_queue	*queues;
116 	struct ifmedia		 media;		/* Media config (fake). */
117 	STAILQ_ENTRY(epair_softc) entry;
118 };
119 
120 struct epair_tasks_t {
121 	int			 tasks;
122 	struct taskqueue	 *tq[MAXCPU];
123 };
124 
125 static struct epair_tasks_t epair_tasks;
126 
127 static void
128 epair_clear_mbuf(struct mbuf *m)
129 {
130 	/* Remove any CSUM_SND_TAG as ether_input will barf. */
131 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
132 		m_snd_tag_rele(m->m_pkthdr.snd_tag);
133 		m->m_pkthdr.snd_tag = NULL;
134 		m->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
135 	}
136 
137 	m_tag_delete_nonpersistent(m);
138 }
139 
140 static void
141 epair_if_input(struct epair_softc *sc, struct epair_queue *q, int ridx)
142 {
143 	struct ifnet *ifp;
144 	struct mbuf *m;
145 
146 	ifp = sc->ifp;
147 	CURVNET_SET(ifp->if_vnet);
148 	while (! buf_ring_empty(q->rxring[ridx])) {
149 		m = buf_ring_dequeue_mc(q->rxring[ridx]);
150 		if (m == NULL)
151 			continue;
152 
153 		MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
154 		(*ifp->if_input)(ifp, m);
155 
156 	}
157 	CURVNET_RESTORE();
158 }
159 
160 static void
161 epair_tx_start_deferred(void *arg, int pending)
162 {
163 	struct epair_queue *q = (struct epair_queue *)arg;
164 	struct epair_softc *sc = q->sc;
165 	int ridx, nidx;
166 
167 	if_ref(sc->ifp);
168 	ridx = atomic_load_int(&q->ridx);
169 	do {
170 		nidx = (ridx == 0) ? 1 : 0;
171 	} while (!atomic_fcmpset_int(&q->ridx, &ridx, nidx));
172 	epair_if_input(sc, q, ridx);
173 
174 	if (! buf_ring_empty(q->rxring[nidx]))
175 		taskqueue_enqueue(epair_tasks.tq[q->id], &q->tx_task);
176 
177 	if_rele(sc->ifp);
178 }
179 
180 static int
181 epair_menq(struct mbuf *m, struct epair_softc *osc)
182 {
183 	struct ifnet *ifp, *oifp;
184 	int len, ret;
185 	int ridx;
186 	short mflags;
187 	struct epair_queue *q = NULL;
188 	uint32_t bucket;
189 	bool was_empty;
190 #ifdef RSS
191 	struct ether_header *eh;
192 #endif
193 
194 	/*
195 	 * I know this looks weird. We pass the "other sc" as we need that one
196 	 * and can get both ifps from it as well.
197 	 */
198 	oifp = osc->ifp;
199 	ifp = osc->oifp;
200 
201 	M_ASSERTPKTHDR(m);
202 	epair_clear_mbuf(m);
203 	if_setrcvif(m, oifp);
204 	M_SETFIB(m, oifp->if_fib);
205 
206 	/* Save values as once the mbuf is queued, it's not ours anymore. */
207 	len = m->m_pkthdr.len;
208 	mflags = m->m_flags;
209 
210 	MPASS(m->m_nextpkt == NULL);
211 	MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
212 
213 #ifdef RSS
214 	ret = rss_m2bucket(m, &bucket);
215 	if (ret) {
216 		/* Actually hash the packet. */
217 		eh = mtod(m, struct ether_header *);
218 
219 		switch (ntohs(eh->ether_type)) {
220 		case ETHERTYPE_IP:
221 			rss_soft_m2cpuid_v4(m, 0, &bucket);
222 			break;
223 		case ETHERTYPE_IPV6:
224 			rss_soft_m2cpuid_v6(m, 0, &bucket);
225 			break;
226 		default:
227 			bucket = 0;
228 			break;
229 		}
230 	}
231 	bucket %= osc->num_queues;
232 #else
233 	bucket = 0;
234 #endif
235 	q = &osc->queues[bucket];
236 
237 	ridx = atomic_load_int(&q->ridx);
238 	was_empty = buf_ring_empty(q->rxring[ridx]);
239 	ret = buf_ring_enqueue(q->rxring[ridx], m);
240 	if (ret != 0) {
241 		/* Ring is full. */
242 		if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1);
243 		m_freem(m);
244 		goto done;
245 	}
246 
247 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
248 	/*
249 	 * IFQ_HANDOFF_ADJ/ip_handoff() update statistics,
250 	 * but as we bypass all this we have to duplicate
251 	 * the logic another time.
252 	 */
253 	if_inc_counter(ifp, IFCOUNTER_OBYTES, len);
254 	if (mflags & (M_BCAST|M_MCAST))
255 		if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
256 	/* Someone else received the packet. */
257 	if_inc_counter(oifp, IFCOUNTER_IPACKETS, 1);
258 
259 done:
260 	if (was_empty)
261 		taskqueue_enqueue(epair_tasks.tq[bucket], &q->tx_task);
262 
263 	return (0);
264 }
265 
266 static void
267 epair_start(struct ifnet *ifp)
268 {
269 	struct mbuf *m;
270 	struct epair_softc *sc;
271 	struct ifnet *oifp;
272 
273 	/*
274 	 * We get packets here from ether_output via if_handoff()
275 	 * and need to put them into the input queue of the oifp
276 	 * and will put the packet into the receive-queue (rxq) of the
277 	 * other interface (oifp) of our pair.
278 	 */
279 	sc = ifp->if_softc;
280 	oifp = sc->oifp;
281 	sc = oifp->if_softc;
282 	for (;;) {
283 		IFQ_DEQUEUE(&ifp->if_snd, m);
284 		if (m == NULL)
285 			break;
286 		M_ASSERTPKTHDR(m);
287 		BPF_MTAP(ifp, m);
288 
289 		/* In case either interface is not usable drop the packet. */
290 		if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
291 		    (ifp->if_flags & IFF_UP) == 0 ||
292 		    (oifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
293 		    (oifp->if_flags & IFF_UP) == 0) {
294 			m_freem(m);
295 			continue;
296 		}
297 
298 		(void) epair_menq(m, sc);
299 	}
300 }
301 
302 static int
303 epair_transmit(struct ifnet *ifp, struct mbuf *m)
304 {
305 	struct epair_softc *sc;
306 	struct ifnet *oifp;
307 	int error;
308 #ifdef ALTQ
309 	int len;
310 	short mflags;
311 #endif
312 
313 	if (m == NULL)
314 		return (0);
315 	M_ASSERTPKTHDR(m);
316 
317 	/*
318 	 * We are not going to use the interface en/dequeue mechanism
319 	 * on the TX side. We are called from ether_output_frame()
320 	 * and will put the packet into the receive-queue (rxq) of the
321 	 * other interface (oifp) of our pair.
322 	 */
323 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
324 		m_freem(m);
325 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
326 		return (ENXIO);
327 	}
328 	if ((ifp->if_flags & IFF_UP) == 0) {
329 		m_freem(m);
330 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
331 		return (ENETDOWN);
332 	}
333 
334 	BPF_MTAP(ifp, m);
335 
336 	/*
337 	 * In case the outgoing interface is not usable,
338 	 * drop the packet.
339 	 */
340 	sc = ifp->if_softc;
341 	oifp = sc->oifp;
342 	if ((oifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
343 	    (oifp->if_flags & IFF_UP) == 0) {
344 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
345 		m_freem(m);
346 		return (0);
347 	}
348 
349 #ifdef ALTQ
350 	len = m->m_pkthdr.len;
351 	mflags = m->m_flags;
352 
353 	/* Support ALTQ via the classic if_start() path. */
354 	IF_LOCK(&ifp->if_snd);
355 	if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
356 		ALTQ_ENQUEUE(&ifp->if_snd, m, NULL, error);
357 		if (error)
358 			if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1);
359 		IF_UNLOCK(&ifp->if_snd);
360 		if (!error) {
361 			if_inc_counter(ifp, IFCOUNTER_OBYTES, len);
362 			if (mflags & (M_BCAST|M_MCAST))
363 				if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
364 			epair_start(ifp);
365 		}
366 		return (error);
367 	}
368 	IF_UNLOCK(&ifp->if_snd);
369 #endif
370 
371 	error = epair_menq(m, oifp->if_softc);
372 	return (error);
373 }
374 
375 static int
376 epair_media_change(struct ifnet *ifp __unused)
377 {
378 
379 	/* Do nothing. */
380 	return (0);
381 }
382 
383 static void
384 epair_media_status(struct ifnet *ifp __unused, struct ifmediareq *imr)
385 {
386 
387 	imr->ifm_status = IFM_AVALID | IFM_ACTIVE;
388 	imr->ifm_active = IFM_ETHER | IFM_10G_T | IFM_FDX;
389 }
390 
391 static int
392 epair_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
393 {
394 	struct epair_softc *sc;
395 	struct ifreq *ifr;
396 	int error;
397 
398 	ifr = (struct ifreq *)data;
399 	switch (cmd) {
400 	case SIOCSIFFLAGS:
401 	case SIOCADDMULTI:
402 	case SIOCDELMULTI:
403 		error = 0;
404 		break;
405 
406 	case SIOCSIFMEDIA:
407 	case SIOCGIFMEDIA:
408 		sc = ifp->if_softc;
409 		error = ifmedia_ioctl(ifp, ifr, &sc->media, cmd);
410 		break;
411 
412 	case SIOCSIFMTU:
413 		/* We basically allow all kinds of MTUs. */
414 		ifp->if_mtu = ifr->ifr_mtu;
415 		error = 0;
416 		break;
417 
418 	default:
419 		/* Let the common ethernet handler process this. */
420 		error = ether_ioctl(ifp, cmd, data);
421 		break;
422 	}
423 
424 	return (error);
425 }
426 
427 static void
428 epair_init(void *dummy __unused)
429 {
430 }
431 
432 /*
433  * Interface cloning functions.
434  * We use our private ones so that we can create/destroy our secondary
435  * device along with the primary one.
436  */
437 static int
438 epair_clone_match(struct if_clone *ifc, const char *name)
439 {
440 	const char *cp;
441 
442 	/*
443 	 * Our base name is epair.
444 	 * Our interfaces will be named epair<n>[ab].
445 	 * So accept anything of the following list:
446 	 * - epair
447 	 * - epair<n>
448 	 * but not the epair<n>[ab] versions.
449 	 */
450 	if (strncmp(epairname, name, sizeof(epairname)-1) != 0)
451 		return (0);
452 
453 	for (cp = name + sizeof(epairname) - 1; *cp != '\0'; cp++) {
454 		if (*cp < '0' || *cp > '9')
455 			return (0);
456 	}
457 
458 	return (1);
459 }
460 
461 static void
462 epair_clone_add(struct if_clone *ifc, struct epair_softc *scb)
463 {
464 	struct ifnet *ifp;
465 	uint8_t eaddr[ETHER_ADDR_LEN];	/* 00:00:00:00:00:00 */
466 
467 	ifp = scb->ifp;
468 	/* Copy epairNa etheraddr and change the last byte. */
469 	memcpy(eaddr, scb->oifp->if_hw_addr, ETHER_ADDR_LEN);
470 	eaddr[5] = 0x0b;
471 	ether_ifattach(ifp, eaddr);
472 
473 	if_clone_addif(ifc, ifp);
474 }
475 
476 static int
477 epair_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
478 {
479 	struct epair_softc *sca, *scb;
480 	struct ifnet *ifp;
481 	char *dp;
482 	int error, unit, wildcard;
483 	uint64_t hostid;
484 	uint32_t key[3];
485 	uint32_t hash;
486 	uint8_t eaddr[ETHER_ADDR_LEN];	/* 00:00:00:00:00:00 */
487 
488 	/* Try to see if a special unit was requested. */
489 	error = ifc_name2unit(name, &unit);
490 	if (error != 0)
491 		return (error);
492 	wildcard = (unit < 0);
493 
494 	error = ifc_alloc_unit(ifc, &unit);
495 	if (error != 0)
496 		return (error);
497 
498 	/*
499 	 * If no unit had been given, we need to adjust the ifName.
500 	 * Also make sure there is space for our extra [ab] suffix.
501 	 */
502 	for (dp = name; *dp != '\0'; dp++);
503 	if (wildcard) {
504 		error = snprintf(dp, len - (dp - name), "%d", unit);
505 		if (error > len - (dp - name) - 1) {
506 			/* ifName too long. */
507 			ifc_free_unit(ifc, unit);
508 			return (ENOSPC);
509 		}
510 		dp += error;
511 	}
512 	if (len - (dp - name) - 1 < 1) {
513 		/* No space left for our [ab] suffix. */
514 		ifc_free_unit(ifc, unit);
515 		return (ENOSPC);
516 	}
517 	*dp = 'b';
518 	/* Must not change dp so we can replace 'a' by 'b' later. */
519 	*(dp+1) = '\0';
520 
521 	/* Check if 'a' and 'b' interfaces already exist. */
522 	if (ifunit(name) != NULL)
523 		return (EEXIST);
524 	*dp = 'a';
525 	if (ifunit(name) != NULL)
526 		return (EEXIST);
527 
528 	/* Allocate memory for both [ab] interfaces */
529 	sca = malloc(sizeof(struct epair_softc), M_EPAIR, M_WAITOK | M_ZERO);
530 	sca->ifp = if_alloc(IFT_ETHER);
531 	sca->num_queues = epair_tasks.tasks;
532 	if (sca->ifp == NULL) {
533 		free(sca, M_EPAIR);
534 		ifc_free_unit(ifc, unit);
535 		return (ENOSPC);
536 	}
537 	sca->queues = mallocarray(sca->num_queues, sizeof(struct epair_queue),
538 	    M_EPAIR, M_WAITOK);
539 	for (int i = 0; i < sca->num_queues; i++) {
540 		struct epair_queue *q = &sca->queues[i];
541 		q->id = i;
542 		q->rxring[0] = buf_ring_alloc(RXRSIZE, M_EPAIR, M_WAITOK, NULL);
543 		q->rxring[1] = buf_ring_alloc(RXRSIZE, M_EPAIR, M_WAITOK, NULL);
544 		q->ridx = 0;
545 		q->sc = sca;
546 		NET_TASK_INIT(&q->tx_task, 0, epair_tx_start_deferred, q);
547 	}
548 
549 	scb = malloc(sizeof(struct epair_softc), M_EPAIR, M_WAITOK | M_ZERO);
550 	scb->ifp = if_alloc(IFT_ETHER);
551 	scb->num_queues = epair_tasks.tasks;
552 	if (scb->ifp == NULL) {
553 		free(scb, M_EPAIR);
554 		if_free(sca->ifp);
555 		free(sca, M_EPAIR);
556 		ifc_free_unit(ifc, unit);
557 		return (ENOSPC);
558 	}
559 	scb->queues = mallocarray(scb->num_queues, sizeof(struct epair_queue),
560 	    M_EPAIR, M_WAITOK);
561 	for (int i = 0; i < scb->num_queues; i++) {
562 		struct epair_queue *q = &scb->queues[i];
563 		q->id = i;
564 		q->rxring[0] = buf_ring_alloc(RXRSIZE, M_EPAIR, M_WAITOK, NULL);
565 		q->rxring[1] = buf_ring_alloc(RXRSIZE, M_EPAIR, M_WAITOK, NULL);
566 		q->ridx = 0;
567 		q->sc = scb;
568 		NET_TASK_INIT(&q->tx_task, 0, epair_tx_start_deferred, q);
569 	}
570 
571 	/*
572 	 * Cross-reference the interfaces so we will be able to free both.
573 	 */
574 	sca->oifp = scb->ifp;
575 	scb->oifp = sca->ifp;
576 
577 	EPAIR_LOCK();
578 #ifdef SMP
579 	/* Get an approximate distribution. */
580 	hash = next_index % mp_ncpus;
581 #else
582 	hash = 0;
583 #endif
584 	EPAIR_UNLOCK();
585 
586 	/* Initialise pseudo media types. */
587 	ifmedia_init(&sca->media, 0, epair_media_change, epair_media_status);
588 	ifmedia_add(&sca->media, IFM_ETHER | IFM_10G_T, 0, NULL);
589 	ifmedia_set(&sca->media, IFM_ETHER | IFM_10G_T);
590 	ifmedia_init(&scb->media, 0, epair_media_change, epair_media_status);
591 	ifmedia_add(&scb->media, IFM_ETHER | IFM_10G_T, 0, NULL);
592 	ifmedia_set(&scb->media, IFM_ETHER | IFM_10G_T);
593 
594 	/* Finish initialization of interface <n>a. */
595 	ifp = sca->ifp;
596 	ifp->if_softc = sca;
597 	strlcpy(ifp->if_xname, name, IFNAMSIZ);
598 	ifp->if_dname = epairname;
599 	ifp->if_dunit = unit;
600 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
601 	ifp->if_flags |= IFF_KNOWSEPOCH;
602 	ifp->if_capabilities = IFCAP_VLAN_MTU;
603 	ifp->if_capenable = IFCAP_VLAN_MTU;
604 	ifp->if_start = epair_start;
605 	ifp->if_ioctl = epair_ioctl;
606 	ifp->if_init  = epair_init;
607 	if_setsendqlen(ifp, ifqmaxlen);
608 	if_setsendqready(ifp);
609 
610 	/*
611 	 * Calculate the etheraddr hashing the hostid and the
612 	 * interface index. The result would be hopefully unique.
613 	 * Note that the "a" component of an epair instance may get moved
614 	 * to a different VNET after creation. In that case its index
615 	 * will be freed and the index can get reused by new epair instance.
616 	 * Make sure we do not create same etheraddr again.
617 	 */
618 	getcredhostid(curthread->td_ucred, (unsigned long *)&hostid);
619 	if (hostid == 0)
620 		arc4rand(&hostid, sizeof(hostid), 0);
621 
622 	EPAIR_LOCK();
623 	if (ifp->if_index > next_index)
624 		next_index = ifp->if_index;
625 	else
626 		next_index++;
627 
628 	key[0] = (uint32_t)next_index;
629 	EPAIR_UNLOCK();
630 	key[1] = (uint32_t)(hostid & 0xffffffff);
631 	key[2] = (uint32_t)((hostid >> 32) & 0xfffffffff);
632 	hash = jenkins_hash32(key, 3, 0);
633 
634 	eaddr[0] = 0x02;
635 	memcpy(&eaddr[1], &hash, 4);
636 	eaddr[5] = 0x0a;
637 	ether_ifattach(ifp, eaddr);
638 	ifp->if_baudrate = IF_Gbps(10);	/* arbitrary maximum */
639 	ifp->if_transmit = epair_transmit;
640 
641 	/* Swap the name and finish initialization of interface <n>b. */
642 	*dp = 'b';
643 
644 	ifp = scb->ifp;
645 	ifp->if_softc = scb;
646 	strlcpy(ifp->if_xname, name, IFNAMSIZ);
647 	ifp->if_dname = epairname;
648 	ifp->if_dunit = unit;
649 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
650 	ifp->if_flags |= IFF_KNOWSEPOCH;
651 	ifp->if_capabilities = IFCAP_VLAN_MTU;
652 	ifp->if_capenable = IFCAP_VLAN_MTU;
653 	ifp->if_start = epair_start;
654 	ifp->if_ioctl = epair_ioctl;
655 	ifp->if_init  = epair_init;
656 	if_setsendqlen(ifp, ifqmaxlen);
657 	if_setsendqready(ifp);
658 	/* We need to play some tricks here for the second interface. */
659 	strlcpy(name, epairname, len);
660 
661 	/* Correctly set the name for the cloner list. */
662 	strlcpy(name, scb->ifp->if_xname, len);
663 	epair_clone_add(ifc, scb);
664 
665 	ifp->if_baudrate = IF_Gbps(10);	/* arbitrary maximum */
666 	ifp->if_transmit = epair_transmit;
667 
668 	/*
669 	 * Restore name to <n>a as the ifp for this will go into the
670 	 * cloner list for the initial call.
671 	 */
672 	strlcpy(name, sca->ifp->if_xname, len);
673 
674 	/* Tell the world, that we are ready to rock. */
675 	sca->ifp->if_drv_flags |= IFF_DRV_RUNNING;
676 	if_link_state_change(sca->ifp, LINK_STATE_UP);
677 	scb->ifp->if_drv_flags |= IFF_DRV_RUNNING;
678 	if_link_state_change(scb->ifp, LINK_STATE_UP);
679 
680 	return (0);
681 }
682 
683 static void
684 epair_drain_rings(struct epair_softc *sc)
685 {
686 	int ridx;
687 	struct mbuf *m;
688 
689 	for (ridx = 0; ridx < 2; ridx++) {
690 		for (int i = 0; i < sc->num_queues; i++) {
691 			struct epair_queue *q = &sc->queues[i];
692 			do {
693 				m = buf_ring_dequeue_sc(q->rxring[ridx]);
694 				if (m == NULL)
695 					break;
696 				m_freem(m);
697 			} while (1);
698 		}
699 	}
700 }
701 
702 static int
703 epair_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
704 {
705 	struct ifnet *oifp;
706 	struct epair_softc *sca, *scb;
707 	int unit, error;
708 
709 	/*
710 	 * In case we called into if_clone_destroyif() ourselves
711 	 * again to remove the second interface, the softc will be
712 	 * NULL. In that case so not do anything but return success.
713 	 */
714 	if (ifp->if_softc == NULL)
715 		return (0);
716 
717 	unit = ifp->if_dunit;
718 	sca = ifp->if_softc;
719 	oifp = sca->oifp;
720 	scb = oifp->if_softc;
721 
722 	/* Frist get the interfaces down and detached. */
723 	if_link_state_change(ifp, LINK_STATE_DOWN);
724 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
725 	if_link_state_change(oifp, LINK_STATE_DOWN);
726 	oifp->if_drv_flags &= ~IFF_DRV_RUNNING;
727 
728 	ether_ifdetach(ifp);
729 	ether_ifdetach(oifp);
730 
731 	/* Third free any queued packets and all the resources. */
732 	CURVNET_SET_QUIET(oifp->if_vnet);
733 	epair_drain_rings(scb);
734 	oifp->if_softc = NULL;
735 	error = if_clone_destroyif(ifc, oifp);
736 	if (error)
737 		panic("%s: if_clone_destroyif() for our 2nd iface failed: %d",
738 		    __func__, error);
739 	if_free(oifp);
740 	ifmedia_removeall(&scb->media);
741 	for (int i = 0; i < scb->num_queues; i++) {
742 		struct epair_queue *q = &scb->queues[i];
743 		buf_ring_free(q->rxring[0], M_EPAIR);
744 		buf_ring_free(q->rxring[1], M_EPAIR);
745 	}
746 	free(scb->queues, M_EPAIR);
747 	free(scb, M_EPAIR);
748 	CURVNET_RESTORE();
749 
750 	epair_drain_rings(sca);
751 	if_free(ifp);
752 	ifmedia_removeall(&sca->media);
753 	for (int i = 0; i < sca->num_queues; i++) {
754 		struct epair_queue *q = &sca->queues[i];
755 		buf_ring_free(q->rxring[0], M_EPAIR);
756 		buf_ring_free(q->rxring[1], M_EPAIR);
757 	}
758 	free(sca->queues, M_EPAIR);
759 	free(sca, M_EPAIR);
760 
761 	/* Last free the cloner unit. */
762 	ifc_free_unit(ifc, unit);
763 
764 	return (0);
765 }
766 
767 static void
768 vnet_epair_init(const void *unused __unused)
769 {
770 
771 	V_epair_cloner = if_clone_advanced(epairname, 0,
772 	    epair_clone_match, epair_clone_create, epair_clone_destroy);
773 }
774 VNET_SYSINIT(vnet_epair_init, SI_SUB_PSEUDO, SI_ORDER_ANY,
775     vnet_epair_init, NULL);
776 
777 static void
778 vnet_epair_uninit(const void *unused __unused)
779 {
780 
781 	if_clone_detach(V_epair_cloner);
782 }
783 VNET_SYSUNINIT(vnet_epair_uninit, SI_SUB_INIT_IF, SI_ORDER_ANY,
784     vnet_epair_uninit, NULL);
785 
786 static int
787 epair_mod_init(void)
788 {
789 	char name[32];
790 	epair_tasks.tasks = 0;
791 
792 #ifdef RSS
793 	struct pcpu *pcpu;
794 	int cpu;
795 
796 	CPU_FOREACH(cpu) {
797 		cpuset_t cpu_mask;
798 
799 		/* Pin to this CPU so we get appropriate NUMA allocations. */
800 		pcpu = pcpu_find(cpu);
801 		thread_lock(curthread);
802 		sched_bind(curthread, cpu);
803 		thread_unlock(curthread);
804 
805 		snprintf(name, sizeof(name), "epair_task_%d", cpu);
806 
807 		epair_tasks.tq[cpu] = taskqueue_create(name, M_WAITOK,
808 		    taskqueue_thread_enqueue,
809 		    &epair_tasks.tq[cpu]);
810 		CPU_SETOF(cpu, &cpu_mask);
811 		taskqueue_start_threads_cpuset(&epair_tasks.tq[cpu], 1, PI_NET,
812 		    &cpu_mask, "%s", name);
813 
814 		epair_tasks.tasks++;
815 	}
816 #else
817 	snprintf(name, sizeof(name), "epair_task");
818 
819 	epair_tasks.tq[0] = taskqueue_create(name, M_WAITOK,
820 	    taskqueue_thread_enqueue,
821 	    &epair_tasks.tq[0]);
822 	taskqueue_start_threads(&epair_tasks.tq[0], 1, PI_NET, "%s", name);
823 
824 	epair_tasks.tasks = 1;
825 #endif
826 
827 	return (0);
828 }
829 
830 static void
831 epair_mod_cleanup(void)
832 {
833 
834 	for (int i = 0; i < epair_tasks.tasks; i++) {
835 		taskqueue_drain_all(epair_tasks.tq[i]);
836 		taskqueue_free(epair_tasks.tq[i]);
837 	}
838 }
839 
840 static int
841 epair_modevent(module_t mod, int type, void *data)
842 {
843 	int ret;
844 
845 	switch (type) {
846 	case MOD_LOAD:
847 		EPAIR_LOCK_INIT();
848 		ret = epair_mod_init();
849 		if (ret != 0)
850 			return (ret);
851 		if (bootverbose)
852 			printf("%s: %s initialized.\n", __func__, epairname);
853 		break;
854 	case MOD_UNLOAD:
855 		epair_mod_cleanup();
856 		EPAIR_LOCK_DESTROY();
857 		if (bootverbose)
858 			printf("%s: %s unloaded.\n", __func__, epairname);
859 		break;
860 	default:
861 		return (EOPNOTSUPP);
862 	}
863 	return (0);
864 }
865 
866 static moduledata_t epair_mod = {
867 	"if_epair",
868 	epair_modevent,
869 	0
870 };
871 
872 DECLARE_MODULE(if_epair, epair_mod, SI_SUB_PSEUDO, SI_ORDER_MIDDLE);
873 MODULE_VERSION(if_epair, 3);
874