2 * SPDX-License-Identifier: BSD-2-Clause
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/interrupt.h>
52 #include <sys/kernel.h>
53 #include <sys/libkern.h>
54 #include <sys/malloc.h>
56 #include <sys/module.h>
58 #include <sys/queue.h>
59 #include <sys/sched.h>
61 #include <sys/socket.h>
62 #include <sys/sockio.h>
63 #include <sys/taskqueue.h>
66 #include <net/ethernet.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_private.h>
73 #include <net/if_types.h>
74 #include <net/netisr.h>
76 #include <net/rss_config.h>
78 #include <netinet/in_rss.h>
81 #include <netinet6/in6_rss.h>
86 static const char epairname[] = "epair";
87 #define RXRSIZE 4096 /* Probably overkill by 4-8x. */
89 static MALLOC_DEFINE(M_EPAIR, epairname,
90 "Pair of virtual cross-over connected Ethernet-like interfaces");
92 VNET_DEFINE_STATIC(struct if_clone *, epair_cloner);
93 #define V_epair_cloner VNET(epair_cloner)
95 static unsigned int next_index = 0;
96 #define EPAIR_LOCK_INIT() mtx_init(&epair_n_index_mtx, "epairidx", \
98 #define EPAIR_LOCK_DESTROY() mtx_destroy(&epair_n_index_mtx)
99 #define EPAIR_LOCK() mtx_lock(&epair_n_index_mtx)
100 #define EPAIR_UNLOCK() mtx_unlock(&epair_n_index_mtx)
113 struct epair_softc *sc;
116 static struct mtx epair_n_index_mtx;
118 struct ifnet *ifp; /* This ifp. */
119 struct ifnet *oifp; /* other ifp of pair. */
121 struct epair_queue *queues;
122 struct ifmedia media; /* Media config (fake). */
123 STAILQ_ENTRY(epair_softc) entry;
126 struct epair_tasks_t {
128 struct taskqueue *tq[MAXCPU];
131 static struct epair_tasks_t epair_tasks;
134 epair_clear_mbuf(struct mbuf *m)
138 /* Remove any CSUM_SND_TAG as ether_input will barf. */
139 if (m->m_pkthdr.csum_flags & CSUM_SND_TAG) {
140 m_snd_tag_rele(m->m_pkthdr.snd_tag);
141 m->m_pkthdr.snd_tag = NULL;
142 m->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
145 /* Clear vlan information. */
146 m->m_flags &= ~M_VLANTAG;
147 m->m_pkthdr.ether_vtag = 0;
149 m_tag_delete_nonpersistent(m);
153 epair_tx_start_deferred(void *arg, int pending)
155 struct epair_queue *q = (struct epair_queue *)arg;
163 CURVNET_SET(ifp->if_vnet);
166 m = mbufq_flush(&q->q);
167 q->state = EPAIR_QUEUE_RUNNING;
171 n = STAILQ_NEXT(m, m_stailqpkt);
178 * Avoid flushing the queue more than once per task. We can otherwise
179 * end up starving ourselves in a multi-epair routing configuration.
182 if (mbufq_len(&q->q) > 0) {
184 q->state = EPAIR_QUEUE_WAKING;
187 q->state = EPAIR_QUEUE_IDLE;
192 taskqueue_enqueue(epair_tasks.tq[q->id], &q->tx_task);
198 static struct epair_queue *
199 epair_select_queue(struct epair_softc *sc, struct mbuf *m)
203 struct ether_header *eh;
206 ret = rss_m2bucket(m, &bucket);
208 /* Actually hash the packet. */
209 eh = mtod(m, struct ether_header *);
211 switch (ntohs(eh->ether_type)) {
214 rss_soft_m2cpuid_v4(m, 0, &bucket);
219 rss_soft_m2cpuid_v6(m, 0, &bucket);
227 bucket %= sc->num_queues;
231 return (&sc->queues[bucket]);
235 epair_prepare_mbuf(struct mbuf *m, struct ifnet *src_ifp)
239 if_setrcvif(m, src_ifp);
240 M_SETFIB(m, src_ifp->if_fib);
242 MPASS(m->m_nextpkt == NULL);
243 MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
247 epair_menq(struct mbuf *m, struct epair_softc *osc)
249 struct epair_queue *q;
250 struct ifnet *ifp, *oifp;
255 * I know this looks weird. We pass the "other sc" as we need that one
256 * and can get both ifps from it as well.
261 epair_prepare_mbuf(m, oifp);
263 /* Save values as once the mbuf is queued, it's not ours anymore. */
264 len = m->m_pkthdr.len;
265 mcast = (m->m_flags & (M_BCAST | M_MCAST)) != 0;
267 q = epair_select_queue(osc, m);
270 if (q->state == EPAIR_QUEUE_IDLE) {
271 q->state = EPAIR_QUEUE_WAKING;
272 taskqueue_enqueue(epair_tasks.tq[q->id], &q->tx_task);
274 error = mbufq_enqueue(&q->q, m);
279 if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1);
281 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
282 if_inc_counter(ifp, IFCOUNTER_OBYTES, len);
284 if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
285 if_inc_counter(oifp, IFCOUNTER_IPACKETS, 1);
290 epair_start(struct ifnet *ifp)
293 struct epair_softc *sc;
297 * We get packets here from ether_output via if_handoff()
298 * and need to put them into the input queue of the oifp
299 * and will put the packet into the receive-queue (rxq) of the
300 * other interface (oifp) of our pair.
306 IFQ_DEQUEUE(&ifp->if_snd, m);
312 /* In case either interface is not usable drop the packet. */
313 if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
314 (ifp->if_flags & IFF_UP) == 0 ||
315 (oifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
316 (oifp->if_flags & IFF_UP) == 0) {
326 epair_transmit(struct ifnet *ifp, struct mbuf *m)
328 struct epair_softc *sc;
340 * We could just transmit this, but it makes testing easier if we're a
341 * little bit more like real hardware.
342 * Allow just that little bit extra for ethernet (and vlan) headers.
344 if (m->m_pkthdr.len > (ifp->if_mtu + sizeof(struct ether_vlan_header))) {
346 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
351 * We are not going to use the interface en/dequeue mechanism
352 * on the TX side. We are called from ether_output_frame()
353 * and will put the packet into the receive-queue (rxq) of the
354 * other interface (oifp) of our pair.
356 if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
358 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
361 if ((ifp->if_flags & IFF_UP) == 0) {
363 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
370 * In case the outgoing interface is not usable,
375 if ((oifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
376 (oifp->if_flags & IFF_UP) == 0) {
377 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
383 len = m->m_pkthdr.len;
384 mcast = (m->m_flags & (M_BCAST | M_MCAST)) != 0;
387 /* Support ALTQ via the classic if_start() path. */
388 IF_LOCK(&ifp->if_snd);
389 if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
390 ALTQ_ENQUEUE(&ifp->if_snd, m, NULL, error);
392 if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1);
393 IF_UNLOCK(&ifp->if_snd);
395 if_inc_counter(ifp, IFCOUNTER_OBYTES, len);
397 if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
402 IF_UNLOCK(&ifp->if_snd);
405 epair_menq(m, oifp->if_softc);
410 epair_qflush(struct ifnet *ifp __unused)
415 epair_media_change(struct ifnet *ifp __unused)
423 epair_media_status(struct ifnet *ifp __unused, struct ifmediareq *imr)
426 imr->ifm_status = IFM_AVALID | IFM_ACTIVE;
427 imr->ifm_active = IFM_ETHER | IFM_10G_T | IFM_FDX;
431 epair_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
433 struct epair_softc *sc;
437 ifr = (struct ifreq *)data;
448 error = ifmedia_ioctl(ifp, ifr, &sc->media, cmd);
452 /* We basically allow all kinds of MTUs. */
453 ifp->if_mtu = ifr->ifr_mtu;
458 /* Let the common ethernet handler process this. */
459 error = ether_ioctl(ifp, cmd, data);
467 epair_init(void *dummy __unused)
472 * Interface cloning functions.
473 * We use our private ones so that we can create/destroy our secondary
474 * device along with the primary one.
477 epair_clone_match(struct if_clone *ifc, const char *name)
482 * Our base name is epair.
483 * Our interfaces will be named epair<n>[ab].
484 * So accept anything of the following list:
487 * but not the epair<n>[ab] versions.
489 if (strncmp(epairname, name, sizeof(epairname)-1) != 0)
492 for (cp = name + sizeof(epairname) - 1; *cp != '\0'; cp++) {
493 if (*cp < '0' || *cp > '9')
501 epair_clone_add(struct if_clone *ifc, struct epair_softc *scb)
504 uint8_t eaddr[ETHER_ADDR_LEN]; /* 00:00:00:00:00:00 */
507 /* Copy epairNa etheraddr and change the last byte. */
508 memcpy(eaddr, scb->oifp->if_hw_addr, ETHER_ADDR_LEN);
510 ether_ifattach(ifp, eaddr);
512 if_clone_addif(ifc, ifp);
515 static struct epair_softc *
516 epair_alloc_sc(struct if_clone *ifc)
518 struct epair_softc *sc;
520 struct ifnet *ifp = if_alloc(IFT_ETHER);
524 sc = malloc(sizeof(struct epair_softc), M_EPAIR, M_WAITOK | M_ZERO);
526 sc->num_queues = epair_tasks.tasks;
527 sc->queues = mallocarray(sc->num_queues, sizeof(struct epair_queue),
529 for (int i = 0; i < sc->num_queues; i++) {
530 struct epair_queue *q = &sc->queues[i];
532 q->state = EPAIR_QUEUE_IDLE;
533 mtx_init(&q->mtx, "epairq", NULL, MTX_DEF | MTX_NEW);
534 mbufq_init(&q->q, RXRSIZE);
536 NET_TASK_INIT(&q->tx_task, 0, epair_tx_start_deferred, q);
539 /* Initialise pseudo media types. */
540 ifmedia_init(&sc->media, 0, epair_media_change, epair_media_status);
541 ifmedia_add(&sc->media, IFM_ETHER | IFM_10G_T, 0, NULL);
542 ifmedia_set(&sc->media, IFM_ETHER | IFM_10G_T);
548 epair_setup_ifp(struct epair_softc *sc, char *name, int unit)
550 struct ifnet *ifp = sc->ifp;
553 strlcpy(ifp->if_xname, name, IFNAMSIZ);
554 ifp->if_dname = epairname;
555 ifp->if_dunit = unit;
556 ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
557 ifp->if_capabilities = IFCAP_VLAN_MTU;
558 ifp->if_capenable = IFCAP_VLAN_MTU;
559 ifp->if_transmit = epair_transmit;
560 ifp->if_qflush = epair_qflush;
561 ifp->if_start = epair_start;
562 ifp->if_ioctl = epair_ioctl;
563 ifp->if_init = epair_init;
564 if_setsendqlen(ifp, ifqmaxlen);
565 if_setsendqready(ifp);
567 ifp->if_baudrate = IF_Gbps(10); /* arbitrary maximum */
571 epair_generate_mac(struct epair_softc *sc, uint8_t *eaddr)
579 /* Get an approximate distribution. */
580 hash = next_index % mp_ncpus;
587 * Calculate the etheraddr hashing the hostid and the
588 * interface index. The result would be hopefully unique.
589 * Note that the "a" component of an epair instance may get moved
590 * to a different VNET after creation. In that case its index
591 * will be freed and the index can get reused by new epair instance.
592 * Make sure we do not create same etheraddr again.
594 getcredhostid(curthread->td_ucred, (unsigned long *)&hostid);
596 arc4rand(&hostid, sizeof(hostid), 0);
598 struct ifnet *ifp = sc->ifp;
600 if (ifp->if_index > next_index)
601 next_index = ifp->if_index;
605 key[0] = (uint32_t)next_index;
607 key[1] = (uint32_t)(hostid & 0xffffffff);
608 key[2] = (uint32_t)((hostid >> 32) & 0xfffffffff);
609 hash = jenkins_hash32(key, 3, 0);
612 memcpy(&eaddr[1], &hash, 4);
617 epair_free_sc(struct epair_softc *sc)
623 ifmedia_removeall(&sc->media);
624 for (int i = 0; i < sc->num_queues; i++) {
625 struct epair_queue *q = &sc->queues[i];
626 mtx_destroy(&q->mtx);
628 free(sc->queues, M_EPAIR);
633 epair_set_state(struct ifnet *ifp, bool running)
636 ifp->if_drv_flags |= IFF_DRV_RUNNING;
637 if_link_state_change(ifp, LINK_STATE_UP);
639 if_link_state_change(ifp, LINK_STATE_DOWN);
640 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
645 epair_handle_unit(struct if_clone *ifc, char *name, size_t len, int *punit)
647 int error = 0, unit, wildcard;
650 /* Try to see if a special unit was requested. */
651 error = ifc_name2unit(name, &unit);
654 wildcard = (unit < 0);
656 error = ifc_alloc_unit(ifc, &unit);
661 * If no unit had been given, we need to adjust the ifName.
662 * Also make sure there is space for our extra [ab] suffix.
664 for (dp = name; *dp != '\0'; dp++);
666 int slen = snprintf(dp, len - (dp - name), "%d", unit);
667 if (slen > len - (dp - name) - 1) {
668 /* ifName too long. */
674 if (len - (dp - name) - 1 < 1) {
675 /* No space left for our [ab] suffix. */
680 /* Must not change dp so we can replace 'a' by 'b' later. */
683 /* Check if 'a' and 'b' interfaces already exist. */
684 if (ifunit(name) != NULL) {
690 if (ifunit(name) != NULL) {
697 ifc_free_unit(ifc, unit);
703 epair_clone_create(struct if_clone *ifc, char *name, size_t len,
704 struct ifc_data *ifd, struct ifnet **ifpp)
706 struct epair_softc *sca, *scb;
710 uint8_t eaddr[ETHER_ADDR_LEN]; /* 00:00:00:00:00:00 */
712 error = epair_handle_unit(ifc, name, len, &unit);
716 /* Allocate memory for both [ab] interfaces */
717 sca = epair_alloc_sc(ifc);
718 scb = epair_alloc_sc(ifc);
719 if (sca == NULL || scb == NULL) {
722 ifc_free_unit(ifc, unit);
727 * Cross-reference the interfaces so we will be able to free both.
729 sca->oifp = scb->ifp;
730 scb->oifp = sca->ifp;
732 /* Finish initialization of interface <n>a. */
734 epair_setup_ifp(sca, name, unit);
735 epair_generate_mac(sca, eaddr);
737 ether_ifattach(ifp, eaddr);
739 /* Swap the name and finish initialization of interface <n>b. */
740 dp = name + strlen(name) - 1;
743 epair_setup_ifp(scb, name, unit);
746 /* We need to play some tricks here for the second interface. */
747 strlcpy(name, epairname, len);
748 /* Correctly set the name for the cloner list. */
749 strlcpy(name, scb->ifp->if_xname, len);
751 epair_clone_add(ifc, scb);
754 * Restore name to <n>a as the ifp for this will go into the
755 * cloner list for the initial call.
757 strlcpy(name, sca->ifp->if_xname, len);
759 /* Tell the world, that we are ready to rock. */
760 epair_set_state(sca->ifp, true);
761 epair_set_state(scb->ifp, true);
769 epair_drain_rings(struct epair_softc *sc)
771 for (int i = 0; i < sc->num_queues; i++) {
772 struct epair_queue *q;
777 m = mbufq_flush(&q->q);
780 for (; m != NULL; m = n) {
788 epair_clone_destroy(struct if_clone *ifc, struct ifnet *ifp, uint32_t flags)
791 struct epair_softc *sca, *scb;
795 * In case we called into if_clone_destroyif() ourselves
796 * again to remove the second interface, the softc will be
797 * NULL. In that case so not do anything but return success.
799 if (ifp->if_softc == NULL)
802 unit = ifp->if_dunit;
805 scb = oifp->if_softc;
807 /* Frist get the interfaces down and detached. */
808 epair_set_state(ifp, false);
809 epair_set_state(oifp, false);
812 ether_ifdetach(oifp);
814 /* Third free any queued packets and all the resources. */
815 CURVNET_SET_QUIET(oifp->if_vnet);
816 epair_drain_rings(scb);
817 oifp->if_softc = NULL;
818 error = if_clone_destroyif(ifc, oifp);
820 panic("%s: if_clone_destroyif() for our 2nd iface failed: %d",
825 epair_drain_rings(sca);
828 /* Last free the cloner unit. */
829 ifc_free_unit(ifc, unit);
835 vnet_epair_init(const void *unused __unused)
837 struct if_clone_addreq req = {
838 .match_f = epair_clone_match,
839 .create_f = epair_clone_create,
840 .destroy_f = epair_clone_destroy,
842 V_epair_cloner = ifc_attach_cloner(epairname, &req);
844 VNET_SYSINIT(vnet_epair_init, SI_SUB_PSEUDO, SI_ORDER_ANY,
845 vnet_epair_init, NULL);
848 vnet_epair_uninit(const void *unused __unused)
851 ifc_detach_cloner(V_epair_cloner);
853 VNET_SYSUNINIT(vnet_epair_uninit, SI_SUB_INIT_IF, SI_ORDER_ANY,
854 vnet_epair_uninit, NULL);
860 epair_tasks.tasks = 0;
868 /* Pin to this CPU so we get appropriate NUMA allocations. */
869 thread_lock(curthread);
870 sched_bind(curthread, cpu);
871 thread_unlock(curthread);
873 snprintf(name, sizeof(name), "epair_task_%d", cpu);
875 epair_tasks.tq[cpu] = taskqueue_create(name, M_WAITOK,
876 taskqueue_thread_enqueue,
877 &epair_tasks.tq[cpu]);
878 CPU_SETOF(cpu, &cpu_mask);
879 taskqueue_start_threads_cpuset(&epair_tasks.tq[cpu], 1, PI_NET,
880 &cpu_mask, "%s", name);
884 thread_lock(curthread);
885 sched_unbind(curthread);
886 thread_unlock(curthread);
888 snprintf(name, sizeof(name), "epair_task");
890 epair_tasks.tq[0] = taskqueue_create(name, M_WAITOK,
891 taskqueue_thread_enqueue,
893 taskqueue_start_threads(&epair_tasks.tq[0], 1, PI_NET, "%s", name);
895 epair_tasks.tasks = 1;
902 epair_mod_cleanup(void)
905 for (int i = 0; i < epair_tasks.tasks; i++) {
906 taskqueue_drain_all(epair_tasks.tq[i]);
907 taskqueue_free(epair_tasks.tq[i]);
912 epair_modevent(module_t mod, int type, void *data)
919 ret = epair_mod_init();
923 printf("%s: %s initialized.\n", __func__, epairname);
927 EPAIR_LOCK_DESTROY();
929 printf("%s: %s unloaded.\n", __func__, epairname);
937 static moduledata_t epair_mod = {
943 DECLARE_MODULE(if_epair, epair_mod, SI_SUB_PSEUDO, SI_ORDER_MIDDLE);
944 MODULE_VERSION(if_epair, 3);