2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2008 The FreeBSD Foundation
5 * Copyright (c) 2009-2021 Bjoern A. Zeeb <bz@FreeBSD.org>
7 * This software was developed by CK Software GmbH under sponsorship
8 * from the FreeBSD Foundation.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
33 * A pair of virtual back-to-back connected ethernet like interfaces
34 * (``two interfaces with a virtual cross-over cable'').
36 * This is mostly intended to be used to provide connectivity between
37 * different virtual network stack instances.
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
45 #include "opt_inet6.h"
47 #include <sys/param.h>
50 #include <sys/kernel.h>
51 #include <sys/libkern.h>
52 #include <sys/malloc.h>
54 #include <sys/module.h>
56 #include <sys/queue.h>
57 #include <sys/sched.h>
59 #include <sys/socket.h>
60 #include <sys/sockio.h>
61 #include <sys/taskqueue.h>
62 #include <sys/types.h>
63 #include <sys/buf_ring.h>
65 #include <sys/interrupt.h>
68 #include <net/ethernet.h>
70 #include <net/if_var.h>
71 #include <net/if_clone.h>
72 #include <net/if_media.h>
73 #include <net/if_var.h>
74 #include <net/if_types.h>
75 #include <net/netisr.h>
77 #include <net/rss_config.h>
79 #include <netinet/in_rss.h>
82 #include <netinet6/in6_rss.h>
87 static int epair_clone_match(struct if_clone *, const char *);
88 static int epair_clone_create(struct if_clone *, char *, size_t, caddr_t);
89 static int epair_clone_destroy(struct if_clone *, struct ifnet *);
91 static const char epairname[] = "epair";
92 #define RXRSIZE 4096 /* Probably overkill by 4-8x. */
94 static MALLOC_DEFINE(M_EPAIR, epairname,
95 "Pair of virtual cross-over connected Ethernet-like interfaces");
97 VNET_DEFINE_STATIC(struct if_clone *, epair_cloner);
98 #define V_epair_cloner VNET(epair_cloner)
100 static unsigned int next_index = 0;
101 #define EPAIR_LOCK_INIT() mtx_init(&epair_n_index_mtx, "epairidx", \
103 #define EPAIR_LOCK_DESTROY() mtx_destroy(&epair_n_index_mtx)
104 #define EPAIR_LOCK() mtx_lock(&epair_n_index_mtx)
105 #define EPAIR_UNLOCK() mtx_unlock(&epair_n_index_mtx)
107 #define BIT_QUEUE_TASK 0
108 #define BIT_MBUF_QUEUED 1
113 struct buf_ring *rxring[2];
114 volatile int ridx; /* 0 || 1 */
115 volatile long state; /* taskqueue coordination */
117 struct epair_softc *sc;
120 static struct mtx epair_n_index_mtx;
122 struct ifnet *ifp; /* This ifp. */
123 struct ifnet *oifp; /* other ifp of pair. */
125 struct epair_queue *queues;
126 struct ifmedia media; /* Media config (fake). */
127 STAILQ_ENTRY(epair_softc) entry;
130 struct epair_tasks_t {
132 struct taskqueue *tq[MAXCPU];
135 static struct epair_tasks_t epair_tasks;
138 epair_clear_mbuf(struct mbuf *m)
140 /* Remove any CSUM_SND_TAG as ether_input will barf. */
141 if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
142 m_snd_tag_rele(m->m_pkthdr.snd_tag);
143 m->m_pkthdr.snd_tag = NULL;
144 m->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
147 m_tag_delete_nonpersistent(m);
151 epair_if_input(struct epair_softc *sc, struct epair_queue *q, int ridx)
157 CURVNET_SET(ifp->if_vnet);
158 while (! buf_ring_empty(q->rxring[ridx])) {
159 m = buf_ring_dequeue_mc(q->rxring[ridx]);
163 MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
164 (*ifp->if_input)(ifp, m);
171 epair_tx_start_deferred(void *arg, int pending)
173 struct epair_queue *q = (struct epair_queue *)arg;
174 struct epair_softc *sc = q->sc;
178 ridx = atomic_load_int(&q->ridx);
180 nidx = (ridx == 0) ? 1 : 0;
181 } while (!atomic_fcmpset_int(&q->ridx, &ridx, nidx));
182 epair_if_input(sc, q, ridx);
184 atomic_clear_long(&q->state, (1 << BIT_QUEUE_TASK));
185 if (atomic_testandclear_long(&q->state, BIT_MBUF_QUEUED))
186 taskqueue_enqueue(epair_tasks.tq[q->id], &q->tx_task);
192 epair_menq(struct mbuf *m, struct epair_softc *osc)
194 struct ifnet *ifp, *oifp;
198 struct epair_queue *q = NULL;
201 struct ether_header *eh;
205 * I know this looks weird. We pass the "other sc" as we need that one
206 * and can get both ifps from it as well.
213 if_setrcvif(m, oifp);
214 M_SETFIB(m, oifp->if_fib);
216 /* Save values as once the mbuf is queued, it's not ours anymore. */
217 len = m->m_pkthdr.len;
220 MPASS(m->m_nextpkt == NULL);
221 MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
224 ret = rss_m2bucket(m, &bucket);
226 /* Actually hash the packet. */
227 eh = mtod(m, struct ether_header *);
229 switch (ntohs(eh->ether_type)) {
232 rss_soft_m2cpuid_v4(m, 0, &bucket);
237 rss_soft_m2cpuid_v6(m, 0, &bucket);
245 bucket %= osc->num_queues;
249 q = &osc->queues[bucket];
251 atomic_set_long(&q->state, (1 << BIT_MBUF_QUEUED));
252 ridx = atomic_load_int(&q->ridx);
253 ret = buf_ring_enqueue(q->rxring[ridx], m);
256 if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1);
261 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
263 * IFQ_HANDOFF_ADJ/ip_handoff() update statistics,
264 * but as we bypass all this we have to duplicate
265 * the logic another time.
267 if_inc_counter(ifp, IFCOUNTER_OBYTES, len);
268 if (mflags & (M_BCAST|M_MCAST))
269 if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
270 /* Someone else received the packet. */
271 if_inc_counter(oifp, IFCOUNTER_IPACKETS, 1);
273 if (!atomic_testandset_long(&q->state, BIT_QUEUE_TASK))
274 taskqueue_enqueue(epair_tasks.tq[bucket], &q->tx_task);
280 epair_start(struct ifnet *ifp)
283 struct epair_softc *sc;
287 * We get packets here from ether_output via if_handoff()
288 * and need to put them into the input queue of the oifp
289 * and will put the packet into the receive-queue (rxq) of the
290 * other interface (oifp) of our pair.
296 IFQ_DEQUEUE(&ifp->if_snd, m);
302 /* In case either interface is not usable drop the packet. */
303 if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
304 (ifp->if_flags & IFF_UP) == 0 ||
305 (oifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
306 (oifp->if_flags & IFF_UP) == 0) {
311 (void) epair_menq(m, sc);
316 epair_transmit(struct ifnet *ifp, struct mbuf *m)
318 struct epair_softc *sc;
331 * We are not going to use the interface en/dequeue mechanism
332 * on the TX side. We are called from ether_output_frame()
333 * and will put the packet into the receive-queue (rxq) of the
334 * other interface (oifp) of our pair.
336 if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
338 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
341 if ((ifp->if_flags & IFF_UP) == 0) {
343 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
350 * In case the outgoing interface is not usable,
355 if ((oifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
356 (oifp->if_flags & IFF_UP) == 0) {
357 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
363 len = m->m_pkthdr.len;
366 /* Support ALTQ via the classic if_start() path. */
367 IF_LOCK(&ifp->if_snd);
368 if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
369 ALTQ_ENQUEUE(&ifp->if_snd, m, NULL, error);
371 if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1);
372 IF_UNLOCK(&ifp->if_snd);
374 if_inc_counter(ifp, IFCOUNTER_OBYTES, len);
375 if (mflags & (M_BCAST|M_MCAST))
376 if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
381 IF_UNLOCK(&ifp->if_snd);
384 error = epair_menq(m, oifp->if_softc);
389 epair_media_change(struct ifnet *ifp __unused)
397 epair_media_status(struct ifnet *ifp __unused, struct ifmediareq *imr)
400 imr->ifm_status = IFM_AVALID | IFM_ACTIVE;
401 imr->ifm_active = IFM_ETHER | IFM_10G_T | IFM_FDX;
405 epair_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
407 struct epair_softc *sc;
411 ifr = (struct ifreq *)data;
422 error = ifmedia_ioctl(ifp, ifr, &sc->media, cmd);
426 /* We basically allow all kinds of MTUs. */
427 ifp->if_mtu = ifr->ifr_mtu;
432 /* Let the common ethernet handler process this. */
433 error = ether_ioctl(ifp, cmd, data);
441 epair_init(void *dummy __unused)
446 * Interface cloning functions.
447 * We use our private ones so that we can create/destroy our secondary
448 * device along with the primary one.
451 epair_clone_match(struct if_clone *ifc, const char *name)
456 * Our base name is epair.
457 * Our interfaces will be named epair<n>[ab].
458 * So accept anything of the following list:
461 * but not the epair<n>[ab] versions.
463 if (strncmp(epairname, name, sizeof(epairname)-1) != 0)
466 for (cp = name + sizeof(epairname) - 1; *cp != '\0'; cp++) {
467 if (*cp < '0' || *cp > '9')
475 epair_clone_add(struct if_clone *ifc, struct epair_softc *scb)
478 uint8_t eaddr[ETHER_ADDR_LEN]; /* 00:00:00:00:00:00 */
481 /* Copy epairNa etheraddr and change the last byte. */
482 memcpy(eaddr, scb->oifp->if_hw_addr, ETHER_ADDR_LEN);
484 ether_ifattach(ifp, eaddr);
486 if_clone_addif(ifc, ifp);
490 epair_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
492 struct epair_softc *sca, *scb;
495 int error, unit, wildcard;
499 uint8_t eaddr[ETHER_ADDR_LEN]; /* 00:00:00:00:00:00 */
501 /* Try to see if a special unit was requested. */
502 error = ifc_name2unit(name, &unit);
505 wildcard = (unit < 0);
507 error = ifc_alloc_unit(ifc, &unit);
512 * If no unit had been given, we need to adjust the ifName.
513 * Also make sure there is space for our extra [ab] suffix.
515 for (dp = name; *dp != '\0'; dp++);
517 error = snprintf(dp, len - (dp - name), "%d", unit);
518 if (error > len - (dp - name) - 1) {
519 /* ifName too long. */
520 ifc_free_unit(ifc, unit);
525 if (len - (dp - name) - 1 < 1) {
526 /* No space left for our [ab] suffix. */
527 ifc_free_unit(ifc, unit);
531 /* Must not change dp so we can replace 'a' by 'b' later. */
534 /* Check if 'a' and 'b' interfaces already exist. */
535 if (ifunit(name) != NULL)
538 if (ifunit(name) != NULL)
541 /* Allocate memory for both [ab] interfaces */
542 sca = malloc(sizeof(struct epair_softc), M_EPAIR, M_WAITOK | M_ZERO);
543 sca->ifp = if_alloc(IFT_ETHER);
544 sca->num_queues = epair_tasks.tasks;
545 if (sca->ifp == NULL) {
547 ifc_free_unit(ifc, unit);
550 sca->queues = mallocarray(sca->num_queues, sizeof(struct epair_queue),
552 for (int i = 0; i < sca->num_queues; i++) {
553 struct epair_queue *q = &sca->queues[i];
555 q->rxring[0] = buf_ring_alloc(RXRSIZE, M_EPAIR, M_WAITOK, NULL);
556 q->rxring[1] = buf_ring_alloc(RXRSIZE, M_EPAIR, M_WAITOK, NULL);
560 NET_TASK_INIT(&q->tx_task, 0, epair_tx_start_deferred, q);
563 scb = malloc(sizeof(struct epair_softc), M_EPAIR, M_WAITOK | M_ZERO);
564 scb->ifp = if_alloc(IFT_ETHER);
565 scb->num_queues = epair_tasks.tasks;
566 if (scb->ifp == NULL) {
570 ifc_free_unit(ifc, unit);
573 scb->queues = mallocarray(scb->num_queues, sizeof(struct epair_queue),
575 for (int i = 0; i < scb->num_queues; i++) {
576 struct epair_queue *q = &scb->queues[i];
578 q->rxring[0] = buf_ring_alloc(RXRSIZE, M_EPAIR, M_WAITOK, NULL);
579 q->rxring[1] = buf_ring_alloc(RXRSIZE, M_EPAIR, M_WAITOK, NULL);
583 NET_TASK_INIT(&q->tx_task, 0, epair_tx_start_deferred, q);
587 * Cross-reference the interfaces so we will be able to free both.
589 sca->oifp = scb->ifp;
590 scb->oifp = sca->ifp;
594 /* Get an approximate distribution. */
595 hash = next_index % mp_ncpus;
601 /* Initialise pseudo media types. */
602 ifmedia_init(&sca->media, 0, epair_media_change, epair_media_status);
603 ifmedia_add(&sca->media, IFM_ETHER | IFM_10G_T, 0, NULL);
604 ifmedia_set(&sca->media, IFM_ETHER | IFM_10G_T);
605 ifmedia_init(&scb->media, 0, epair_media_change, epair_media_status);
606 ifmedia_add(&scb->media, IFM_ETHER | IFM_10G_T, 0, NULL);
607 ifmedia_set(&scb->media, IFM_ETHER | IFM_10G_T);
609 /* Finish initialization of interface <n>a. */
612 strlcpy(ifp->if_xname, name, IFNAMSIZ);
613 ifp->if_dname = epairname;
614 ifp->if_dunit = unit;
615 ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
616 ifp->if_flags |= IFF_KNOWSEPOCH;
617 ifp->if_capabilities = IFCAP_VLAN_MTU;
618 ifp->if_capenable = IFCAP_VLAN_MTU;
619 ifp->if_start = epair_start;
620 ifp->if_ioctl = epair_ioctl;
621 ifp->if_init = epair_init;
622 if_setsendqlen(ifp, ifqmaxlen);
623 if_setsendqready(ifp);
626 * Calculate the etheraddr hashing the hostid and the
627 * interface index. The result would be hopefully unique.
628 * Note that the "a" component of an epair instance may get moved
629 * to a different VNET after creation. In that case its index
630 * will be freed and the index can get reused by new epair instance.
631 * Make sure we do not create same etheraddr again.
633 getcredhostid(curthread->td_ucred, (unsigned long *)&hostid);
635 arc4rand(&hostid, sizeof(hostid), 0);
638 if (ifp->if_index > next_index)
639 next_index = ifp->if_index;
643 key[0] = (uint32_t)next_index;
645 key[1] = (uint32_t)(hostid & 0xffffffff);
646 key[2] = (uint32_t)((hostid >> 32) & 0xfffffffff);
647 hash = jenkins_hash32(key, 3, 0);
650 memcpy(&eaddr[1], &hash, 4);
652 ether_ifattach(ifp, eaddr);
653 ifp->if_baudrate = IF_Gbps(10); /* arbitrary maximum */
654 ifp->if_transmit = epair_transmit;
656 /* Swap the name and finish initialization of interface <n>b. */
661 strlcpy(ifp->if_xname, name, IFNAMSIZ);
662 ifp->if_dname = epairname;
663 ifp->if_dunit = unit;
664 ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
665 ifp->if_flags |= IFF_KNOWSEPOCH;
666 ifp->if_capabilities = IFCAP_VLAN_MTU;
667 ifp->if_capenable = IFCAP_VLAN_MTU;
668 ifp->if_start = epair_start;
669 ifp->if_ioctl = epair_ioctl;
670 ifp->if_init = epair_init;
671 if_setsendqlen(ifp, ifqmaxlen);
672 if_setsendqready(ifp);
673 /* We need to play some tricks here for the second interface. */
674 strlcpy(name, epairname, len);
676 /* Correctly set the name for the cloner list. */
677 strlcpy(name, scb->ifp->if_xname, len);
678 epair_clone_add(ifc, scb);
680 ifp->if_baudrate = IF_Gbps(10); /* arbitrary maximum */
681 ifp->if_transmit = epair_transmit;
684 * Restore name to <n>a as the ifp for this will go into the
685 * cloner list for the initial call.
687 strlcpy(name, sca->ifp->if_xname, len);
689 /* Tell the world, that we are ready to rock. */
690 sca->ifp->if_drv_flags |= IFF_DRV_RUNNING;
691 if_link_state_change(sca->ifp, LINK_STATE_UP);
692 scb->ifp->if_drv_flags |= IFF_DRV_RUNNING;
693 if_link_state_change(scb->ifp, LINK_STATE_UP);
699 epair_drain_rings(struct epair_softc *sc)
704 for (ridx = 0; ridx < 2; ridx++) {
705 for (int i = 0; i < sc->num_queues; i++) {
706 struct epair_queue *q = &sc->queues[i];
708 m = buf_ring_dequeue_sc(q->rxring[ridx]);
718 epair_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
721 struct epair_softc *sca, *scb;
725 * In case we called into if_clone_destroyif() ourselves
726 * again to remove the second interface, the softc will be
727 * NULL. In that case so not do anything but return success.
729 if (ifp->if_softc == NULL)
732 unit = ifp->if_dunit;
735 scb = oifp->if_softc;
737 /* Frist get the interfaces down and detached. */
738 if_link_state_change(ifp, LINK_STATE_DOWN);
739 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
740 if_link_state_change(oifp, LINK_STATE_DOWN);
741 oifp->if_drv_flags &= ~IFF_DRV_RUNNING;
744 ether_ifdetach(oifp);
746 /* Third free any queued packets and all the resources. */
747 CURVNET_SET_QUIET(oifp->if_vnet);
748 epair_drain_rings(scb);
749 oifp->if_softc = NULL;
750 error = if_clone_destroyif(ifc, oifp);
752 panic("%s: if_clone_destroyif() for our 2nd iface failed: %d",
755 ifmedia_removeall(&scb->media);
756 for (int i = 0; i < scb->num_queues; i++) {
757 struct epair_queue *q = &scb->queues[i];
758 buf_ring_free(q->rxring[0], M_EPAIR);
759 buf_ring_free(q->rxring[1], M_EPAIR);
761 free(scb->queues, M_EPAIR);
765 epair_drain_rings(sca);
767 ifmedia_removeall(&sca->media);
768 for (int i = 0; i < sca->num_queues; i++) {
769 struct epair_queue *q = &sca->queues[i];
770 buf_ring_free(q->rxring[0], M_EPAIR);
771 buf_ring_free(q->rxring[1], M_EPAIR);
773 free(sca->queues, M_EPAIR);
776 /* Last free the cloner unit. */
777 ifc_free_unit(ifc, unit);
783 vnet_epair_init(const void *unused __unused)
786 V_epair_cloner = if_clone_advanced(epairname, 0,
787 epair_clone_match, epair_clone_create, epair_clone_destroy);
789 VNET_SYSINIT(vnet_epair_init, SI_SUB_PSEUDO, SI_ORDER_ANY,
790 vnet_epair_init, NULL);
793 vnet_epair_uninit(const void *unused __unused)
796 if_clone_detach(V_epair_cloner);
798 VNET_SYSUNINIT(vnet_epair_uninit, SI_SUB_INIT_IF, SI_ORDER_ANY,
799 vnet_epair_uninit, NULL);
805 epair_tasks.tasks = 0;
813 /* Pin to this CPU so we get appropriate NUMA allocations. */
814 thread_lock(curthread);
815 sched_bind(curthread, cpu);
816 thread_unlock(curthread);
818 snprintf(name, sizeof(name), "epair_task_%d", cpu);
820 epair_tasks.tq[cpu] = taskqueue_create(name, M_WAITOK,
821 taskqueue_thread_enqueue,
822 &epair_tasks.tq[cpu]);
823 CPU_SETOF(cpu, &cpu_mask);
824 taskqueue_start_threads_cpuset(&epair_tasks.tq[cpu], 1, PI_NET,
825 &cpu_mask, "%s", name);
829 thread_lock(curthread);
830 sched_unbind(curthread);
831 thread_unlock(curthread);
833 snprintf(name, sizeof(name), "epair_task");
835 epair_tasks.tq[0] = taskqueue_create(name, M_WAITOK,
836 taskqueue_thread_enqueue,
838 taskqueue_start_threads(&epair_tasks.tq[0], 1, PI_NET, "%s", name);
840 epair_tasks.tasks = 1;
847 epair_mod_cleanup(void)
850 for (int i = 0; i < epair_tasks.tasks; i++) {
851 taskqueue_drain_all(epair_tasks.tq[i]);
852 taskqueue_free(epair_tasks.tq[i]);
857 epair_modevent(module_t mod, int type, void *data)
864 ret = epair_mod_init();
868 printf("%s: %s initialized.\n", __func__, epairname);
872 EPAIR_LOCK_DESTROY();
874 printf("%s: %s unloaded.\n", __func__, epairname);
882 static moduledata_t epair_mod = {
888 DECLARE_MODULE(if_epair, epair_mod, SI_SUB_PSEUDO, SI_ORDER_MIDDLE);
889 MODULE_VERSION(if_epair, 3);