Home | History | Annotate | Line # | Download | only in net
      1 /*	$NetBSD: if.c,v 1.538 2026/05/14 08:05:48 roy Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2001, 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by William Studenmund and Jason R. Thorpe.
      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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
     34  * All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. Neither the name of the project nor the names of its contributors
     45  *    may be used to endorse or promote products derived from this software
     46  *    without specific prior written permission.
     47  *
     48  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     58  * SUCH DAMAGE.
     59  */
     60 
     61 /*
     62  * Copyright (c) 1980, 1986, 1993
     63  *	The Regents of the University of California.  All rights reserved.
     64  *
     65  * Redistribution and use in source and binary forms, with or without
     66  * modification, are permitted provided that the following conditions
     67  * are met:
     68  * 1. Redistributions of source code must retain the above copyright
     69  *    notice, this list of conditions and the following disclaimer.
     70  * 2. Redistributions in binary form must reproduce the above copyright
     71  *    notice, this list of conditions and the following disclaimer in the
     72  *    documentation and/or other materials provided with the distribution.
     73  * 3. Neither the name of the University nor the names of its contributors
     74  *    may be used to endorse or promote products derived from this software
     75  *    without specific prior written permission.
     76  *
     77  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     78  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     79  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     80  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     81  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     82  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     83  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     84  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     85  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     86  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     87  * SUCH DAMAGE.
     88  *
     89  *	@(#)if.c	8.5 (Berkeley) 1/9/95
     90  */
     91 
     92 #include <sys/cdefs.h>
     93 __KERNEL_RCSID(0, "$NetBSD: if.c,v 1.538 2026/05/14 08:05:48 roy Exp $");
     94 
     95 #if defined(_KERNEL_OPT)
     96 #include "opt_inet.h"
     97 #include "opt_ipsec.h"
     98 #include "opt_atalk.h"
     99 #include "opt_wlan.h"
    100 #include "opt_net_mpsafe.h"
    101 #include "opt_mrouting.h"
    102 #endif
    103 
    104 #include <sys/param.h>
    105 #include <sys/mbuf.h>
    106 #include <sys/systm.h>
    107 #include <sys/callout.h>
    108 #include <sys/proc.h>
    109 #include <sys/socket.h>
    110 #include <sys/socketvar.h>
    111 #include <sys/domain.h>
    112 #include <sys/protosw.h>
    113 #include <sys/kernel.h>
    114 #include <sys/ioctl.h>
    115 #include <sys/sysctl.h>
    116 #include <sys/syslog.h>
    117 #include <sys/kauth.h>
    118 #include <sys/kmem.h>
    119 #include <sys/xcall.h>
    120 #include <sys/cpu.h>
    121 #include <sys/intr.h>
    122 #include <sys/module_hook.h>
    123 #include <sys/compat_stub.h>
    124 #include <sys/msan.h>
    125 #include <sys/hook.h>
    126 
    127 #include <net/if.h>
    128 #include <net/if_dl.h>
    129 #include <net/if_ether.h>
    130 #include <net/if_media.h>
    131 #include <net80211/ieee80211.h>
    132 #include <net80211/ieee80211_ioctl.h>
    133 #include <net/if_types.h>
    134 #include <net/route.h>
    135 #include <sys/module.h>
    136 #ifdef NETATALK
    137 #include <netatalk/at_extern.h>
    138 #include <netatalk/at.h>
    139 #endif
    140 #include <net/pfil.h>
    141 #include <netinet/in.h>
    142 #include <netinet/in_var.h>
    143 #include <netinet/ip_encap.h>
    144 #include <net/bpf.h>
    145 
    146 #ifdef INET6
    147 #include <netinet6/in6_var.h>
    148 #include <netinet6/nd6.h>
    149 #endif
    150 
    151 #include "ether.h"
    152 
    153 #include "bridge.h"
    154 #if NBRIDGE > 0
    155 #include <net/if_bridgevar.h>
    156 #endif
    157 
    158 #include "carp.h"
    159 #if NCARP > 0
    160 #include <netinet/ip_carp.h>
    161 #endif
    162 
    163 #include <compat/sys/sockio.h>
    164 
    165 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
    166 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
    167 
    168 /*
    169  * XXX reusing (ifp)->if_snd->ifq_lock rather than having another spin mutex
    170  * for each ifnet.  It doesn't matter because:
    171  * - if IFEF_MPSAFE is enabled, if_snd isn't used and lock contentions on
    172  *   ifq_lock don't happen
    173  * - if IFEF_MPSAFE is disabled, there is no lock contention on ifq_lock
    174  *   because if_snd, if_link_state_change and if_link_state_change_process
    175  *   are all called with KERNEL_LOCK
    176  */
    177 #define IF_LINK_STATE_CHANGE_LOCK(ifp)		\
    178 	mutex_enter((ifp)->if_snd.ifq_lock)
    179 #define IF_LINK_STATE_CHANGE_UNLOCK(ifp)	\
    180 	mutex_exit((ifp)->if_snd.ifq_lock)
    181 
    182 /*
    183  * Global list of interfaces.
    184  */
    185 /* DEPRECATED. Remove it once kvm(3) users disappeared */
    186 struct ifnet_head		ifnet_list;
    187 
    188 struct pslist_head		ifnet_pslist;
    189 static ifnet_t **		ifindex2ifnet = NULL;
    190 static u_int			if_index = 1;
    191 static size_t			if_indexlim = 0;
    192 static uint64_t			index_gen;
    193 /* Mutex to protect the above objects. */
    194 kmutex_t			ifnet_mtx __cacheline_aligned;
    195 static struct psref_class	*ifnet_psref_class __read_mostly;
    196 static pserialize_t		ifnet_psz;
    197 static struct workqueue		*ifnet_link_state_wq __read_mostly;
    198 
    199 static struct workqueue		*if_slowtimo_wq __read_mostly;
    200 
    201 static kmutex_t			if_clone_mtx;
    202 
    203 struct ifnet *lo0ifp;
    204 int	ifqmaxlen = IFQ_MAXLEN;
    205 
    206 struct psref_class		*ifa_psref_class __read_mostly;
    207 
    208 static int	if_delroute_matcher(struct rtentry *, void *);
    209 
    210 static bool if_is_unit(const char *);
    211 static struct if_clone *if_clone_lookup(const char *, int *);
    212 
    213 static LIST_HEAD(, if_clone) if_cloners = LIST_HEAD_INITIALIZER(if_cloners);
    214 static int if_cloners_count;
    215 
    216 /* Packet filtering hook for interfaces. */
    217 pfil_head_t *			if_pfil __read_mostly;
    218 
    219 static kauth_listener_t if_listener;
    220 
    221 static int doifioctl(struct socket *, u_long, void *, struct lwp *);
    222 static void sysctl_sndq_setup(struct sysctllog **, const char *,
    223     struct ifaltq *);
    224 static void if_slowtimo_intr(void *);
    225 static void if_slowtimo_work(struct work *, void *);
    226 static int sysctl_if_watchdog(SYSCTLFN_PROTO);
    227 static void sysctl_watchdog_setup(struct ifnet *);
    228 static void if_attachdomain1(struct ifnet *);
    229 static int ifconf(u_long, void *);
    230 static int if_transmit(struct ifnet *, struct mbuf *);
    231 static int if_clone_create(const char *);
    232 static int if_clone_destroy(const char *);
    233 static void if_link_state_change_work(struct work *, void *);
    234 static void if_up_locked(struct ifnet *);
    235 static void _if_down(struct ifnet *);
    236 static void if_down_deactivated(struct ifnet *);
    237 
    238 struct if_percpuq {
    239 	struct ifnet	*ipq_ifp;
    240 	void		*ipq_si;
    241 	struct percpu	*ipq_ifqs;	/* struct ifqueue */
    242 };
    243 
    244 static struct mbuf *if_percpuq_dequeue(struct if_percpuq *);
    245 
    246 static void if_percpuq_drops(void *, void *, struct cpu_info *);
    247 static int sysctl_percpuq_drops_handler(SYSCTLFN_PROTO);
    248 static void sysctl_percpuq_setup(struct sysctllog **, const char *,
    249     struct if_percpuq *);
    250 
    251 struct if_deferred_start {
    252 	struct ifnet	*ids_ifp;
    253 	void		(*ids_if_start)(struct ifnet *);
    254 	void		*ids_si;
    255 };
    256 
    257 static void if_deferred_start_softint(void *);
    258 static void if_deferred_start_common(struct ifnet *);
    259 static void if_deferred_start_destroy(struct ifnet *);
    260 
    261 struct if_slowtimo_data {
    262 	kmutex_t		isd_lock;
    263 	struct callout		isd_ch;
    264 	struct work		isd_work;
    265 	struct ifnet		*isd_ifp;
    266 	bool			isd_queued;
    267 	bool			isd_dying;
    268 	bool			isd_trigger;
    269 };
    270 
    271 /*
    272  * Hook for if_vlan - needed by if_agr
    273  */
    274 struct if_vlan_vlan_input_hook_t if_vlan_vlan_input_hook;
    275 
    276 static void if_sysctl_setup(struct sysctllog **);
    277 
    278 static int
    279 if_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    280     void *arg0, void *arg1, void *arg2, void *arg3)
    281 {
    282 	int result;
    283 	enum kauth_network_req req;
    284 
    285 	result = KAUTH_RESULT_DEFER;
    286 	req = (enum kauth_network_req)(uintptr_t)arg1;
    287 
    288 	if (action != KAUTH_NETWORK_INTERFACE)
    289 		return result;
    290 
    291 	if ((req == KAUTH_REQ_NETWORK_INTERFACE_GET) ||
    292 	    (req == KAUTH_REQ_NETWORK_INTERFACE_SET))
    293 		result = KAUTH_RESULT_ALLOW;
    294 
    295 	return result;
    296 }
    297 
    298 /*
    299  * Network interface utility routines.
    300  *
    301  * Routines with ifa_ifwith* names take sockaddr *'s as
    302  * parameters.
    303  */
    304 void
    305 ifinit(void)
    306 {
    307 
    308 #if (defined(INET) || defined(INET6))
    309 	encapinit();
    310 #endif
    311 
    312 	if_listener = kauth_listen_scope(KAUTH_SCOPE_NETWORK,
    313 	    if_listener_cb, NULL);
    314 
    315 	/* interfaces are available, inform socket code */
    316 	ifioctl = doifioctl;
    317 }
    318 
    319 /*
    320  * XXX Initialization before configure().
    321  * XXX hack to get pfil_add_hook working in autoconf.
    322  */
    323 void
    324 ifinit1(void)
    325 {
    326 	int error __diagused;
    327 
    328 #ifdef NET_MPSAFE
    329 	printf("NET_MPSAFE enabled\n");
    330 #endif
    331 
    332 	mutex_init(&if_clone_mtx, MUTEX_DEFAULT, IPL_NONE);
    333 
    334 	TAILQ_INIT(&ifnet_list);
    335 	mutex_init(&ifnet_mtx, MUTEX_DEFAULT, IPL_NONE);
    336 	ifnet_psz = pserialize_create();
    337 	ifnet_psref_class = psref_class_create("ifnet", IPL_SOFTNET);
    338 	ifa_psref_class = psref_class_create("ifa", IPL_SOFTNET);
    339 	error = workqueue_create(&ifnet_link_state_wq, "iflnkst",
    340 	    if_link_state_change_work, NULL, PRI_SOFTNET, IPL_NET,
    341 	    WQ_MPSAFE);
    342 	KASSERT(error == 0);
    343 	PSLIST_INIT(&ifnet_pslist);
    344 
    345 	error = workqueue_create(&if_slowtimo_wq, "ifwdog",
    346 	    if_slowtimo_work, NULL, PRI_SOFTNET, IPL_SOFTCLOCK, WQ_MPSAFE);
    347 	KASSERTMSG(error == 0, "error=%d", error);
    348 
    349 	if_indexlim = 8;
    350 
    351 	if_pfil = pfil_head_create(PFIL_TYPE_IFNET, NULL);
    352 	KASSERT(if_pfil != NULL);
    353 
    354 #if NETHER > 0 || defined(NETATALK) || defined(WLAN)
    355 	etherinit();
    356 #endif
    357 }
    358 
    359 /* XXX must be after domaininit() */
    360 void
    361 ifinit_post(void)
    362 {
    363 
    364 	if_sysctl_setup(NULL);
    365 }
    366 
    367 ifnet_t *
    368 if_alloc(u_char type)
    369 {
    370 
    371 	return kmem_zalloc(sizeof(ifnet_t), KM_SLEEP);
    372 }
    373 
    374 void
    375 if_free(ifnet_t *ifp)
    376 {
    377 
    378 	kmem_free(ifp, sizeof(ifnet_t));
    379 }
    380 
    381 void
    382 if_initname(struct ifnet *ifp, const char *name, int unit)
    383 {
    384 
    385 	(void)snprintf(ifp->if_xname, sizeof(ifp->if_xname),
    386 	    "%s%d", name, unit);
    387 }
    388 
    389 /*
    390  * Null routines used while an interface is going away.  These routines
    391  * just return an error.
    392  */
    393 
    394 int
    395 if_nulloutput(struct ifnet *ifp, struct mbuf *m,
    396     const struct sockaddr *so, const struct rtentry *rt)
    397 {
    398 
    399 	return ENXIO;
    400 }
    401 
    402 void
    403 if_nullinput(struct ifnet *ifp, struct mbuf *m)
    404 {
    405 
    406 	/* Nothing. */
    407 }
    408 
    409 void
    410 if_nullstart(struct ifnet *ifp)
    411 {
    412 
    413 	/* Nothing. */
    414 }
    415 
    416 int
    417 if_nulltransmit(struct ifnet *ifp, struct mbuf *m)
    418 {
    419 
    420 	m_freem(m);
    421 	return ENXIO;
    422 }
    423 
    424 int
    425 if_nullioctl(struct ifnet *ifp, u_long cmd, void *data)
    426 {
    427 
    428 	return ENXIO;
    429 }
    430 
    431 int
    432 if_nullinit(struct ifnet *ifp)
    433 {
    434 
    435 	return ENXIO;
    436 }
    437 
    438 void
    439 if_nullstop(struct ifnet *ifp, int disable)
    440 {
    441 
    442 	/* Nothing. */
    443 }
    444 
    445 void
    446 if_nullslowtimo(struct ifnet *ifp)
    447 {
    448 
    449 	/* Nothing. */
    450 }
    451 
    452 void
    453 if_nulldrain(struct ifnet *ifp)
    454 {
    455 
    456 	/* Nothing. */
    457 }
    458 
    459 void
    460 if_set_sadl(struct ifnet *ifp, const void *lla, u_char addrlen, bool factory)
    461 {
    462 	struct ifaddr *ifa;
    463 	struct sockaddr_dl *sdl;
    464 
    465 	ifp->if_addrlen = addrlen;
    466 	if_alloc_sadl(ifp);
    467 	ifa = ifp->if_dl;
    468 	sdl = satosdl(ifa->ifa_addr);
    469 
    470 	(void)sockaddr_dl_setaddr(sdl, sdl->sdl_len, lla, ifp->if_addrlen);
    471 	if (factory) {
    472 		KASSERT(ifp->if_hwdl == NULL);
    473 		ifp->if_hwdl = ifp->if_dl;
    474 		ifaref(ifp->if_hwdl);
    475 	}
    476 	/* TBD routing socket */
    477 }
    478 
    479 struct ifaddr *
    480 if_dl_create(const struct ifnet *ifp, const struct sockaddr_dl **sdlp)
    481 {
    482 	unsigned socksize, ifasize;
    483 	int addrlen, namelen;
    484 	struct sockaddr_dl *mask, *sdl;
    485 	struct ifaddr *ifa;
    486 
    487 	namelen = strlen(ifp->if_xname);
    488 	addrlen = ifp->if_addrlen;
    489 	socksize = roundup(sockaddr_dl_measure(namelen, addrlen),
    490 	    sizeof(long));
    491 	ifasize = sizeof(*ifa) + 2 * socksize;
    492 	ifa = malloc(ifasize, M_IFADDR, M_WAITOK | M_ZERO);
    493 
    494 	sdl = (struct sockaddr_dl *)(ifa + 1);
    495 	mask = (struct sockaddr_dl *)(socksize + (char *)sdl);
    496 
    497 	sockaddr_dl_init(sdl, socksize, ifp->if_index, ifp->if_type,
    498 	    ifp->if_xname, namelen, NULL, addrlen);
    499 	mask->sdl_family = AF_LINK;
    500 	mask->sdl_len = sockaddr_dl_measure(namelen, 0);
    501 	memset(&mask->sdl_data[0], 0xff, namelen);
    502 	ifa->ifa_rtrequest = link_rtrequest;
    503 	ifa->ifa_addr = (struct sockaddr *)sdl;
    504 	ifa->ifa_netmask = (struct sockaddr *)mask;
    505 	ifa_psref_init(ifa);
    506 
    507 	*sdlp = sdl;
    508 
    509 	return ifa;
    510 }
    511 
    512 static void
    513 if_sadl_setrefs(struct ifnet *ifp, struct ifaddr *ifa)
    514 {
    515 	const struct sockaddr_dl *sdl;
    516 
    517 	ifp->if_dl = ifa;
    518 	ifaref(ifa);
    519 	sdl = satosdl(ifa->ifa_addr);
    520 	ifp->if_sadl = sdl;
    521 }
    522 
    523 /*
    524  * Allocate the link level name for the specified interface.  This
    525  * is an attachment helper.  It must be called after ifp->if_addrlen
    526  * is initialized, which may not be the case when if_attach() is
    527  * called.
    528  */
    529 void
    530 if_alloc_sadl(struct ifnet *ifp)
    531 {
    532 	struct ifaddr *ifa;
    533 	const struct sockaddr_dl *sdl;
    534 
    535 	/*
    536 	 * If the interface already has a link name, release it
    537 	 * now.  This is useful for interfaces that can change
    538 	 * link types, and thus switch link names often.
    539 	 */
    540 	if (ifp->if_sadl != NULL)
    541 		if_free_sadl(ifp, 0);
    542 
    543 	ifa = if_dl_create(ifp, &sdl);
    544 
    545 	ifa_insert(ifp, ifa);
    546 	if_sadl_setrefs(ifp, ifa);
    547 }
    548 
    549 static void
    550 if_deactivate_sadl(struct ifnet *ifp)
    551 {
    552 	struct ifaddr *ifa;
    553 
    554 	KASSERT(ifp->if_dl != NULL);
    555 
    556 	ifa = ifp->if_dl;
    557 
    558 	ifp->if_sadl = NULL;
    559 
    560 	ifp->if_dl = NULL;
    561 	ifafree(ifa);
    562 }
    563 
    564 static void
    565 if_replace_sadl(struct ifnet *ifp, struct ifaddr *ifa)
    566 {
    567 	struct ifaddr *old;
    568 
    569 	KASSERT(ifp->if_dl != NULL);
    570 
    571 	old = ifp->if_dl;
    572 
    573 	ifaref(ifa);
    574 	/* XXX Update if_dl and if_sadl atomically */
    575 	ifp->if_dl = ifa;
    576 	ifp->if_sadl = satosdl(ifa->ifa_addr);
    577 
    578 	ifafree(old);
    579 }
    580 
    581 void
    582 if_activate_sadl(struct ifnet *ifp, struct ifaddr *ifa0,
    583     const struct sockaddr_dl *sdl)
    584 {
    585 	struct ifaddr *ifa;
    586 	const int bound = curlwp_bind();
    587 
    588 	KASSERT(ifa_held(ifa0));
    589 
    590 	const int s = splsoftnet();
    591 
    592 	if_replace_sadl(ifp, ifa0);
    593 
    594 	int ss = pserialize_read_enter();
    595 	IFADDR_READER_FOREACH(ifa, ifp) {
    596 		struct psref psref;
    597 		ifa_acquire(ifa, &psref);
    598 		pserialize_read_exit(ss);
    599 
    600 		rtinit(ifa, RTM_LLINFO_UPD, 0);
    601 
    602 		ss = pserialize_read_enter();
    603 		ifa_release(ifa, &psref);
    604 	}
    605 	pserialize_read_exit(ss);
    606 
    607 	splx(s);
    608 	curlwp_bindx(bound);
    609 }
    610 
    611 /*
    612  * Free the link level name for the specified interface.  This is
    613  * a detach helper.  This is called from if_detach().
    614  */
    615 void
    616 if_free_sadl(struct ifnet *ifp, int factory)
    617 {
    618 	struct ifaddr *ifa;
    619 
    620 	if (factory && ifp->if_hwdl != NULL) {
    621 		ifa = ifp->if_hwdl;
    622 		ifp->if_hwdl = NULL;
    623 		ifafree(ifa);
    624 	}
    625 
    626 	ifa = ifp->if_dl;
    627 	if (ifa == NULL) {
    628 		KASSERT(ifp->if_sadl == NULL);
    629 		return;
    630 	}
    631 
    632 	KASSERT(ifp->if_sadl != NULL);
    633 
    634 	const int s = splsoftnet();
    635 	KASSERT(ifa->ifa_addr->sa_family == AF_LINK);
    636 	ifa_remove(ifp, ifa);
    637 	if_deactivate_sadl(ifp);
    638 	splx(s);
    639 }
    640 
    641 static void
    642 if_getindex(ifnet_t *ifp)
    643 {
    644 	bool hitlimit = false;
    645 
    646 	ifp->if_index_gen = index_gen++;
    647 
    648 	ifp->if_index = if_index;
    649 	if (ifindex2ifnet == NULL) {
    650 		if_index++;
    651 		goto skip;
    652 	}
    653 	while (if_byindex(ifp->if_index)) {
    654 		/*
    655 		 * If we hit USHRT_MAX, we skip back to 0 since
    656 		 * there are a number of places where the value
    657 		 * of if_index or if_index itself is compared
    658 		 * to or stored in an unsigned short.  By
    659 		 * jumping back, we won't botch those assignments
    660 		 * or comparisons.
    661 		 */
    662 		if (++if_index == 0) {
    663 			if_index = 1;
    664 		} else if (if_index == USHRT_MAX) {
    665 			/*
    666 			 * However, if we have to jump back to
    667 			 * zero *twice* without finding an empty
    668 			 * slot in ifindex2ifnet[], then there
    669 			 * there are too many (>65535) interfaces.
    670 			 */
    671 			if (hitlimit)
    672 				panic("too many interfaces");
    673 			hitlimit = true;
    674 			if_index = 1;
    675 		}
    676 		ifp->if_index = if_index;
    677 	}
    678 skip:
    679 	/*
    680 	 * ifindex2ifnet is indexed by if_index. Since if_index will
    681 	 * grow dynamically, it should grow too.
    682 	 */
    683 	if (ifindex2ifnet == NULL || ifp->if_index >= if_indexlim) {
    684 		size_t m, n, oldlim;
    685 		void *q;
    686 
    687 		oldlim = if_indexlim;
    688 		while (ifp->if_index >= if_indexlim)
    689 			if_indexlim <<= 1;
    690 
    691 		/* grow ifindex2ifnet */
    692 		m = oldlim * sizeof(struct ifnet *);
    693 		n = if_indexlim * sizeof(struct ifnet *);
    694 		q = malloc(n, M_IFADDR, M_WAITOK | M_ZERO);
    695 		if (ifindex2ifnet != NULL) {
    696 			memcpy(q, ifindex2ifnet, m);
    697 			free(ifindex2ifnet, M_IFADDR);
    698 		}
    699 		ifindex2ifnet = (struct ifnet **)q;
    700 	}
    701 	ifindex2ifnet[ifp->if_index] = ifp;
    702 }
    703 
    704 /*
    705  * Initialize an interface and assign an index for it.
    706  *
    707  * It must be called prior to a device specific attach routine
    708  * (e.g., ether_ifattach and ieee80211_ifattach) or if_alloc_sadl,
    709  * and be followed by if_register:
    710  *
    711  *     if_initialize(ifp);
    712  *     ether_ifattach(ifp, enaddr);
    713  *     if_register(ifp);
    714  */
    715 void
    716 if_initialize(ifnet_t *ifp)
    717 {
    718 	char xnamebuf[HOOKNAMSIZ];
    719 
    720 	KASSERT(if_indexlim > 0);
    721 	TAILQ_INIT(&ifp->if_addrlist);
    722 
    723 	/*
    724 	 * Link level name is allocated later by a separate call to
    725 	 * if_alloc_sadl().
    726 	 */
    727 
    728 	if (ifp->if_snd.ifq_maxlen == 0)
    729 		ifp->if_snd.ifq_maxlen = ifqmaxlen;
    730 
    731 	ifp->if_broadcastaddr = 0; /* reliably crash if used uninitialized */
    732 
    733 	ifp->if_link_state = LINK_STATE_UNKNOWN;
    734 	ifp->if_link_queue = 0;
    735 
    736 	ifp->if_capenable = 0;
    737 	ifp->if_csum_flags_tx = 0;
    738 	ifp->if_csum_flags_rx = 0;
    739 
    740 #ifdef ALTQ
    741 	ifp->if_snd.altq_type = 0;
    742 	ifp->if_snd.altq_disc = NULL;
    743 	ifp->if_snd.altq_flags &= ALTQF_CANTCHANGE;
    744 	ifp->if_snd.altq_tbr  = NULL;
    745 	ifp->if_snd.altq_ifp  = ifp;
    746 #endif
    747 
    748 	IFQ_LOCK_INIT(&ifp->if_snd);
    749 
    750 	ifp->if_pfil = pfil_head_create(PFIL_TYPE_IFNET, ifp);
    751 	pfil_run_ifhooks(if_pfil, PFIL_IFNET_ATTACH, ifp);
    752 
    753 	IF_AFDATA_LOCK_INIT(ifp);
    754 
    755 	PSLIST_ENTRY_INIT(ifp, if_pslist_entry);
    756 	PSLIST_INIT(&ifp->if_addr_pslist);
    757 	psref_target_init(&ifp->if_psref, ifnet_psref_class);
    758 	ifp->if_ioctl_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    759 	LIST_INIT(&ifp->if_multiaddrs);
    760 	if_stats_init(ifp);
    761 
    762 	snprintf(xnamebuf, sizeof(xnamebuf), "%s-lshk", ifp->if_xname);
    763 	ifp->if_linkstate_hooks = simplehook_create(IPL_NET, xnamebuf);
    764 
    765 	IFNET_GLOBAL_LOCK();
    766 	if_getindex(ifp);
    767 	IFNET_GLOBAL_UNLOCK();
    768 }
    769 
    770 /*
    771  * Register an interface to the list of "active" interfaces.
    772  */
    773 void
    774 if_register(ifnet_t *ifp)
    775 {
    776 	/*
    777 	 * If the driver has not supplied its own if_ioctl or if_stop,
    778 	 * then supply the default.
    779 	 */
    780 	if (ifp->if_ioctl == NULL)
    781 		ifp->if_ioctl = ifioctl_common;
    782 	if (ifp->if_stop == NULL)
    783 		ifp->if_stop = if_nullstop;
    784 
    785 	sysctl_sndq_setup(&ifp->if_sysctl_log, ifp->if_xname, &ifp->if_snd);
    786 
    787 	if (!STAILQ_EMPTY(&domains))
    788 		if_attachdomain1(ifp);
    789 
    790 	/* Announce the interface. */
    791 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
    792 
    793 	if (ifp->if_slowtimo != NULL) {
    794 		struct if_slowtimo_data *isd;
    795 
    796 		isd = kmem_zalloc(sizeof(*isd), KM_SLEEP);
    797 		mutex_init(&isd->isd_lock, MUTEX_DEFAULT, IPL_SOFTCLOCK);
    798 		callout_init(&isd->isd_ch, CALLOUT_MPSAFE);
    799 		callout_setfunc(&isd->isd_ch, if_slowtimo_intr, ifp);
    800 		isd->isd_ifp = ifp;
    801 
    802 		ifp->if_slowtimo_data = isd;
    803 
    804 		if_slowtimo_intr(ifp);
    805 
    806 		sysctl_watchdog_setup(ifp);
    807 	}
    808 
    809 	if (ifp->if_transmit == NULL || ifp->if_transmit == if_nulltransmit)
    810 		ifp->if_transmit = if_transmit;
    811 
    812 	IFNET_GLOBAL_LOCK();
    813 	TAILQ_INSERT_TAIL(&ifnet_list, ifp, if_list);
    814 	IFNET_WRITER_INSERT_TAIL(ifp);
    815 	IFNET_GLOBAL_UNLOCK();
    816 }
    817 
    818 /*
    819  * The if_percpuq framework
    820  *
    821  * It allows network device drivers to execute the network stack
    822  * in softint (so called softint-based if_input). It utilizes
    823  * softint and percpu ifqueue. It doesn't distribute any packets
    824  * between CPUs, unlike pktqueue(9).
    825  *
    826  * Currently we support two options for device drivers to apply the framework:
    827  * - Use it implicitly with less changes
    828  *   - If you use if_attach in driver's _attach function and if_input in
    829  *     driver's Rx interrupt handler, a packet is queued and a softint handles
    830  *     the packet implicitly
    831  * - Use it explicitly in each driver (recommended)
    832  *   - You can use if_percpuq_* directly in your driver
    833  *   - In this case, you need to allocate struct if_percpuq in driver's softc
    834  *   - See wm(4) as a reference implementation
    835  */
    836 
    837 static void
    838 if_percpuq_softint(void *arg)
    839 {
    840 	struct if_percpuq *ipq = arg;
    841 	struct ifnet *ifp = ipq->ipq_ifp;
    842 	struct mbuf *m;
    843 
    844 	while ((m = if_percpuq_dequeue(ipq)) != NULL) {
    845 		if_statinc(ifp, if_ipackets);
    846 		bpf_mtap(ifp, m, BPF_D_IN);
    847 
    848 		ifp->_if_input(ifp, m);
    849 	}
    850 }
    851 
    852 static void
    853 if_percpuq_init_ifq(void *p, void *arg __unused, struct cpu_info *ci __unused)
    854 {
    855 	struct ifqueue *const ifq = p;
    856 
    857 	memset(ifq, 0, sizeof(*ifq));
    858 	ifq->ifq_maxlen = IFQ_MAXLEN;
    859 }
    860 
    861 struct if_percpuq *
    862 if_percpuq_create(struct ifnet *ifp)
    863 {
    864 	struct if_percpuq *ipq;
    865 	u_int flags = SOFTINT_NET;
    866 
    867 	flags |= if_is_mpsafe(ifp) ? SOFTINT_MPSAFE : 0;
    868 
    869 	ipq = kmem_zalloc(sizeof(*ipq), KM_SLEEP);
    870 	ipq->ipq_ifp = ifp;
    871 	ipq->ipq_si = softint_establish(flags, if_percpuq_softint, ipq);
    872 	ipq->ipq_ifqs = percpu_alloc(sizeof(struct ifqueue));
    873 	percpu_foreach(ipq->ipq_ifqs, &if_percpuq_init_ifq, NULL);
    874 
    875 	sysctl_percpuq_setup(&ifp->if_sysctl_log, ifp->if_xname, ipq);
    876 
    877 	return ipq;
    878 }
    879 
    880 static struct mbuf *
    881 if_percpuq_dequeue(struct if_percpuq *ipq)
    882 {
    883 	struct mbuf *m;
    884 	struct ifqueue *ifq;
    885 
    886 	const int s = splnet();
    887 	ifq = percpu_getref(ipq->ipq_ifqs);
    888 	IF_DEQUEUE(ifq, m);
    889 	percpu_putref(ipq->ipq_ifqs);
    890 	splx(s);
    891 
    892 	return m;
    893 }
    894 
    895 static void
    896 if_percpuq_purge_ifq(void *p, void *arg __unused, struct cpu_info *ci __unused)
    897 {
    898 	struct ifqueue *const ifq = p;
    899 
    900 	IF_PURGE(ifq);
    901 }
    902 
    903 void
    904 if_percpuq_destroy(struct if_percpuq *ipq)
    905 {
    906 
    907 	/* if_detach may already destroy it */
    908 	if (ipq == NULL)
    909 		return;
    910 
    911 	softint_disestablish(ipq->ipq_si);
    912 	percpu_foreach(ipq->ipq_ifqs, &if_percpuq_purge_ifq, NULL);
    913 	percpu_free(ipq->ipq_ifqs, sizeof(struct ifqueue));
    914 	kmem_free(ipq, sizeof(*ipq));
    915 }
    916 
    917 void
    918 if_percpuq_enqueue(struct if_percpuq *ipq, struct mbuf *m)
    919 {
    920 	struct ifqueue *ifq;
    921 
    922 	KASSERT(ipq != NULL);
    923 
    924 	const int s = splnet();
    925 	ifq = percpu_getref(ipq->ipq_ifqs);
    926 	if (IF_QFULL(ifq)) {
    927 		IF_DROP(ifq);
    928 		percpu_putref(ipq->ipq_ifqs);
    929 		if_statinc(ipq->ipq_ifp, if_iqdrops);
    930 		m_freem(m);
    931 		goto out;
    932 	}
    933 	IF_ENQUEUE(ifq, m);
    934 	percpu_putref(ipq->ipq_ifqs);
    935 
    936 	softint_schedule(ipq->ipq_si);
    937 out:
    938 	splx(s);
    939 }
    940 
    941 static void
    942 if_percpuq_drops(void *p, void *arg, struct cpu_info *ci __unused)
    943 {
    944 	struct ifqueue *const ifq = p;
    945 	uint64_t *sum = arg;
    946 
    947 	*sum += ifq->ifq_drops;
    948 }
    949 
    950 static int
    951 sysctl_percpuq_drops_handler(SYSCTLFN_ARGS)
    952 {
    953 	struct sysctlnode node;
    954 	struct if_percpuq *ipq;
    955 	uint64_t sum = 0;
    956 	int error;
    957 
    958 	node = *rnode;
    959 	ipq = node.sysctl_data;
    960 
    961 	percpu_foreach(ipq->ipq_ifqs, if_percpuq_drops, &sum);
    962 
    963 	node.sysctl_data = &sum;
    964 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    965 	if (error != 0 || newp == NULL)
    966 		return error;
    967 
    968 	return 0;
    969 }
    970 
    971 static void
    972 sysctl_percpuq_setup(struct sysctllog **clog, const char* ifname,
    973     struct if_percpuq *ipq)
    974 {
    975 	const struct sysctlnode *cnode, *rnode;
    976 
    977 	if (sysctl_createv(clog, 0, NULL, &rnode,
    978 		       CTLFLAG_PERMANENT,
    979 		       CTLTYPE_NODE, "interfaces",
    980 		       SYSCTL_DESCR("Per-interface controls"),
    981 		       NULL, 0, NULL, 0,
    982 		       CTL_NET, CTL_CREATE, CTL_EOL) != 0)
    983 		goto bad;
    984 
    985 	if (sysctl_createv(clog, 0, &rnode, &rnode,
    986 		       CTLFLAG_PERMANENT,
    987 		       CTLTYPE_NODE, ifname,
    988 		       SYSCTL_DESCR("Interface controls"),
    989 		       NULL, 0, NULL, 0,
    990 		       CTL_CREATE, CTL_EOL) != 0)
    991 		goto bad;
    992 
    993 	if (sysctl_createv(clog, 0, &rnode, &rnode,
    994 		       CTLFLAG_PERMANENT,
    995 		       CTLTYPE_NODE, "rcvq",
    996 		       SYSCTL_DESCR("Interface input queue controls"),
    997 		       NULL, 0, NULL, 0,
    998 		       CTL_CREATE, CTL_EOL) != 0)
    999 		goto bad;
   1000 
   1001 #ifdef NOTYET
   1002 	/* XXX Should show each per-CPU queue length? */
   1003 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   1004 		       CTLFLAG_PERMANENT,
   1005 		       CTLTYPE_INT, "len",
   1006 		       SYSCTL_DESCR("Current input queue length"),
   1007 		       sysctl_percpuq_len, 0, NULL, 0,
   1008 		       CTL_CREATE, CTL_EOL) != 0)
   1009 		goto bad;
   1010 
   1011 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   1012 		       CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1013 		       CTLTYPE_INT, "maxlen",
   1014 		       SYSCTL_DESCR("Maximum allowed input queue length"),
   1015 		       sysctl_percpuq_maxlen_handler, 0, (void *)ipq, 0,
   1016 		       CTL_CREATE, CTL_EOL) != 0)
   1017 		goto bad;
   1018 #endif
   1019 
   1020 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   1021 		       CTLFLAG_PERMANENT,
   1022 		       CTLTYPE_QUAD, "drops",
   1023 		       SYSCTL_DESCR("Total packets dropped due to full input queue"),
   1024 		       sysctl_percpuq_drops_handler, 0, (void *)ipq, 0,
   1025 		       CTL_CREATE, CTL_EOL) != 0)
   1026 		goto bad;
   1027 
   1028 	return;
   1029 bad:
   1030 	printf("%s: could not attach sysctl nodes\n", ifname);
   1031 	return;
   1032 }
   1033 
   1034 /*
   1035  * The deferred if_start framework
   1036  *
   1037  * The common APIs to defer if_start to softint when if_start is requested
   1038  * from a device driver running in hardware interrupt context.
   1039  */
   1040 /*
   1041  * Call ifp->if_start (or equivalent) in a dedicated softint for
   1042  * deferred if_start.
   1043  */
   1044 static void
   1045 if_deferred_start_softint(void *arg)
   1046 {
   1047 	struct if_deferred_start *ids = arg;
   1048 	struct ifnet *ifp = ids->ids_ifp;
   1049 
   1050 	ids->ids_if_start(ifp);
   1051 }
   1052 
   1053 /*
   1054  * The default callback function for deferred if_start.
   1055  */
   1056 static void
   1057 if_deferred_start_common(struct ifnet *ifp)
   1058 {
   1059 	const int s = splnet();
   1060 	if_start_lock(ifp);
   1061 	splx(s);
   1062 }
   1063 
   1064 static inline bool
   1065 if_snd_is_used(struct ifnet *ifp)
   1066 {
   1067 
   1068 	return ALTQ_IS_ENABLED(&ifp->if_snd) ||
   1069 	    ifp->if_transmit == if_transmit ||
   1070 	    ifp->if_transmit == NULL ||
   1071 	    ifp->if_transmit == if_nulltransmit;
   1072 }
   1073 
   1074 /*
   1075  * Schedule deferred if_start.
   1076  */
   1077 void
   1078 if_schedule_deferred_start(struct ifnet *ifp)
   1079 {
   1080 
   1081 	KASSERT(ifp->if_deferred_start != NULL);
   1082 
   1083 	if (if_snd_is_used(ifp) && IFQ_IS_EMPTY(&ifp->if_snd))
   1084 		return;
   1085 
   1086 	softint_schedule(ifp->if_deferred_start->ids_si);
   1087 }
   1088 
   1089 /*
   1090  * Create an instance of deferred if_start. A driver should call the function
   1091  * only if the driver needs deferred if_start. Drivers can setup their own
   1092  * deferred if_start function via 2nd argument.
   1093  */
   1094 void
   1095 if_deferred_start_init(struct ifnet *ifp, void (*func)(struct ifnet *))
   1096 {
   1097 	struct if_deferred_start *ids;
   1098 	u_int flags = SOFTINT_NET;
   1099 
   1100 	flags |= if_is_mpsafe(ifp) ? SOFTINT_MPSAFE : 0;
   1101 
   1102 	ids = kmem_zalloc(sizeof(*ids), KM_SLEEP);
   1103 	ids->ids_ifp = ifp;
   1104 	ids->ids_si = softint_establish(flags, if_deferred_start_softint, ids);
   1105 	if (func != NULL)
   1106 		ids->ids_if_start = func;
   1107 	else
   1108 		ids->ids_if_start = if_deferred_start_common;
   1109 
   1110 	ifp->if_deferred_start = ids;
   1111 }
   1112 
   1113 static void
   1114 if_deferred_start_destroy(struct ifnet *ifp)
   1115 {
   1116 
   1117 	if (ifp->if_deferred_start == NULL)
   1118 		return;
   1119 
   1120 	softint_disestablish(ifp->if_deferred_start->ids_si);
   1121 	kmem_free(ifp->if_deferred_start, sizeof(*ifp->if_deferred_start));
   1122 	ifp->if_deferred_start = NULL;
   1123 }
   1124 
   1125 /*
   1126  * The common interface input routine that is called by device drivers,
   1127  * which should be used only when the driver's rx handler already runs
   1128  * in softint.
   1129  */
   1130 void
   1131 if_input(struct ifnet *ifp, struct mbuf *m)
   1132 {
   1133 
   1134 	KASSERT(ifp->if_percpuq == NULL);
   1135 	KASSERT(!cpu_intr_p());
   1136 
   1137 	if_statinc(ifp, if_ipackets);
   1138 	bpf_mtap(ifp, m, BPF_D_IN);
   1139 
   1140 	ifp->_if_input(ifp, m);
   1141 }
   1142 
   1143 /*
   1144  * DEPRECATED. Use if_initialize and if_register instead.
   1145  * See the above comment of if_initialize.
   1146  *
   1147  * Note that it implicitly enables if_percpuq to make drivers easy to
   1148  * migrate softint-based if_input without much changes. If you don't
   1149  * want to enable it, use if_initialize instead.
   1150  */
   1151 void
   1152 if_attach(ifnet_t *ifp)
   1153 {
   1154 
   1155 	if_initialize(ifp);
   1156 	ifp->if_percpuq = if_percpuq_create(ifp);
   1157 	if_register(ifp);
   1158 }
   1159 
   1160 void
   1161 if_attachdomain(void)
   1162 {
   1163 	struct ifnet *ifp;
   1164 	const int bound = curlwp_bind();
   1165 
   1166 	int s = pserialize_read_enter();
   1167 	IFNET_READER_FOREACH(ifp) {
   1168 		struct psref psref;
   1169 		psref_acquire(&psref, &ifp->if_psref, ifnet_psref_class);
   1170 		pserialize_read_exit(s);
   1171 		if_attachdomain1(ifp);
   1172 		s = pserialize_read_enter();
   1173 		psref_release(&psref, &ifp->if_psref, ifnet_psref_class);
   1174 	}
   1175 	pserialize_read_exit(s);
   1176 	curlwp_bindx(bound);
   1177 }
   1178 
   1179 static void
   1180 if_attachdomain1(struct ifnet *ifp)
   1181 {
   1182 	struct domain *dp;
   1183 	const int s = splsoftnet();
   1184 
   1185 	/* address family dependent data region */
   1186 	memset(ifp->if_afdata, 0, sizeof(ifp->if_afdata));
   1187 	DOMAIN_FOREACH(dp) {
   1188 		if (dp->dom_ifattach != NULL)
   1189 			ifp->if_afdata[dp->dom_family] =
   1190 			    (*dp->dom_ifattach)(ifp);
   1191 	}
   1192 
   1193 	splx(s);
   1194 }
   1195 
   1196 /*
   1197  * Deactivate an interface.  This points all of the procedure
   1198  * handles at error stubs.  May be called from interrupt context.
   1199  */
   1200 void
   1201 if_deactivate(struct ifnet *ifp)
   1202 {
   1203 	const int s = splsoftnet();
   1204 
   1205 	ifp->if_output	 = if_nulloutput;
   1206 	ifp->_if_input	 = if_nullinput;
   1207 	ifp->if_start	 = if_nullstart;
   1208 	ifp->if_transmit = if_nulltransmit;
   1209 	ifp->if_ioctl	 = if_nullioctl;
   1210 	ifp->if_init	 = if_nullinit;
   1211 	ifp->if_stop	 = if_nullstop;
   1212 	if (ifp->if_slowtimo)
   1213 		ifp->if_slowtimo = if_nullslowtimo;
   1214 	ifp->if_drain	 = if_nulldrain;
   1215 
   1216 	/* No more packets may be enqueued. */
   1217 	ifp->if_snd.ifq_maxlen = 0;
   1218 
   1219 	splx(s);
   1220 }
   1221 
   1222 bool
   1223 if_is_deactivated(const struct ifnet *ifp)
   1224 {
   1225 
   1226 	return ifp->if_output == if_nulloutput;
   1227 }
   1228 
   1229 void
   1230 if_purgeaddrs(struct ifnet *ifp, int family,
   1231     void (*purgeaddr)(struct ifaddr *))
   1232 {
   1233 	struct ifaddr *ifa, *nifa;
   1234 	int s;
   1235 
   1236 	s = pserialize_read_enter();
   1237 	for (ifa = IFADDR_READER_FIRST(ifp); ifa; ifa = nifa) {
   1238 		nifa = IFADDR_READER_NEXT(ifa);
   1239 		if (ifa->ifa_addr->sa_family != family)
   1240 			continue;
   1241 		pserialize_read_exit(s);
   1242 
   1243 		(*purgeaddr)(ifa);
   1244 
   1245 		s = pserialize_read_enter();
   1246 	}
   1247 	pserialize_read_exit(s);
   1248 }
   1249 
   1250 #ifdef IFAREF_DEBUG
   1251 static struct ifaddr **ifa_list;
   1252 static int ifa_list_size;
   1253 
   1254 /* Depends on only one if_attach runs at once */
   1255 static void
   1256 if_build_ifa_list(struct ifnet *ifp)
   1257 {
   1258 	struct ifaddr *ifa;
   1259 	int i;
   1260 
   1261 	KASSERT(ifa_list == NULL);
   1262 	KASSERT(ifa_list_size == 0);
   1263 
   1264 	IFADDR_READER_FOREACH(ifa, ifp)
   1265 		ifa_list_size++;
   1266 
   1267 	ifa_list = kmem_alloc(sizeof(*ifa) * ifa_list_size, KM_SLEEP);
   1268 	i = 0;
   1269 	IFADDR_READER_FOREACH(ifa, ifp) {
   1270 		ifa_list[i++] = ifa;
   1271 		ifaref(ifa);
   1272 	}
   1273 }
   1274 
   1275 static void
   1276 if_check_and_free_ifa_list(struct ifnet *ifp)
   1277 {
   1278 	int i;
   1279 	struct ifaddr *ifa;
   1280 
   1281 	if (ifa_list == NULL)
   1282 		return;
   1283 
   1284 	for (i = 0; i < ifa_list_size; i++) {
   1285 		char buf[64];
   1286 
   1287 		ifa = ifa_list[i];
   1288 		sockaddr_format(ifa->ifa_addr, buf, sizeof(buf));
   1289 		if (ifa->ifa_refcnt > 1) {
   1290 			log(LOG_WARNING,
   1291 			    "ifa(%s) still referenced (refcnt=%d)\n",
   1292 			    buf, ifa->ifa_refcnt - 1);
   1293 		} else
   1294 			log(LOG_DEBUG,
   1295 			    "ifa(%s) not referenced (refcnt=%d)\n",
   1296 			    buf, ifa->ifa_refcnt - 1);
   1297 		ifafree(ifa);
   1298 	}
   1299 
   1300 	kmem_free(ifa_list, sizeof(*ifa) * ifa_list_size);
   1301 	ifa_list = NULL;
   1302 	ifa_list_size = 0;
   1303 }
   1304 #endif
   1305 
   1306 /*
   1307  * Detach an interface from the list of "active" interfaces,
   1308  * freeing any resources as we go along.
   1309  *
   1310  * NOTE: This routine must be called with a valid thread context,
   1311  * as it may block.
   1312  */
   1313 void
   1314 if_detach(struct ifnet *ifp)
   1315 {
   1316 	struct socket so;
   1317 	struct ifaddr *ifa;
   1318 #ifdef IFAREF_DEBUG
   1319 	struct ifaddr *last_ifa = NULL;
   1320 #endif
   1321 	struct domain *dp;
   1322 	const struct protosw *pr;
   1323 	int i, family, purged;
   1324 
   1325 #ifdef IFAREF_DEBUG
   1326 	if_build_ifa_list(ifp);
   1327 #endif
   1328 	/*
   1329 	 * XXX It's kind of lame that we have to have the
   1330 	 * XXX socket structure...
   1331 	 */
   1332 	memset(&so, 0, sizeof(so));
   1333 
   1334 	const int s = splnet();
   1335 
   1336 	sysctl_teardown(&ifp->if_sysctl_log);
   1337 
   1338 	IFNET_LOCK(ifp);
   1339 
   1340 	/*
   1341 	 * Lock the link queue.
   1342 	 * This stops any more link state changes occurring for this
   1343 	 * interface while it's being detached so it's safe
   1344 	 * to drain the workqueue.
   1345 	 */
   1346 	IF_LINK_STATE_CHANGE_LOCK(ifp);
   1347 	ifp->if_link_queue = LINK_QUEUE_LOCKED;
   1348 	IF_LINK_STATE_CHANGE_UNLOCK(ifp);
   1349 	workqueue_wait(ifnet_link_state_wq, &ifp->if_link_work);
   1350 
   1351 	if_deactivate(ifp);
   1352 	IFNET_UNLOCK(ifp);
   1353 
   1354 	/*
   1355 	 * Unlink from the list and wait for all readers to leave
   1356 	 * from pserialize read sections.  Note that we can't do
   1357 	 * psref_target_destroy here.  See below.
   1358 	 */
   1359 	IFNET_GLOBAL_LOCK();
   1360 	ifindex2ifnet[ifp->if_index] = NULL;
   1361 	TAILQ_REMOVE(&ifnet_list, ifp, if_list);
   1362 	IFNET_WRITER_REMOVE(ifp);
   1363 	pserialize_perform(ifnet_psz);
   1364 	IFNET_GLOBAL_UNLOCK();
   1365 
   1366 	if (ifp->if_slowtimo != NULL) {
   1367 		struct if_slowtimo_data *isd = ifp->if_slowtimo_data;
   1368 
   1369 		mutex_enter(&isd->isd_lock);
   1370 		isd->isd_dying = true;
   1371 		mutex_exit(&isd->isd_lock);
   1372 		callout_halt(&isd->isd_ch, NULL);
   1373 		workqueue_wait(if_slowtimo_wq, &isd->isd_work);
   1374 		callout_destroy(&isd->isd_ch);
   1375 		mutex_destroy(&isd->isd_lock);
   1376 		kmem_free(isd, sizeof(*isd));
   1377 
   1378 		ifp->if_slowtimo_data = NULL; /* paraonia */
   1379 		ifp->if_slowtimo = NULL;      /* paranoia */
   1380 	}
   1381 	if_deferred_start_destroy(ifp);
   1382 
   1383 	/*
   1384 	 * Do an if_down() to give protocols a chance to do something.
   1385 	 */
   1386 	if_down_deactivated(ifp);
   1387 
   1388 #ifdef ALTQ
   1389 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
   1390 		altq_disable(&ifp->if_snd);
   1391 	if (ALTQ_IS_ATTACHED(&ifp->if_snd))
   1392 		altq_detach(&ifp->if_snd);
   1393 #endif
   1394 
   1395 #if NCARP > 0
   1396 	/* Remove the interface from any carp group it is a part of.  */
   1397 	if (ifp->if_carp != NULL && ifp->if_type != IFT_CARP)
   1398 		carp_ifdetach(ifp);
   1399 #endif
   1400 
   1401 	/*
   1402 	 * Ensure that all packets on protocol input pktqueues have been
   1403 	 * processed, or, at least, removed from the queues.
   1404 	 *
   1405 	 * A cross-call will ensure that the interrupts have completed.
   1406 	 * FIXME: not quite..
   1407 	 */
   1408 	pktq_ifdetach();
   1409 	xc_barrier(0);
   1410 
   1411 	/*
   1412 	 * Rip all the addresses off the interface.  This should make
   1413 	 * all of the routes go away.
   1414 	 *
   1415 	 * pr_usrreq calls can remove an arbitrary number of ifaddrs
   1416 	 * from the list, including our "cursor", ifa.  For safety,
   1417 	 * and to honor the TAILQ abstraction, I just restart the
   1418 	 * loop after each removal.  Note that the loop will exit
   1419 	 * when all of the remaining ifaddrs belong to the AF_LINK
   1420 	 * family.  I am counting on the historical fact that at
   1421 	 * least one pr_usrreq in each address domain removes at
   1422 	 * least one ifaddr.
   1423 	 */
   1424 again:
   1425 	/*
   1426 	 * At this point, no other one tries to remove ifa in the list,
   1427 	 * so we don't need to take a lock or psref.  Avoid using
   1428 	 * IFADDR_READER_FOREACH to pass over an inspection of contract
   1429 	 * violations of pserialize.
   1430 	 */
   1431 	IFADDR_WRITER_FOREACH(ifa, ifp) {
   1432 		family = ifa->ifa_addr->sa_family;
   1433 #ifdef IFAREF_DEBUG
   1434 		printf("if_detach: ifaddr %p, family %d, refcnt %d\n",
   1435 		    ifa, family, ifa->ifa_refcnt);
   1436 		if (last_ifa != NULL && ifa == last_ifa)
   1437 			panic("if_detach: loop detected");
   1438 		last_ifa = ifa;
   1439 #endif
   1440 		if (family == AF_LINK)
   1441 			continue;
   1442 		dp = pffinddomain(family);
   1443 		KASSERTMSG(dp != NULL, "no domain for AF %d", family);
   1444 		/*
   1445 		 * XXX These PURGEIF calls are redundant with the
   1446 		 * purge-all-families calls below, but are left in for
   1447 		 * now both to make a smaller change, and to avoid
   1448 		 * unplanned interactions with clearing of
   1449 		 * ifp->if_addrlist.
   1450 		 */
   1451 		purged = 0;
   1452 		for (pr = dp->dom_protosw;
   1453 		     pr < dp->dom_protoswNPROTOSW; pr++) {
   1454 			so.so_proto = pr;
   1455 			if (pr->pr_usrreqs) {
   1456 				(void) (*pr->pr_usrreqs->pr_purgeif)(&so, ifp);
   1457 				purged = 1;
   1458 			}
   1459 		}
   1460 		if (purged == 0) {
   1461 			/*
   1462 			 * XXX What's really the best thing to do
   1463 			 * XXX here?  --thorpej (at) NetBSD.org
   1464 			 */
   1465 			printf("if_detach: WARNING: AF %d not purged\n",
   1466 			    family);
   1467 			ifa_remove(ifp, ifa);
   1468 		}
   1469 		goto again;
   1470 	}
   1471 
   1472 	if_free_sadl(ifp, 1);
   1473 
   1474 restart:
   1475 	IFADDR_WRITER_FOREACH(ifa, ifp) {
   1476 		family = ifa->ifa_addr->sa_family;
   1477 		KASSERT(family == AF_LINK);
   1478 		ifa_remove(ifp, ifa);
   1479 		goto restart;
   1480 	}
   1481 
   1482 	/* Delete stray routes from the routing table. */
   1483 	for (i = 0; i <= AF_MAX; i++)
   1484 		rt_delete_matched_entries(i, if_delroute_matcher, ifp, false);
   1485 
   1486 	DOMAIN_FOREACH(dp) {
   1487 		if (dp->dom_ifdetach != NULL && ifp->if_afdata[dp->dom_family])
   1488 		{
   1489 			void *p = ifp->if_afdata[dp->dom_family];
   1490 			if (p) {
   1491 				ifp->if_afdata[dp->dom_family] = NULL;
   1492 				(*dp->dom_ifdetach)(ifp, p);
   1493 			}
   1494 		}
   1495 
   1496 		/*
   1497 		 * One would expect multicast memberships (INET and
   1498 		 * INET6) on UDP sockets to be purged by the PURGEIF
   1499 		 * calls above, but if all addresses were removed from
   1500 		 * the interface prior to destruction, the calls will
   1501 		 * not be made (e.g. ppp, for which pppd(8) generally
   1502 		 * removes addresses before destroying the interface).
   1503 		 * Because there is no invariant that multicast
   1504 		 * memberships only exist for interfaces with IPv4
   1505 		 * addresses, we must call PURGEIF regardless of
   1506 		 * addresses.  (Protocols which might store ifnet
   1507 		 * pointers are marked with PR_PURGEIF.)
   1508 		 */
   1509 		for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++)
   1510 		{
   1511 			so.so_proto = pr;
   1512 			if (pr->pr_usrreqs && pr->pr_flags & PR_PURGEIF)
   1513 				(void)(*pr->pr_usrreqs->pr_purgeif)(&so, ifp);
   1514 		}
   1515 	}
   1516 
   1517 	/*
   1518 	 * Must be done after the above pr_purgeif because if_psref may be
   1519 	 * still used in pr_purgeif.
   1520 	 */
   1521 	psref_target_destroy(&ifp->if_psref, ifnet_psref_class);
   1522 	PSLIST_ENTRY_DESTROY(ifp, if_pslist_entry);
   1523 
   1524 	pfil_run_ifhooks(if_pfil, PFIL_IFNET_DETACH, ifp);
   1525 	(void)pfil_head_destroy(ifp->if_pfil);
   1526 
   1527 	/* Announce that the interface is gone. */
   1528 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
   1529 
   1530 	IF_AFDATA_LOCK_DESTROY(ifp);
   1531 
   1532 	if (ifp->if_percpuq != NULL) {
   1533 		if_percpuq_destroy(ifp->if_percpuq);
   1534 		ifp->if_percpuq = NULL;
   1535 	}
   1536 
   1537 	mutex_obj_free(ifp->if_ioctl_lock);
   1538 	ifp->if_ioctl_lock = NULL;
   1539 	mutex_obj_free(ifp->if_snd.ifq_lock);
   1540 	if_stats_fini(ifp);
   1541 	KASSERT(!simplehook_has_hooks(ifp->if_linkstate_hooks));
   1542 	simplehook_destroy(ifp->if_linkstate_hooks);
   1543 
   1544 	splx(s);
   1545 
   1546 #ifdef IFAREF_DEBUG
   1547 	if_check_and_free_ifa_list(ifp);
   1548 #endif
   1549 }
   1550 
   1551 /*
   1552  * Callback for a radix tree walk to delete all references to an
   1553  * ifnet.
   1554  */
   1555 static int
   1556 if_delroute_matcher(struct rtentry *rt, void *v)
   1557 {
   1558 	struct ifnet *ifp = (struct ifnet *)v;
   1559 
   1560 	if (rt->rt_ifp == ifp)
   1561 		return 1;
   1562 	else
   1563 		return 0;
   1564 }
   1565 
   1566 /*
   1567  * Create a clone network interface.
   1568  */
   1569 static int
   1570 if_clone_create(const char *name)
   1571 {
   1572 	struct if_clone *ifc;
   1573 	struct ifnet *ifp;
   1574 	struct psref psref;
   1575 	int unit;
   1576 
   1577 	KASSERT(mutex_owned(&if_clone_mtx));
   1578 
   1579 	ifc = if_clone_lookup(name, &unit);
   1580 	if (ifc == NULL)
   1581 		return EINVAL;
   1582 
   1583 	ifp = if_get(name, &psref);
   1584 	if (ifp != NULL) {
   1585 		if_put(ifp, &psref);
   1586 		return EEXIST;
   1587 	}
   1588 
   1589 	return (*ifc->ifc_create)(ifc, unit);
   1590 }
   1591 
   1592 /*
   1593  * Destroy a clone network interface.
   1594  */
   1595 static int
   1596 if_clone_destroy(const char *name)
   1597 {
   1598 	struct if_clone *ifc;
   1599 	struct ifnet *ifp;
   1600 	struct psref psref;
   1601 	int error;
   1602 	int (*if_ioctlfn)(struct ifnet *, u_long, void *);
   1603 
   1604 	KASSERT(mutex_owned(&if_clone_mtx));
   1605 
   1606 	ifc = if_clone_lookup(name, NULL);
   1607 	if (ifc == NULL)
   1608 		return EINVAL;
   1609 
   1610 	if (ifc->ifc_destroy == NULL)
   1611 		return EOPNOTSUPP;
   1612 
   1613 	ifp = if_get(name, &psref);
   1614 	if (ifp == NULL)
   1615 		return ENXIO;
   1616 
   1617 	/* We have to disable ioctls here */
   1618 	IFNET_LOCK(ifp);
   1619 	if_ioctlfn = ifp->if_ioctl;
   1620 	ifp->if_ioctl = if_nullioctl;
   1621 	IFNET_UNLOCK(ifp);
   1622 
   1623 	/*
   1624 	 * We cannot call ifc_destroy with holding ifp.
   1625 	 * Releasing ifp here is safe thanks to if_clone_mtx.
   1626 	 */
   1627 	if_put(ifp, &psref);
   1628 
   1629 	error = (*ifc->ifc_destroy)(ifp);
   1630 
   1631 	if (error != 0) {
   1632 		/* We have to restore if_ioctl on error */
   1633 		IFNET_LOCK(ifp);
   1634 		ifp->if_ioctl = if_ioctlfn;
   1635 		IFNET_UNLOCK(ifp);
   1636 	}
   1637 
   1638 	return error;
   1639 }
   1640 
   1641 static bool
   1642 if_is_unit(const char *name)
   1643 {
   1644 
   1645 	while (*name != '\0') {
   1646 		if (*name < '0' || *name > '9')
   1647 			return false;
   1648 		name++;
   1649 	}
   1650 
   1651 	return true;
   1652 }
   1653 
   1654 /*
   1655  * Look up a network interface cloner.
   1656  */
   1657 static struct if_clone *
   1658 if_clone_lookup(const char *name, int *unitp)
   1659 {
   1660 	struct if_clone *ifc;
   1661 	const char *cp;
   1662 	char *dp, ifname[IFNAMSIZ + 3];
   1663 	int unit;
   1664 
   1665 	KASSERT(mutex_owned(&if_clone_mtx));
   1666 
   1667 	strcpy(ifname, "if_");
   1668 	/* separate interface name from unit */
   1669 	/* TODO: search unit number from backward */
   1670 	for (dp = ifname + 3, cp = name; cp - name < IFNAMSIZ &&
   1671 	    *cp && !if_is_unit(cp);)
   1672 		*dp++ = *cp++;
   1673 
   1674 	if (cp == name || cp - name == IFNAMSIZ || !*cp)
   1675 		return NULL;	/* No name or unit number */
   1676 	*dp++ = '\0';
   1677 
   1678 again:
   1679 	LIST_FOREACH(ifc, &if_cloners, ifc_list) {
   1680 		if (strcmp(ifname + 3, ifc->ifc_name) == 0)
   1681 			break;
   1682 	}
   1683 
   1684 	if (ifc == NULL) {
   1685 		int error;
   1686 		if (*ifname == '\0')
   1687 			return NULL;
   1688 		mutex_exit(&if_clone_mtx);
   1689 		error = module_autoload(ifname, MODULE_CLASS_DRIVER);
   1690 		mutex_enter(&if_clone_mtx);
   1691 		if (error)
   1692 			return NULL;
   1693 		*ifname = '\0';
   1694 		goto again;
   1695 	}
   1696 
   1697 	unit = 0;
   1698 	while (cp - name < IFNAMSIZ && *cp) {
   1699 		if (*cp < '0' || *cp > '9' || unit >= INT_MAX / 10) {
   1700 			/* Bogus unit number. */
   1701 			return NULL;
   1702 		}
   1703 		unit = (unit * 10) + (*cp++ - '0');
   1704 	}
   1705 
   1706 	if (unitp != NULL)
   1707 		*unitp = unit;
   1708 	return ifc;
   1709 }
   1710 
   1711 /*
   1712  * Register a network interface cloner.
   1713  */
   1714 void
   1715 if_clone_attach(struct if_clone *ifc)
   1716 {
   1717 
   1718 	mutex_enter(&if_clone_mtx);
   1719 	LIST_INSERT_HEAD(&if_cloners, ifc, ifc_list);
   1720 	if_cloners_count++;
   1721 	mutex_exit(&if_clone_mtx);
   1722 }
   1723 
   1724 /*
   1725  * Unregister a network interface cloner.
   1726  */
   1727 void
   1728 if_clone_detach(struct if_clone *ifc)
   1729 {
   1730 
   1731 	mutex_enter(&if_clone_mtx);
   1732 	LIST_REMOVE(ifc, ifc_list);
   1733 	if_cloners_count--;
   1734 	mutex_exit(&if_clone_mtx);
   1735 }
   1736 
   1737 /*
   1738  * Provide list of interface cloners to userspace.
   1739  */
   1740 int
   1741 if_clone_list(int buf_count, char *buffer, int *total)
   1742 {
   1743 	char outbuf[IFNAMSIZ], *dst;
   1744 	struct if_clone *ifc;
   1745 	int count, error = 0;
   1746 
   1747 	mutex_enter(&if_clone_mtx);
   1748 	*total = if_cloners_count;
   1749 	if ((dst = buffer) == NULL) {
   1750 		/* Just asking how many there are. */
   1751 		goto out;
   1752 	}
   1753 
   1754 	if (buf_count < 0) {
   1755 		error = EINVAL;
   1756 		goto out;
   1757 	}
   1758 
   1759 	count = (if_cloners_count < buf_count) ? if_cloners_count : buf_count;
   1760 
   1761 	for (ifc = LIST_FIRST(&if_cloners); ifc != NULL && count != 0;
   1762 	     ifc = LIST_NEXT(ifc, ifc_list), count--, dst += IFNAMSIZ) {
   1763 		(void)strncpy(outbuf, ifc->ifc_name, sizeof(outbuf));
   1764 		if (outbuf[sizeof(outbuf) - 1] != '\0') {
   1765 			error = ENAMETOOLONG;
   1766 			goto out;
   1767 		}
   1768 		error = copyout(outbuf, dst, sizeof(outbuf));
   1769 		if (error != 0)
   1770 			break;
   1771 	}
   1772 
   1773 out:
   1774 	mutex_exit(&if_clone_mtx);
   1775 	return error;
   1776 }
   1777 
   1778 void
   1779 ifa_psref_init(struct ifaddr *ifa)
   1780 {
   1781 
   1782 	psref_target_init(&ifa->ifa_psref, ifa_psref_class);
   1783 }
   1784 
   1785 void
   1786 ifaref(struct ifaddr *ifa)
   1787 {
   1788 
   1789 	atomic_inc_uint(&ifa->ifa_refcnt);
   1790 }
   1791 
   1792 void
   1793 ifafree(struct ifaddr *ifa)
   1794 {
   1795 	KASSERT(ifa != NULL);
   1796 	KASSERTMSG(ifa->ifa_refcnt > 0, "ifa_refcnt=%d", ifa->ifa_refcnt);
   1797 
   1798 	membar_release();
   1799 	if (atomic_dec_uint_nv(&ifa->ifa_refcnt) != 0)
   1800 		return;
   1801 	membar_acquire();
   1802 	free(ifa, M_IFADDR);
   1803 }
   1804 
   1805 bool
   1806 ifa_is_destroying(struct ifaddr *ifa)
   1807 {
   1808 
   1809 	return ISSET(ifa->ifa_flags, IFA_DESTROYING);
   1810 }
   1811 
   1812 void
   1813 ifa_insert(struct ifnet *ifp, struct ifaddr *ifa)
   1814 {
   1815 
   1816 	ifa->ifa_ifp = ifp;
   1817 
   1818 	/*
   1819 	 * Check MP-safety for IFEF_MPSAFE drivers.
   1820 	 * Check !IFF_RUNNING for initialization routines that normally don't
   1821 	 * take IFNET_LOCK but it's safe because there is no competitor.
   1822 	 * XXX there are false positive cases because IFF_RUNNING can be off on
   1823 	 * if_stop.
   1824 	 */
   1825 	KASSERT(!if_is_mpsafe(ifp) || !ISSET(ifp->if_flags, IFF_RUNNING) ||
   1826 	    IFNET_LOCKED(ifp));
   1827 
   1828 	TAILQ_INSERT_TAIL(&ifp->if_addrlist, ifa, ifa_list);
   1829 	IFADDR_ENTRY_INIT(ifa);
   1830 	IFADDR_WRITER_INSERT_TAIL(ifp, ifa);
   1831 
   1832 	ifaref(ifa);
   1833 }
   1834 
   1835 void
   1836 ifa_remove(struct ifnet *ifp, struct ifaddr *ifa)
   1837 {
   1838 
   1839 	KASSERT(ifa->ifa_ifp == ifp);
   1840 	/*
   1841 	 * Check MP-safety for IFEF_MPSAFE drivers.
   1842 	 * if_is_deactivated indicates ifa_remove is called from if_detach
   1843 	 * where it is safe even if IFNET_LOCK isn't held.
   1844 	 */
   1845 	KASSERT(!if_is_mpsafe(ifp) || if_is_deactivated(ifp) ||
   1846 	    IFNET_LOCKED(ifp));
   1847 
   1848 	TAILQ_REMOVE(&ifp->if_addrlist, ifa, ifa_list);
   1849 	IFADDR_WRITER_REMOVE(ifa);
   1850 #ifdef NET_MPSAFE
   1851 	IFNET_GLOBAL_LOCK();
   1852 	pserialize_perform(ifnet_psz);
   1853 	IFNET_GLOBAL_UNLOCK();
   1854 #endif
   1855 
   1856 #ifdef NET_MPSAFE
   1857 	psref_target_destroy(&ifa->ifa_psref, ifa_psref_class);
   1858 #endif
   1859 	IFADDR_ENTRY_DESTROY(ifa);
   1860 	ifafree(ifa);
   1861 }
   1862 
   1863 void
   1864 ifa_acquire(struct ifaddr *ifa, struct psref *psref)
   1865 {
   1866 
   1867 	PSREF_DEBUG_FILL_RETURN_ADDRESS(psref);
   1868 	psref_acquire(psref, &ifa->ifa_psref, ifa_psref_class);
   1869 }
   1870 
   1871 void
   1872 ifa_release(struct ifaddr *ifa, struct psref *psref)
   1873 {
   1874 
   1875 	if (ifa == NULL)
   1876 		return;
   1877 
   1878 	psref_release(psref, &ifa->ifa_psref, ifa_psref_class);
   1879 }
   1880 
   1881 bool
   1882 ifa_held(struct ifaddr *ifa)
   1883 {
   1884 
   1885 	return psref_held(&ifa->ifa_psref, ifa_psref_class);
   1886 }
   1887 
   1888 static inline int
   1889 equal(const struct sockaddr *sa1, const struct sockaddr *sa2)
   1890 {
   1891 
   1892 	return sockaddr_cmp(sa1, sa2) == 0;
   1893 }
   1894 
   1895 /*
   1896  * Locate an interface based on a complete address.
   1897  */
   1898 /*ARGSUSED*/
   1899 struct ifaddr *
   1900 ifa_ifwithaddr(const struct sockaddr *addr)
   1901 {
   1902 	struct ifnet *ifp;
   1903 	struct ifaddr *ifa;
   1904 
   1905 	IFNET_READER_FOREACH(ifp) {
   1906 		if (if_is_deactivated(ifp))
   1907 			continue;
   1908 		IFADDR_READER_FOREACH(ifa, ifp) {
   1909 			if (ifa->ifa_addr->sa_family != addr->sa_family)
   1910 				continue;
   1911 			if (equal(addr, ifa->ifa_addr))
   1912 				return ifa;
   1913 			if ((ifp->if_flags & IFF_BROADCAST) &&
   1914 			    ifa->ifa_broadaddr &&
   1915 			    /* IP6 doesn't have broadcast */
   1916 			    ifa->ifa_broadaddr->sa_len != 0 &&
   1917 			    equal(ifa->ifa_broadaddr, addr))
   1918 				return ifa;
   1919 		}
   1920 	}
   1921 	return NULL;
   1922 }
   1923 
   1924 struct ifaddr *
   1925 ifa_ifwithaddr_psref(const struct sockaddr *addr, struct psref *psref)
   1926 {
   1927 	struct ifaddr *ifa;
   1928 	int s = pserialize_read_enter();
   1929 
   1930 	ifa = ifa_ifwithaddr(addr);
   1931 	if (ifa != NULL)
   1932 		ifa_acquire(ifa, psref);
   1933 	pserialize_read_exit(s);
   1934 
   1935 	return ifa;
   1936 }
   1937 
   1938 /*
   1939  * Locate the point to point interface with a given destination address.
   1940  */
   1941 /*ARGSUSED*/
   1942 struct ifaddr *
   1943 ifa_ifwithdstaddr(const struct sockaddr *addr)
   1944 {
   1945 	struct ifnet *ifp;
   1946 	struct ifaddr *ifa;
   1947 
   1948 	IFNET_READER_FOREACH(ifp) {
   1949 		if (if_is_deactivated(ifp))
   1950 			continue;
   1951 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
   1952 			continue;
   1953 		IFADDR_READER_FOREACH(ifa, ifp) {
   1954 			if (ifa->ifa_addr->sa_family != addr->sa_family ||
   1955 			    ifa->ifa_dstaddr == NULL)
   1956 				continue;
   1957 			if (equal(addr, ifa->ifa_dstaddr))
   1958 				return ifa;
   1959 		}
   1960 	}
   1961 
   1962 	return NULL;
   1963 }
   1964 
   1965 struct ifaddr *
   1966 ifa_ifwithdstaddr_psref(const struct sockaddr *addr, struct psref *psref)
   1967 {
   1968 	struct ifaddr *ifa;
   1969 	int s;
   1970 
   1971 	s = pserialize_read_enter();
   1972 	ifa = ifa_ifwithdstaddr(addr);
   1973 	if (ifa != NULL)
   1974 		ifa_acquire(ifa, psref);
   1975 	pserialize_read_exit(s);
   1976 
   1977 	return ifa;
   1978 }
   1979 
   1980 /*
   1981  * Find an interface on a specific network.  If many, choice
   1982  * is most specific found.
   1983  */
   1984 struct ifaddr *
   1985 ifa_ifwithnet(const struct sockaddr *addr)
   1986 {
   1987 	struct ifnet *ifp;
   1988 	struct ifaddr *ifa, *ifa_maybe = NULL;
   1989 	const struct sockaddr_dl *sdl;
   1990 	u_int af = addr->sa_family;
   1991 	const char *addr_data = addr->sa_data, *cplim;
   1992 
   1993 	if (af == AF_LINK) {
   1994 		sdl = satocsdl(addr);
   1995 		if (sdl->sdl_index && sdl->sdl_index < if_indexlim &&
   1996 		    ifindex2ifnet[sdl->sdl_index] &&
   1997 		    !if_is_deactivated(ifindex2ifnet[sdl->sdl_index])) {
   1998 			return ifindex2ifnet[sdl->sdl_index]->if_dl;
   1999 		}
   2000 	}
   2001 #ifdef NETATALK
   2002 	if (af == AF_APPLETALK) {
   2003 		const struct sockaddr_at *sat, *sat2;
   2004 		sat = (const struct sockaddr_at *)addr;
   2005 		IFNET_READER_FOREACH(ifp) {
   2006 			if (if_is_deactivated(ifp))
   2007 				continue;
   2008 			ifa = at_ifawithnet((const struct sockaddr_at *)addr,
   2009 			    ifp);
   2010 			if (ifa == NULL)
   2011 				continue;
   2012 			sat2 = (struct sockaddr_at *)ifa->ifa_addr;
   2013 			if (sat2->sat_addr.s_net == sat->sat_addr.s_net)
   2014 				return ifa; /* exact match */
   2015 			if (ifa_maybe == NULL) {
   2016 				/* else keep the if with the right range */
   2017 				ifa_maybe = ifa;
   2018 			}
   2019 		}
   2020 		return ifa_maybe;
   2021 	}
   2022 #endif
   2023 	IFNET_READER_FOREACH(ifp) {
   2024 		if (if_is_deactivated(ifp))
   2025 			continue;
   2026 		IFADDR_READER_FOREACH(ifa, ifp) {
   2027 			const char *cp, *cp2, *cp3;
   2028 
   2029 			if (ifa->ifa_addr->sa_family != af ||
   2030 			    ifa->ifa_netmask == NULL)
   2031  next:				continue;
   2032 			cp = addr_data;
   2033 			cp2 = ifa->ifa_addr->sa_data;
   2034 			cp3 = ifa->ifa_netmask->sa_data;
   2035 			cplim = (const char *)ifa->ifa_netmask +
   2036 			    ifa->ifa_netmask->sa_len;
   2037 			while (cp3 < cplim) {
   2038 				if ((*cp++ ^ *cp2++) & *cp3++) {
   2039 					/* want to continue for() loop */
   2040 					goto next;
   2041 				}
   2042 			}
   2043 			if (ifa_maybe == NULL ||
   2044 			    rt_refines(ifa->ifa_netmask,
   2045 				       ifa_maybe->ifa_netmask))
   2046 				ifa_maybe = ifa;
   2047 		}
   2048 	}
   2049 	return ifa_maybe;
   2050 }
   2051 
   2052 struct ifaddr *
   2053 ifa_ifwithnet_psref(const struct sockaddr *addr, struct psref *psref)
   2054 {
   2055 	struct ifaddr *ifa;
   2056 	int s;
   2057 
   2058 	s = pserialize_read_enter();
   2059 	ifa = ifa_ifwithnet(addr);
   2060 	if (ifa != NULL)
   2061 		ifa_acquire(ifa, psref);
   2062 	pserialize_read_exit(s);
   2063 
   2064 	return ifa;
   2065 }
   2066 
   2067 /*
   2068  * Find the interface of the address.
   2069  */
   2070 struct ifaddr *
   2071 ifa_ifwithladdr(const struct sockaddr *addr)
   2072 {
   2073 	struct ifaddr *ia;
   2074 
   2075 	if ((ia = ifa_ifwithaddr(addr)) || (ia = ifa_ifwithdstaddr(addr)) ||
   2076 	    (ia = ifa_ifwithnet(addr)))
   2077 		return ia;
   2078 	return NULL;
   2079 }
   2080 
   2081 struct ifaddr *
   2082 ifa_ifwithladdr_psref(const struct sockaddr *addr, struct psref *psref)
   2083 {
   2084 	struct ifaddr *ifa;
   2085 	int s;
   2086 
   2087 	s = pserialize_read_enter();
   2088 	ifa = ifa_ifwithladdr(addr);
   2089 	if (ifa != NULL)
   2090 		ifa_acquire(ifa, psref);
   2091 	pserialize_read_exit(s);
   2092 
   2093 	return ifa;
   2094 }
   2095 
   2096 struct ifaddr *
   2097 if_first_addr(const struct ifnet *ifp, const int af)
   2098 {
   2099 	struct ifaddr *ifa = NULL;
   2100 
   2101 	IFADDR_READER_FOREACH(ifa, ifp) {
   2102 		if (ifa->ifa_addr->sa_family == af)
   2103 			break;
   2104 	}
   2105 	return ifa;
   2106 }
   2107 
   2108 struct ifaddr *
   2109 if_first_addr_psref(const struct ifnet *ifp, const int af, struct psref *psref)
   2110 {
   2111 	struct ifaddr *ifa;
   2112 	int s;
   2113 
   2114 	s = pserialize_read_enter();
   2115 	ifa = if_first_addr(ifp, af);
   2116 	if (ifa != NULL)
   2117 		ifa_acquire(ifa, psref);
   2118 	pserialize_read_exit(s);
   2119 
   2120 	return ifa;
   2121 }
   2122 
   2123 /*
   2124  * Find an interface address specific to an interface best matching
   2125  * a given address.
   2126  */
   2127 struct ifaddr *
   2128 ifaof_ifpforaddr(const struct sockaddr *addr, struct ifnet *ifp)
   2129 {
   2130 	struct ifaddr *ifa;
   2131 	const char *cp, *cp2, *cp3;
   2132 	const char *cplim;
   2133 	struct ifaddr *ifa_maybe = 0;
   2134 	u_int af = addr->sa_family;
   2135 
   2136 	if (if_is_deactivated(ifp))
   2137 		return NULL;
   2138 
   2139 	if (af >= AF_MAX)
   2140 		return NULL;
   2141 
   2142 	IFADDR_READER_FOREACH(ifa, ifp) {
   2143 		if (ifa->ifa_addr->sa_family != af)
   2144 			continue;
   2145 		ifa_maybe = ifa;
   2146 		if (ifa->ifa_netmask == NULL) {
   2147 			if (equal(addr, ifa->ifa_addr) ||
   2148 			    (ifa->ifa_dstaddr &&
   2149 			     equal(addr, ifa->ifa_dstaddr)))
   2150 				return ifa;
   2151 			continue;
   2152 		}
   2153 		cp = addr->sa_data;
   2154 		cp2 = ifa->ifa_addr->sa_data;
   2155 		cp3 = ifa->ifa_netmask->sa_data;
   2156 		cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
   2157 		for (; cp3 < cplim; cp3++) {
   2158 			if ((*cp++ ^ *cp2++) & *cp3)
   2159 				break;
   2160 		}
   2161 		if (cp3 == cplim)
   2162 			return ifa;
   2163 	}
   2164 	return ifa_maybe;
   2165 }
   2166 
   2167 struct ifaddr *
   2168 ifaof_ifpforaddr_psref(const struct sockaddr *addr, struct ifnet *ifp,
   2169     struct psref *psref)
   2170 {
   2171 	struct ifaddr *ifa;
   2172 	int s;
   2173 
   2174 	s = pserialize_read_enter();
   2175 	ifa = ifaof_ifpforaddr(addr, ifp);
   2176 	if (ifa != NULL)
   2177 		ifa_acquire(ifa, psref);
   2178 	pserialize_read_exit(s);
   2179 
   2180 	return ifa;
   2181 }
   2182 
   2183 /*
   2184  * Default action when installing a route with a Link Level gateway.
   2185  * Lookup an appropriate real ifa to point to.
   2186  * This should be moved to /sys/net/link.c eventually.
   2187  */
   2188 void
   2189 link_rtrequest(int cmd, struct rtentry *rt, const struct rt_addrinfo *info)
   2190 {
   2191 	struct ifaddr *ifa;
   2192 	const struct sockaddr *dst;
   2193 	struct ifnet *ifp;
   2194 	struct psref psref;
   2195 
   2196 	if (cmd != RTM_ADD || ISSET(info->rti_flags, RTF_DONTCHANGEIFA))
   2197 		return;
   2198 	ifp = rt->rt_ifa->ifa_ifp;
   2199 	dst = rt_getkey(rt);
   2200 	if ((ifa = ifaof_ifpforaddr_psref(dst, ifp, &psref)) != NULL) {
   2201 		rt_replace_ifa(rt, ifa);
   2202 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
   2203 			ifa->ifa_rtrequest(cmd, rt, info);
   2204 		ifa_release(ifa, &psref);
   2205 	}
   2206 }
   2207 
   2208 /*
   2209  * Handle a change in the interface link state and
   2210  * queue notifications.
   2211  */
   2212 void
   2213 if_link_state_change(struct ifnet *ifp, int link_state)
   2214 {
   2215 	uint16_t queue;
   2216 
   2217 	IF_LINK_STATE_CHANGE_LOCK(ifp);
   2218 
   2219 	if (ifp->if_link_queue & LINK_QUEUE_LOCKED)
   2220 		goto out;
   2221 
   2222 	/* If nothing is queued and we are already at the state, do nothing. */
   2223 	if (ifp->if_link_queue == 0 && ifp->if_link_state == link_state)
   2224 		goto out;
   2225 
   2226 	/*
   2227 	 * The logic is simple.
   2228 	 * DOWN will remove any existing states and will be processed first.
   2229 	 * UNKNOWN will remove the UP state and will be processed after DOWN.
   2230 	 * UP will be processed last.
   2231 	 * So if an interface link state flaps fast, userland will be kept in
   2232 	 * sane state with minimal notifications.
   2233 	 */
   2234 	queue = ifp->if_link_queue;
   2235 	switch (link_state) {
   2236 	case LINK_STATE_UNKNOWN:
   2237 		/* cannot be UP */
   2238 		queue &= ~LINK_QUEUE_UP;
   2239 		queue |= LINK_QUEUE_UNKNOWN;
   2240 		break;
   2241 	case LINK_STATE_DOWN:
   2242 		/* cannot be UNKNOWN or UP */
   2243 		queue &= ~(LINK_QUEUE_UNKNOWN | LINK_QUEUE_UP);
   2244 		queue |= LINK_QUEUE_DOWN;
   2245 		break;
   2246 	case LINK_STATE_UP:
   2247 		queue |= LINK_QUEUE_UP;
   2248 		break;
   2249 	default:
   2250 #ifdef DEBUG
   2251 		printf("%s: invalid link state %d\n",
   2252 		    ifp->if_xname, link_state);
   2253 #endif
   2254 		goto out;
   2255 	}
   2256 
   2257 	if (ifp->if_link_queue == queue)
   2258 		goto out;
   2259 
   2260 	ifp->if_link_queue = queue;
   2261 	if (ifp->if_link_queue & LINK_QUEUE_SCHEDULED)
   2262 		goto out;
   2263 
   2264 	ifp->if_link_queue |= LINK_QUEUE_SCHEDULED;
   2265 	workqueue_enqueue(ifnet_link_state_wq, &ifp->if_link_work, NULL);
   2266 
   2267 out:
   2268 	IF_LINK_STATE_CHANGE_UNLOCK(ifp);
   2269 }
   2270 
   2271 /*
   2272  * Handle interface link state change notifications.
   2273  */
   2274 static void
   2275 if_link_state_change_process(struct ifnet *ifp, int link_state)
   2276 {
   2277 	struct domain *dp;
   2278 	const int s = splnet();
   2279 	bool notify;
   2280 
   2281 	KASSERT(!cpu_intr_p());
   2282 
   2283 	IF_LINK_STATE_CHANGE_LOCK(ifp);
   2284 
   2285 	/* Ensure the change is still valid. */
   2286 	if (ifp->if_link_state == link_state) {
   2287 		IF_LINK_STATE_CHANGE_UNLOCK(ifp);
   2288 		splx(s);
   2289 		return;
   2290 	}
   2291 
   2292 #ifdef DEBUG
   2293 	log(LOG_DEBUG, "%s: link state %s (was %s)\n", ifp->if_xname,
   2294 		link_state == LINK_STATE_UP ? "UP" :
   2295 		link_state == LINK_STATE_DOWN ? "DOWN" :
   2296 		"UNKNOWN",
   2297 		ifp->if_link_state == LINK_STATE_UP ? "UP" :
   2298 		ifp->if_link_state == LINK_STATE_DOWN ? "DOWN" :
   2299 		"UNKNOWN");
   2300 #endif
   2301 
   2302 	/*
   2303 	 * When going from UNKNOWN to UP, we need to mark existing
   2304 	 * addresses as tentative and restart DAD as we may have
   2305 	 * erroneously not found a duplicate.
   2306 	 *
   2307 	 * This needs to happen before rt_ifmsg to avoid a race where
   2308 	 * listeners would have an address and expect it to work right
   2309 	 * away.
   2310 	 */
   2311 	notify = (link_state == LINK_STATE_UP &&
   2312 	    ifp->if_link_state == LINK_STATE_UNKNOWN);
   2313 	ifp->if_link_state = link_state;
   2314 	/* The following routines may sleep so release the spin mutex */
   2315 	IF_LINK_STATE_CHANGE_UNLOCK(ifp);
   2316 
   2317 	KERNEL_LOCK_UNLESS_NET_MPSAFE();
   2318 	if (notify) {
   2319 		DOMAIN_FOREACH(dp) {
   2320 			if (dp->dom_if_link_state_change != NULL)
   2321 				dp->dom_if_link_state_change(ifp,
   2322 				    LINK_STATE_DOWN);
   2323 		}
   2324 	}
   2325 
   2326 	/* Notify that the link state has changed. */
   2327 	rt_ifmsg(ifp);
   2328 
   2329 	simplehook_dohooks(ifp->if_linkstate_hooks);
   2330 
   2331 	DOMAIN_FOREACH(dp) {
   2332 		if (dp->dom_if_link_state_change != NULL)
   2333 			dp->dom_if_link_state_change(ifp, link_state);
   2334 	}
   2335 	KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
   2336 	splx(s);
   2337 }
   2338 
   2339 /*
   2340  * Process the interface link state change queue.
   2341  */
   2342 static void
   2343 if_link_state_change_work(struct work *work, void *arg)
   2344 {
   2345 	struct ifnet *ifp = container_of(work, struct ifnet, if_link_work);
   2346 	uint8_t state;
   2347 
   2348 	KERNEL_LOCK_UNLESS_NET_MPSAFE();
   2349 	const int s = splnet();
   2350 
   2351 	/*
   2352 	 * Process a single link state in order of precedence:
   2353 	 *     DOWN, UNKNOWN and finally UP.
   2354 	 * If locked, abort.
   2355 	 */
   2356 	IF_LINK_STATE_CHANGE_LOCK(ifp);
   2357 	ifp->if_link_queue &= ~LINK_QUEUE_SCHEDULED;
   2358 	if (ifp->if_link_queue & LINK_QUEUE_LOCKED)
   2359 		goto out;
   2360 	else if (ifp->if_link_queue & LINK_QUEUE_DOWN) {
   2361 		ifp->if_link_queue &= ~LINK_QUEUE_DOWN;
   2362 		state = LINK_STATE_DOWN;
   2363 	} else if (ifp->if_link_queue & LINK_QUEUE_UNKNOWN) {
   2364 		ifp->if_link_queue &= ~LINK_QUEUE_UNKNOWN;
   2365 		state = LINK_STATE_UNKNOWN;
   2366 	} else if (ifp->if_link_queue & LINK_QUEUE_UP) {
   2367 		ifp->if_link_queue &= ~LINK_QUEUE_UP;
   2368 		state = LINK_STATE_UP;
   2369 	} else {
   2370 #ifdef DEBUG
   2371 		printf("%s: unknown link queue %u\n",
   2372 		    ifp->if_xname, ifp->if_link_queue);
   2373 #endif
   2374 		goto out;
   2375 	}
   2376 	IF_LINK_STATE_CHANGE_UNLOCK(ifp);
   2377 
   2378 	IFNET_LOCK(ifp);
   2379 	if_link_state_change_process(ifp, state);
   2380 	IFNET_UNLOCK(ifp);
   2381 
   2382 	/* If there is a link state change to come, schedule it. */
   2383 	IF_LINK_STATE_CHANGE_LOCK(ifp);
   2384 	if (ifp->if_link_queue == 0 ||
   2385 	    (ifp->if_link_queue & (LINK_QUEUE_LOCKED | LINK_QUEUE_SCHEDULED)))
   2386 		goto out;
   2387 
   2388 	ifp->if_link_queue |= LINK_QUEUE_SCHEDULED;
   2389 	workqueue_enqueue(ifnet_link_state_wq, &ifp->if_link_work, NULL);
   2390 
   2391 out:
   2392 	IF_LINK_STATE_CHANGE_UNLOCK(ifp);
   2393 	splx(s);
   2394 	KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
   2395 }
   2396 
   2397 void *
   2398 if_linkstate_change_establish(struct ifnet *ifp, void (*fn)(void *), void *arg)
   2399 {
   2400 	khook_t *hk;
   2401 
   2402 	hk = simplehook_establish(ifp->if_linkstate_hooks, fn, arg);
   2403 
   2404 	return (void *)hk;
   2405 }
   2406 
   2407 void
   2408 if_linkstate_change_disestablish(struct ifnet *ifp, void *vhook,
   2409     kmutex_t *lock)
   2410 {
   2411 
   2412 	simplehook_disestablish(ifp->if_linkstate_hooks, vhook, lock);
   2413 }
   2414 
   2415 /*
   2416  * Used to mark addresses on an interface as DETATCHED or TENTATIVE
   2417  * and thus start Duplicate Address Detection without changing the
   2418  * real link state.
   2419  */
   2420 void
   2421 if_domain_link_state_change(struct ifnet *ifp, int link_state)
   2422 {
   2423 	struct domain *dp;
   2424 
   2425 	const int s = splnet();
   2426 	KERNEL_LOCK_UNLESS_NET_MPSAFE();
   2427 
   2428 	DOMAIN_FOREACH(dp) {
   2429 		if (dp->dom_if_link_state_change != NULL)
   2430 			dp->dom_if_link_state_change(ifp, link_state);
   2431 	}
   2432 
   2433 	splx(s);
   2434 	KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
   2435 }
   2436 
   2437 /*
   2438  * Default action when installing a local route on a point-to-point
   2439  * interface.
   2440  */
   2441 void
   2442 p2p_rtrequest(int req, struct rtentry *rt,
   2443     __unused const struct rt_addrinfo *info)
   2444 {
   2445 	struct ifnet *ifp = rt->rt_ifp;
   2446 	struct ifaddr *ifa, *lo0ifa;
   2447 	int s = pserialize_read_enter();
   2448 
   2449 	switch (req) {
   2450 	case RTM_ADD:
   2451 		if ((rt->rt_flags & RTF_LOCAL) == 0)
   2452 			break;
   2453 
   2454 		rt->rt_ifp = lo0ifp;
   2455 
   2456 		if (ISSET(info->rti_flags, RTF_DONTCHANGEIFA))
   2457 			break;
   2458 
   2459 		IFADDR_READER_FOREACH(ifa, ifp) {
   2460 			if (equal(rt_getkey(rt), ifa->ifa_addr))
   2461 				break;
   2462 		}
   2463 		if (ifa == NULL)
   2464 			break;
   2465 
   2466 		/*
   2467 		 * Ensure lo0 has an address of the same family.
   2468 		 */
   2469 		IFADDR_READER_FOREACH(lo0ifa, lo0ifp) {
   2470 			if (lo0ifa->ifa_addr->sa_family ==
   2471 			    ifa->ifa_addr->sa_family)
   2472 				break;
   2473 		}
   2474 		if (lo0ifa == NULL)
   2475 			break;
   2476 
   2477 		/*
   2478 		 * Make sure to set rt->rt_ifa to the interface
   2479 		 * address we are using, otherwise we will have trouble
   2480 		 * with source address selection.
   2481 		 */
   2482 		if (ifa != rt->rt_ifa)
   2483 			rt_replace_ifa(rt, ifa);
   2484 		break;
   2485 	case RTM_DELETE:
   2486 	default:
   2487 		break;
   2488 	}
   2489 	pserialize_read_exit(s);
   2490 }
   2491 
   2492 static void
   2493 _if_down(struct ifnet *ifp)
   2494 {
   2495 	struct ifaddr *ifa;
   2496 	struct domain *dp;
   2497 	struct psref psref;
   2498 
   2499 	ifp->if_flags &= ~IFF_UP;
   2500 	nanotime(&ifp->if_lastchange);
   2501 
   2502 	const int bound = curlwp_bind();
   2503 	int s = pserialize_read_enter();
   2504 	IFADDR_READER_FOREACH(ifa, ifp) {
   2505 		ifa_acquire(ifa, &psref);
   2506 		pserialize_read_exit(s);
   2507 
   2508 		pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
   2509 
   2510 		s = pserialize_read_enter();
   2511 		ifa_release(ifa, &psref);
   2512 	}
   2513 	pserialize_read_exit(s);
   2514 	curlwp_bindx(bound);
   2515 
   2516 	IFQ_PURGE(&ifp->if_snd);
   2517 #if NCARP > 0
   2518 	if (ifp->if_carp)
   2519 		carp_carpdev_state(ifp);
   2520 #endif
   2521 	rt_ifmsg(ifp);
   2522 	DOMAIN_FOREACH(dp) {
   2523 		if (dp->dom_if_down)
   2524 			dp->dom_if_down(ifp);
   2525 	}
   2526 }
   2527 
   2528 static void
   2529 if_down_deactivated(struct ifnet *ifp)
   2530 {
   2531 
   2532 	KASSERT(if_is_deactivated(ifp));
   2533 	_if_down(ifp);
   2534 }
   2535 
   2536 void
   2537 if_down_locked(struct ifnet *ifp)
   2538 {
   2539 
   2540 	KASSERT(IFNET_LOCKED(ifp));
   2541 	_if_down(ifp);
   2542 }
   2543 
   2544 /*
   2545  * Mark an interface down and notify protocols of
   2546  * the transition.
   2547  * NOTE: must be called at splsoftnet or equivalent.
   2548  */
   2549 void
   2550 if_down(struct ifnet *ifp)
   2551 {
   2552 
   2553 	IFNET_LOCK(ifp);
   2554 	if_down_locked(ifp);
   2555 	IFNET_UNLOCK(ifp);
   2556 }
   2557 
   2558 /*
   2559  * Must be called with holding if_ioctl_lock.
   2560  */
   2561 static void
   2562 if_up_locked(struct ifnet *ifp)
   2563 {
   2564 #ifdef notyet
   2565 	struct ifaddr *ifa;
   2566 #endif
   2567 	struct domain *dp;
   2568 
   2569 	KASSERT(IFNET_LOCKED(ifp));
   2570 
   2571 	KASSERT(!if_is_deactivated(ifp));
   2572 	ifp->if_flags |= IFF_UP;
   2573 	nanotime(&ifp->if_lastchange);
   2574 #ifdef notyet
   2575 	/* this has no effect on IP, and will kill all ISO connections XXX */
   2576 	IFADDR_READER_FOREACH(ifa, ifp)
   2577 		pfctlinput(PRC_IFUP, ifa->ifa_addr);
   2578 #endif
   2579 #if NCARP > 0
   2580 	if (ifp->if_carp)
   2581 		carp_carpdev_state(ifp);
   2582 #endif
   2583 	rt_ifmsg(ifp);
   2584 	DOMAIN_FOREACH(dp) {
   2585 		if (dp->dom_if_up)
   2586 			dp->dom_if_up(ifp);
   2587 	}
   2588 }
   2589 
   2590 /*
   2591  * Handle interface slowtimo timer routine.  Called
   2592  * from softclock, we decrement timer (if set) and
   2593  * call the appropriate interface routine on expiration.
   2594  */
   2595 static bool
   2596 if_slowtimo_countdown(struct ifnet *ifp)
   2597 {
   2598 	bool fire = false;
   2599 	const int s = splnet();
   2600 
   2601 	KERNEL_LOCK(1, NULL);
   2602 	if (ifp->if_timer != 0 && --ifp->if_timer == 0)
   2603 		fire = true;
   2604 	KERNEL_UNLOCK_ONE(NULL);
   2605 	splx(s);
   2606 
   2607 	return fire;
   2608 }
   2609 
   2610 static void
   2611 if_slowtimo_intr(void *arg)
   2612 {
   2613 	struct ifnet *ifp = arg;
   2614 	struct if_slowtimo_data *isd = ifp->if_slowtimo_data;
   2615 
   2616 	mutex_enter(&isd->isd_lock);
   2617 	if (!isd->isd_dying) {
   2618 		if (isd->isd_trigger || if_slowtimo_countdown(ifp)) {
   2619 			if (!isd->isd_queued) {
   2620 				isd->isd_queued = true;
   2621 				workqueue_enqueue(if_slowtimo_wq,
   2622 				    &isd->isd_work, NULL);
   2623 			}
   2624 		} else
   2625 			callout_schedule(&isd->isd_ch, hz / IFNET_SLOWHZ);
   2626 	}
   2627 	mutex_exit(&isd->isd_lock);
   2628 }
   2629 
   2630 static void
   2631 if_slowtimo_work(struct work *work, void *arg)
   2632 {
   2633 	struct if_slowtimo_data *isd =
   2634 	    container_of(work, struct if_slowtimo_data, isd_work);
   2635 	struct ifnet *ifp = isd->isd_ifp;
   2636 	const int s = splnet();
   2637 
   2638 	KERNEL_LOCK(1, NULL);
   2639 	(*ifp->if_slowtimo)(ifp);
   2640 	KERNEL_UNLOCK_ONE(NULL);
   2641 	splx(s);
   2642 
   2643 	mutex_enter(&isd->isd_lock);
   2644 	if (isd->isd_trigger) {
   2645 		isd->isd_trigger = false;
   2646 		printf("%s: watchdog triggered\n", ifp->if_xname);
   2647 	}
   2648 	isd->isd_queued = false;
   2649 	if (!isd->isd_dying)
   2650 		callout_schedule(&isd->isd_ch, hz / IFNET_SLOWHZ);
   2651 	mutex_exit(&isd->isd_lock);
   2652 }
   2653 
   2654 static int
   2655 sysctl_if_watchdog(SYSCTLFN_ARGS)
   2656 {
   2657 	struct sysctlnode node = *rnode;
   2658 	struct ifnet *ifp = node.sysctl_data;
   2659 	struct if_slowtimo_data *isd = ifp->if_slowtimo_data;
   2660 	int arg = 0;
   2661 	int error;
   2662 
   2663 	node.sysctl_data = &arg;
   2664 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2665 	if (error || newp == NULL)
   2666 		return error;
   2667 	if (arg) {
   2668 		mutex_enter(&isd->isd_lock);
   2669 		KASSERT(!isd->isd_dying);
   2670 		isd->isd_trigger = true;
   2671 		callout_schedule(&isd->isd_ch, 0);
   2672 		mutex_exit(&isd->isd_lock);
   2673 	}
   2674 
   2675 	return 0;
   2676 }
   2677 
   2678 static void
   2679 sysctl_watchdog_setup(struct ifnet *ifp)
   2680 {
   2681 	struct sysctllog **clog = &ifp->if_sysctl_log;
   2682 	const struct sysctlnode *rnode;
   2683 
   2684 	if (sysctl_createv(clog, 0, NULL, &rnode,
   2685 		CTLFLAG_PERMANENT, CTLTYPE_NODE, "interfaces",
   2686 		SYSCTL_DESCR("Per-interface controls"),
   2687 		NULL, 0, NULL, 0,
   2688 		CTL_NET, CTL_CREATE, CTL_EOL) != 0)
   2689 		goto bad;
   2690 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   2691 		CTLFLAG_PERMANENT, CTLTYPE_NODE, ifp->if_xname,
   2692 		SYSCTL_DESCR("Interface controls"),
   2693 		NULL, 0, NULL, 0,
   2694 		CTL_CREATE, CTL_EOL) != 0)
   2695 		goto bad;
   2696 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   2697 		CTLFLAG_PERMANENT, CTLTYPE_NODE, "watchdog",
   2698 		SYSCTL_DESCR("Interface watchdog controls"),
   2699 		NULL, 0, NULL, 0,
   2700 		CTL_CREATE, CTL_EOL) != 0)
   2701 		goto bad;
   2702 	if (sysctl_createv(clog, 0, &rnode, NULL,
   2703 		CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT, "trigger",
   2704 		SYSCTL_DESCR("Trigger watchdog timeout"),
   2705 		sysctl_if_watchdog, 0, (int *)ifp, 0,
   2706 		CTL_CREATE, CTL_EOL) != 0)
   2707 		goto bad;
   2708 
   2709 	return;
   2710 
   2711 bad:
   2712 	printf("%s: could not attach sysctl watchdog nodes\n", ifp->if_xname);
   2713 }
   2714 
   2715 /*
   2716  * Mark an interface up and notify protocols of
   2717  * the transition.
   2718  * NOTE: must be called at splsoftnet or equivalent.
   2719  */
   2720 void
   2721 if_up(struct ifnet *ifp)
   2722 {
   2723 
   2724 	IFNET_LOCK(ifp);
   2725 	if_up_locked(ifp);
   2726 	IFNET_UNLOCK(ifp);
   2727 }
   2728 
   2729 /*
   2730  * Set/clear promiscuous mode on interface ifp based on the truth value
   2731  * of pswitch.  The calls are reference counted so that only the first
   2732  * "on" request actually has an effect, as does the final "off" request.
   2733  * Results are undefined if the "off" and "on" requests are not matched.
   2734  */
   2735 int
   2736 ifpromisc_locked(struct ifnet *ifp, int pswitch)
   2737 {
   2738 	int pcount, ret = 0;
   2739 	u_short nflags;
   2740 
   2741 	KASSERT(IFNET_LOCKED(ifp));
   2742 
   2743 	pcount = ifp->if_pcount;
   2744 	if (pswitch) {
   2745 		/*
   2746 		 * Allow the device to be "placed" into promiscuous
   2747 		 * mode even if it is not configured up.  It will
   2748 		 * consult IFF_PROMISC when it is brought up.
   2749 		 */
   2750 		if (ifp->if_pcount++ != 0)
   2751 			goto out;
   2752 		nflags = ifp->if_flags | IFF_PROMISC;
   2753 	} else {
   2754 		if (--ifp->if_pcount > 0)
   2755 			goto out;
   2756 		nflags = ifp->if_flags & ~IFF_PROMISC;
   2757 	}
   2758 	ret = if_flags_set(ifp, nflags);
   2759 	/* Restore interface state if not successful. */
   2760 	if (ret != 0)
   2761 		ifp->if_pcount = pcount;
   2762 
   2763 out:
   2764 	return ret;
   2765 }
   2766 
   2767 int
   2768 ifpromisc(struct ifnet *ifp, int pswitch)
   2769 {
   2770 	int e;
   2771 
   2772 	IFNET_LOCK(ifp);
   2773 	e = ifpromisc_locked(ifp, pswitch);
   2774 	IFNET_UNLOCK(ifp);
   2775 
   2776 	return e;
   2777 }
   2778 
   2779 /*
   2780  * if_ioctl(ifp, cmd, data)
   2781  *
   2782  *	Apply an ioctl command to the interface.  Returns 0 on success,
   2783  *	nonzero errno(3) number on failure.
   2784  *
   2785  *	For SIOCADDMULTI/SIOCDELMULTI, caller need not hold locks -- it
   2786  *	is the driver's responsibility to take any internal locks.
   2787  *	(Kernel logic should generally invoke these only through
   2788  *	if_mcast_op.)
   2789  *
   2790  *	For all other ioctls, caller must hold ifp->if_ioctl_lock,
   2791  *	a.k.a. IFNET_LOCK.  May sleep.
   2792  */
   2793 int
   2794 if_ioctl(struct ifnet *ifp, u_long cmd, void *data)
   2795 {
   2796 
   2797 	switch (cmd) {
   2798 	case SIOCADDMULTI:
   2799 	case SIOCDELMULTI:
   2800 		break;
   2801 	default:
   2802 		KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
   2803 	}
   2804 
   2805 	return (*ifp->if_ioctl)(ifp, cmd, data);
   2806 }
   2807 
   2808 /*
   2809  * if_init(ifp)
   2810  *
   2811  *	Prepare the hardware underlying ifp to process packets
   2812  *	according to its current configuration.  Returns 0 on success,
   2813  *	nonzero errno(3) number on failure.
   2814  *
   2815  *	May sleep.  Caller must hold ifp->if_ioctl_lock, a.k.a
   2816  *	IFNET_LOCK.
   2817  */
   2818 int
   2819 if_init(struct ifnet *ifp)
   2820 {
   2821 
   2822 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
   2823 
   2824 	return (*ifp->if_init)(ifp);
   2825 }
   2826 
   2827 /*
   2828  * if_stop(ifp, disable)
   2829  *
   2830  *	Stop the hardware underlying ifp from processing packets.
   2831  *
   2832  *	If disable is true, ... XXX(?)
   2833  *
   2834  *	May sleep.  Caller must hold ifp->if_ioctl_lock, a.k.a
   2835  *	IFNET_LOCK.
   2836  */
   2837 void
   2838 if_stop(struct ifnet *ifp, int disable)
   2839 {
   2840 
   2841 	KASSERTMSG(IFNET_LOCKED(ifp), "%s", ifp->if_xname);
   2842 
   2843 	(*ifp->if_stop)(ifp, disable);
   2844 }
   2845 
   2846 /*
   2847  * Map interface name to
   2848  * interface structure pointer.
   2849  */
   2850 struct ifnet *
   2851 ifunit(const char *name)
   2852 {
   2853 	struct ifnet *ifp;
   2854 	const char *cp = name;
   2855 	u_int unit = 0;
   2856 	u_int i;
   2857 
   2858 	/*
   2859 	 * If the entire name is a number, treat it as an ifindex.
   2860 	 */
   2861 	for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++)
   2862 		unit = unit * 10 + (*cp - '0');
   2863 
   2864 	/*
   2865 	 * If the number took all of the name, then it's a valid ifindex.
   2866 	 */
   2867 	if (i == IFNAMSIZ || (cp != name && *cp == '\0'))
   2868 		return if_byindex(unit);
   2869 
   2870 	ifp = NULL;
   2871 	const int s = pserialize_read_enter();
   2872 	IFNET_READER_FOREACH(ifp) {
   2873 		if (if_is_deactivated(ifp))
   2874 			continue;
   2875 		if (strcmp(ifp->if_xname, name) == 0)
   2876 			goto out;
   2877 	}
   2878 out:
   2879 	pserialize_read_exit(s);
   2880 	return ifp;
   2881 }
   2882 
   2883 /*
   2884  * Get a reference of an ifnet object by an interface name.
   2885  * The returned reference is protected by psref(9). The caller
   2886  * must release a returned reference by if_put after use.
   2887  */
   2888 struct ifnet *
   2889 if_get(const char *name, struct psref *psref)
   2890 {
   2891 	struct ifnet *ifp;
   2892 	const char *cp = name;
   2893 	u_int unit = 0;
   2894 	u_int i;
   2895 
   2896 	/*
   2897 	 * If the entire name is a number, treat it as an ifindex.
   2898 	 */
   2899 	for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++)
   2900 		unit = unit * 10 + (*cp - '0');
   2901 
   2902 	/*
   2903 	 * If the number took all of the name, then it's a valid ifindex.
   2904 	 */
   2905 	if (i == IFNAMSIZ || (cp != name && *cp == '\0'))
   2906 		return if_get_byindex(unit, psref);
   2907 
   2908 	ifp = NULL;
   2909 	const int s = pserialize_read_enter();
   2910 	IFNET_READER_FOREACH(ifp) {
   2911 		if (if_is_deactivated(ifp))
   2912 			continue;
   2913 		if (strcmp(ifp->if_xname, name) == 0) {
   2914 			PSREF_DEBUG_FILL_RETURN_ADDRESS(psref);
   2915 			psref_acquire(psref, &ifp->if_psref,
   2916 			    ifnet_psref_class);
   2917 			goto out;
   2918 		}
   2919 	}
   2920 out:
   2921 	pserialize_read_exit(s);
   2922 	return ifp;
   2923 }
   2924 
   2925 /*
   2926  * Release a reference of an ifnet object given by if_get, if_get_byindex
   2927  * or if_get_bylla.
   2928  */
   2929 void
   2930 if_put(const struct ifnet *ifp, struct psref *psref)
   2931 {
   2932 
   2933 	if (ifp == NULL)
   2934 		return;
   2935 
   2936 	psref_release(psref, &ifp->if_psref, ifnet_psref_class);
   2937 }
   2938 
   2939 /*
   2940  * Return ifp having idx. Return NULL if not found.  Normally if_byindex
   2941  * should be used.
   2942  */
   2943 ifnet_t *
   2944 _if_byindex(u_int idx)
   2945 {
   2946 
   2947 	return (__predict_true(idx < if_indexlim)) ? ifindex2ifnet[idx] : NULL;
   2948 }
   2949 
   2950 /*
   2951  * Return ifp having idx. Return NULL if not found or the found ifp is
   2952  * already deactivated.
   2953  */
   2954 ifnet_t *
   2955 if_byindex(u_int idx)
   2956 {
   2957 	ifnet_t *ifp;
   2958 
   2959 	ifp = _if_byindex(idx);
   2960 	if (ifp != NULL && if_is_deactivated(ifp))
   2961 		ifp = NULL;
   2962 	return ifp;
   2963 }
   2964 
   2965 /*
   2966  * Get a reference of an ifnet object by an interface index.
   2967  * The returned reference is protected by psref(9). The caller
   2968  * must release a returned reference by if_put after use.
   2969  */
   2970 ifnet_t *
   2971 if_get_byindex(u_int idx, struct psref *psref)
   2972 {
   2973 	ifnet_t *ifp;
   2974 
   2975 	const int s = pserialize_read_enter();
   2976 	ifp = if_byindex(idx);
   2977 	if (__predict_true(ifp != NULL)) {
   2978 		PSREF_DEBUG_FILL_RETURN_ADDRESS(psref);
   2979 		psref_acquire(psref, &ifp->if_psref, ifnet_psref_class);
   2980 	}
   2981 	pserialize_read_exit(s);
   2982 
   2983 	return ifp;
   2984 }
   2985 
   2986 ifnet_t *
   2987 if_get_bylla(const void *lla, unsigned char lla_len, struct psref *psref)
   2988 {
   2989 	ifnet_t *ifp;
   2990 
   2991 	const int s = pserialize_read_enter();
   2992 	IFNET_READER_FOREACH(ifp) {
   2993 		if (if_is_deactivated(ifp))
   2994 			continue;
   2995 		if (ifp->if_addrlen != lla_len)
   2996 			continue;
   2997 		if (memcmp(lla, CLLADDR(ifp->if_sadl), lla_len) == 0) {
   2998 			psref_acquire(psref, &ifp->if_psref,
   2999 			    ifnet_psref_class);
   3000 			break;
   3001 		}
   3002 	}
   3003 	pserialize_read_exit(s);
   3004 
   3005 	return ifp;
   3006 }
   3007 
   3008 /*
   3009  * Note that it's safe only if the passed ifp is guaranteed to not be freed,
   3010  * for example using pserialize or the ifp is already held or some other
   3011  * object is held which guarantes the ifp to not be freed indirectly.
   3012  */
   3013 void
   3014 if_acquire(struct ifnet *ifp, struct psref *psref)
   3015 {
   3016 
   3017 	KASSERT(ifp->if_index != 0);
   3018 	psref_acquire(psref, &ifp->if_psref, ifnet_psref_class);
   3019 }
   3020 
   3021 bool
   3022 if_held(struct ifnet *ifp)
   3023 {
   3024 
   3025 	return psref_held(&ifp->if_psref, ifnet_psref_class);
   3026 }
   3027 
   3028 /*
   3029  * Some tunnel interfaces can nest, e.g. IPv4 over IPv4 gif(4) tunnel over
   3030  * IPv4. Check the tunnel nesting count.
   3031  * Return > 0, if tunnel nesting count is more than limit.
   3032  * Return 0, if tunnel nesting count is equal or less than limit.
   3033  */
   3034 int
   3035 if_tunnel_check_nesting(struct ifnet *ifp, struct mbuf *m, int limit)
   3036 {
   3037 	struct m_tag *mtag;
   3038 	int *count;
   3039 
   3040 	mtag = m_tag_find(m, PACKET_TAG_TUNNEL_INFO);
   3041 	if (mtag != NULL) {
   3042 		count = (int *)(mtag + 1);
   3043 		if (++(*count) > limit) {
   3044 			log(LOG_NOTICE,
   3045 			    "%s: recursively called too many times(%d)\n",
   3046 			    ifp->if_xname, *count);
   3047 			return EIO;
   3048 		}
   3049 	} else {
   3050 		mtag = m_tag_get(PACKET_TAG_TUNNEL_INFO, sizeof(*count),
   3051 		    M_NOWAIT);
   3052 		if (mtag != NULL) {
   3053 			m_tag_prepend(m, mtag);
   3054 			count = (int *)(mtag + 1);
   3055 			*count = 0;
   3056 		} else {
   3057 			log(LOG_DEBUG, "%s: m_tag_get() failed, "
   3058 			    "recursion calls are not prevented.\n",
   3059 			    ifp->if_xname);
   3060 		}
   3061 	}
   3062 
   3063 	return 0;
   3064 }
   3065 
   3066 static void
   3067 if_tunnel_ro_init_pc(void *p, void *arg __unused, struct cpu_info *ci __unused)
   3068 {
   3069 	struct tunnel_ro *tro = p;
   3070 
   3071 	tro->tr_ro = kmem_zalloc(sizeof(*tro->tr_ro), KM_SLEEP);
   3072 	tro->tr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
   3073 }
   3074 
   3075 static void
   3076 if_tunnel_ro_fini_pc(void *p, void *arg __unused, struct cpu_info *ci __unused)
   3077 {
   3078 	struct tunnel_ro *tro = p;
   3079 
   3080 	rtcache_free(tro->tr_ro);
   3081 	kmem_free(tro->tr_ro, sizeof(*tro->tr_ro));
   3082 
   3083 	mutex_obj_free(tro->tr_lock);
   3084 }
   3085 
   3086 percpu_t *
   3087 if_tunnel_alloc_ro_percpu(void)
   3088 {
   3089 
   3090 	return percpu_create(sizeof(struct tunnel_ro),
   3091 	    if_tunnel_ro_init_pc, if_tunnel_ro_fini_pc, NULL);
   3092 }
   3093 
   3094 void
   3095 if_tunnel_free_ro_percpu(percpu_t *ro_percpu)
   3096 {
   3097 
   3098 	percpu_free(ro_percpu, sizeof(struct tunnel_ro));
   3099 }
   3100 
   3101 
   3102 static void
   3103 if_tunnel_rtcache_free_pc(void *p, void *arg __unused,
   3104     struct cpu_info *ci __unused)
   3105 {
   3106 	struct tunnel_ro *tro = p;
   3107 
   3108 	mutex_enter(tro->tr_lock);
   3109 	rtcache_free(tro->tr_ro);
   3110 	mutex_exit(tro->tr_lock);
   3111 }
   3112 
   3113 void if_tunnel_ro_percpu_rtcache_free(percpu_t *ro_percpu)
   3114 {
   3115 
   3116 	percpu_foreach(ro_percpu, if_tunnel_rtcache_free_pc, NULL);
   3117 }
   3118 
   3119 void
   3120 if_export_if_data(ifnet_t * const ifp, struct if_data *ifi, bool zero_stats)
   3121 {
   3122 
   3123 	/* Collect the volatile stats first; this zeros *ifi. */
   3124 	if_stats_to_if_data(ifp, ifi, zero_stats);
   3125 
   3126 	ifi->ifi_type = ifp->if_type;
   3127 	ifi->ifi_addrlen = ifp->if_addrlen;
   3128 	ifi->ifi_hdrlen = ifp->if_hdrlen;
   3129 	ifi->ifi_link_state = ifp->if_link_state;
   3130 	ifi->ifi_mtu = ifp->if_mtu;
   3131 	ifi->ifi_metric = ifp->if_metric;
   3132 	ifi->ifi_baudrate = ifp->if_baudrate;
   3133 	ifi->ifi_lastchange = ifp->if_lastchange;
   3134 }
   3135 
   3136 /* common */
   3137 int
   3138 ifioctl_common(struct ifnet *ifp, u_long cmd, void *data)
   3139 {
   3140 	struct ifreq *ifr;
   3141 	struct ifcapreq *ifcr;
   3142 	struct ifdatareq *ifdr;
   3143 	unsigned short flags;
   3144 	char *descr;
   3145 	int error;
   3146 
   3147 	switch (cmd) {
   3148 	case SIOCSIFCAP:
   3149 		ifcr = data;
   3150 		if ((ifcr->ifcr_capenable & ~ifp->if_capabilities) != 0)
   3151 			return EINVAL;
   3152 
   3153 		if (ifcr->ifcr_capenable == ifp->if_capenable)
   3154 			return 0;
   3155 
   3156 		ifp->if_capenable = ifcr->ifcr_capenable;
   3157 
   3158 		/* Pre-compute the checksum flags mask. */
   3159 		ifp->if_csum_flags_tx = 0;
   3160 		ifp->if_csum_flags_rx = 0;
   3161 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Tx)
   3162 			ifp->if_csum_flags_tx |= M_CSUM_IPv4;
   3163 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Rx)
   3164 			ifp->if_csum_flags_rx |= M_CSUM_IPv4;
   3165 
   3166 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Tx)
   3167 			ifp->if_csum_flags_tx |= M_CSUM_TCPv4;
   3168 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Rx)
   3169 			ifp->if_csum_flags_rx |= M_CSUM_TCPv4;
   3170 
   3171 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Tx)
   3172 			ifp->if_csum_flags_tx |= M_CSUM_UDPv4;
   3173 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Rx)
   3174 			ifp->if_csum_flags_rx |= M_CSUM_UDPv4;
   3175 
   3176 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Tx)
   3177 			ifp->if_csum_flags_tx |= M_CSUM_TCPv6;
   3178 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Rx)
   3179 			ifp->if_csum_flags_rx |= M_CSUM_TCPv6;
   3180 
   3181 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Tx)
   3182 			ifp->if_csum_flags_tx |= M_CSUM_UDPv6;
   3183 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Rx)
   3184 			ifp->if_csum_flags_rx |= M_CSUM_UDPv6;
   3185 
   3186 		if (ifp->if_capenable & IFCAP_TSOv4)
   3187 			ifp->if_csum_flags_tx |= M_CSUM_TSOv4;
   3188 		if (ifp->if_capenable & IFCAP_TSOv6)
   3189 			ifp->if_csum_flags_tx |= M_CSUM_TSOv6;
   3190 
   3191 #if NBRIDGE > 0
   3192 		if (ifp->if_bridge != NULL)
   3193 			bridge_calc_csum_flags(ifp->if_bridge);
   3194 #endif
   3195 
   3196 		if (ifp->if_flags & IFF_UP)
   3197 			return ENETRESET;
   3198 		return 0;
   3199 	case SIOCSIFFLAGS:
   3200 		ifr = data;
   3201 		/*
   3202 		 * If if_is_mpsafe(ifp), KERNEL_LOCK isn't held here, but if_up
   3203 		 * and if_down aren't MP-safe yet, so we must hold the lock.
   3204 		 */
   3205 		KERNEL_LOCK_IF_IFP_MPSAFE(ifp);
   3206 		if (ifp->if_flags & IFF_UP && (ifr->ifr_flags & IFF_UP) == 0) {
   3207 			const int s = splsoftnet();
   3208 			if_down_locked(ifp);
   3209 			splx(s);
   3210 		}
   3211 		if (ifr->ifr_flags & IFF_UP && (ifp->if_flags & IFF_UP) == 0) {
   3212 			const int s = splsoftnet();
   3213 			if_up_locked(ifp);
   3214 			splx(s);
   3215 		}
   3216 		KERNEL_UNLOCK_IF_IFP_MPSAFE(ifp);
   3217 		flags = (ifp->if_flags & IFF_CANTCHANGE) |
   3218 		    (ifr->ifr_flags &~ IFF_CANTCHANGE);
   3219 		if (ifp->if_flags != flags) {
   3220 			ifp->if_flags = flags;
   3221 			/* Notify that the flags have changed. */
   3222 			rt_ifmsg(ifp);
   3223 		}
   3224 		break;
   3225 	case SIOCGIFFLAGS:
   3226 		ifr = data;
   3227 		ifr->ifr_flags = ifp->if_flags;
   3228 		break;
   3229 
   3230 	case SIOCGIFMETRIC:
   3231 		ifr = data;
   3232 		ifr->ifr_metric = ifp->if_metric;
   3233 		break;
   3234 
   3235 	case SIOCGIFMTU:
   3236 		ifr = data;
   3237 		ifr->ifr_mtu = ifp->if_mtu;
   3238 		break;
   3239 
   3240 	case SIOCGIFDLT:
   3241 		ifr = data;
   3242 		ifr->ifr_dlt = ifp->if_dlt;
   3243 		break;
   3244 
   3245 	case SIOCGIFCAP:
   3246 		ifcr = data;
   3247 		ifcr->ifcr_capabilities = ifp->if_capabilities;
   3248 		ifcr->ifcr_capenable = ifp->if_capenable;
   3249 		break;
   3250 
   3251 	case SIOCSIFMETRIC:
   3252 		ifr = data;
   3253 		ifp->if_metric = ifr->ifr_metric;
   3254 		break;
   3255 
   3256 	case SIOCGIFDATA:
   3257 		ifdr = data;
   3258 		if_export_if_data(ifp, &ifdr->ifdr_data, false);
   3259 		break;
   3260 
   3261 	case SIOCGIFINDEX:
   3262 		ifr = data;
   3263 		ifr->ifr_index = ifp->if_index;
   3264 		break;
   3265 
   3266 	case SIOCZIFDATA:
   3267 		ifdr = data;
   3268 		if_export_if_data(ifp, &ifdr->ifdr_data, true);
   3269 		getnanotime(&ifp->if_lastchange);
   3270 		break;
   3271 	case SIOCSIFMTU:
   3272 		ifr = data;
   3273 		if (ifp->if_mtu == ifr->ifr_mtu)
   3274 			break;
   3275 		ifp->if_mtu = ifr->ifr_mtu;
   3276 		return ENETRESET;
   3277 	case SIOCSIFDESCR:
   3278 		error = kauth_authorize_network(kauth_cred_get(),
   3279 		    KAUTH_NETWORK_INTERFACE,
   3280 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, KAUTH_ARG(cmd),
   3281 		    NULL);
   3282 		if (error)
   3283 			return error;
   3284 
   3285 		ifr = data;
   3286 
   3287 		if (ifr->ifr_buflen > IFDESCRSIZE)
   3288 			return ENAMETOOLONG;
   3289 
   3290 		if (ifr->ifr_buf == NULL || ifr->ifr_buflen == 0) {
   3291 			/* unset description */
   3292 			descr = NULL;
   3293 		} else {
   3294 			descr = kmem_zalloc(IFDESCRSIZE, KM_SLEEP);
   3295 			/*
   3296 			 * copy (IFDESCRSIZE - 1) bytes to ensure
   3297 			 * terminating nul
   3298 			 */
   3299 			error = copyin(ifr->ifr_buf, descr, IFDESCRSIZE - 1);
   3300 			if (error) {
   3301 				kmem_free(descr, IFDESCRSIZE);
   3302 				return error;
   3303 			}
   3304 		}
   3305 
   3306 		if (ifp->if_description != NULL)
   3307 			kmem_free(ifp->if_description, IFDESCRSIZE);
   3308 
   3309 		ifp->if_description = descr;
   3310 		break;
   3311 
   3312 	case SIOCGIFDESCR:
   3313 		ifr = data;
   3314 		descr = ifp->if_description;
   3315 
   3316 		if (descr == NULL)
   3317 			return ENOMSG;
   3318 
   3319 		if (ifr->ifr_buflen < IFDESCRSIZE)
   3320 			return EINVAL;
   3321 
   3322 		error = copyout(descr, ifr->ifr_buf, IFDESCRSIZE);
   3323 		if (error)
   3324 			return error;
   3325 		break;
   3326 
   3327 	default:
   3328 		return ENOTTY;
   3329 	}
   3330 	return 0;
   3331 }
   3332 
   3333 int
   3334 ifaddrpref_ioctl(struct socket *so, u_long cmd, void *data, struct ifnet *ifp)
   3335 {
   3336 	struct if_addrprefreq *ifap = (struct if_addrprefreq *)data;
   3337 	struct ifaddr *ifa;
   3338 	const struct sockaddr *any, *sa;
   3339 	union {
   3340 		struct sockaddr sa;
   3341 		struct sockaddr_storage ss;
   3342 	} u, v;
   3343 	int s, error = 0;
   3344 
   3345 	switch (cmd) {
   3346 	case SIOCSIFADDRPREF:
   3347 		error = kauth_authorize_network(kauth_cred_get(),
   3348 		    KAUTH_NETWORK_INTERFACE,
   3349 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, KAUTH_ARG(cmd),
   3350 		    NULL);
   3351 		if (error)
   3352 			return error;
   3353 		break;
   3354 	case SIOCGIFADDRPREF:
   3355 		break;
   3356 	default:
   3357 		return EOPNOTSUPP;
   3358 	}
   3359 
   3360 	/* sanity checks */
   3361 	if (data == NULL || ifp == NULL) {
   3362 		panic("invalid argument to %s", __func__);
   3363 		/*NOTREACHED*/
   3364 	}
   3365 
   3366 	/* address must be specified on ADD and DELETE */
   3367 	sa = sstocsa(&ifap->ifap_addr);
   3368 	if (sa->sa_family != sofamily(so))
   3369 		return EINVAL;
   3370 	if ((any = sockaddr_any(sa)) == NULL || sa->sa_len != any->sa_len)
   3371 		return EINVAL;
   3372 
   3373 	sockaddr_externalize(&v.sa, sizeof(v.ss), sa);
   3374 
   3375 	s = pserialize_read_enter();
   3376 	IFADDR_READER_FOREACH(ifa, ifp) {
   3377 		if (ifa->ifa_addr->sa_family != sa->sa_family)
   3378 			continue;
   3379 		sockaddr_externalize(&u.sa, sizeof(u.ss), ifa->ifa_addr);
   3380 		if (sockaddr_cmp(&u.sa, &v.sa) == 0)
   3381 			break;
   3382 	}
   3383 	if (ifa == NULL) {
   3384 		error = EADDRNOTAVAIL;
   3385 		goto out;
   3386 	}
   3387 
   3388 	switch (cmd) {
   3389 	case SIOCSIFADDRPREF:
   3390 		ifa->ifa_preference = ifap->ifap_preference;
   3391 		goto out;
   3392 	case SIOCGIFADDRPREF:
   3393 		/* fill in the if_laddrreq structure */
   3394 		(void)sockaddr_copy(sstosa(&ifap->ifap_addr),
   3395 		    sizeof(ifap->ifap_addr), ifa->ifa_addr);
   3396 		ifap->ifap_preference = ifa->ifa_preference;
   3397 		goto out;
   3398 	default:
   3399 		error = EOPNOTSUPP;
   3400 	}
   3401 out:
   3402 	pserialize_read_exit(s);
   3403 	return error;
   3404 }
   3405 
   3406 /*
   3407  * Interface ioctls.
   3408  */
   3409 static int
   3410 doifioctl(struct socket *so, u_long cmd, void *data, struct lwp *l)
   3411 {
   3412 	struct ifnet *ifp;
   3413 	struct ifreq *ifr;
   3414 	int error = 0;
   3415 	u_long ocmd = cmd;
   3416 	u_short oif_flags;
   3417 	struct ifreq ifrb;
   3418 	struct oifreq *oifr = NULL;
   3419 	int r;
   3420 	struct psref psref;
   3421 	bool do_if43_post = false;
   3422 	bool do_ifm80_post = false;
   3423 
   3424 	switch (cmd) {
   3425 	case SIOCGIFCONF:
   3426 		return ifconf(cmd, data);
   3427 	case SIOCINITIFADDR:
   3428 		return EPERM;
   3429 	default:
   3430 		MODULE_HOOK_CALL(uipc_syscalls_40_hook, (cmd, data), enosys(),
   3431 		    error);
   3432 		if (error != ENOSYS)
   3433 			return error;
   3434 		MODULE_HOOK_CALL(uipc_syscalls_50_hook, (l, cmd, data),
   3435 		    enosys(), error);
   3436 		if (error != ENOSYS)
   3437 			return error;
   3438 		error = 0;
   3439 		break;
   3440 	}
   3441 
   3442 	ifr = data;
   3443 	/* Pre-conversion */
   3444 	MODULE_HOOK_CALL(if_cvtcmd_43_hook, (&cmd, ocmd), enosys(), error);
   3445 	if (cmd != ocmd) {
   3446 		oifr = data;
   3447 		data = ifr = &ifrb;
   3448 		IFREQO2N_43(oifr, ifr);
   3449 		do_if43_post = true;
   3450 	}
   3451 	MODULE_HOOK_CALL(ifmedia_80_pre_hook, (ifr, &cmd, &do_ifm80_post),
   3452 	    enosys(), error);
   3453 
   3454 	switch (cmd) {
   3455 	case SIOCIFCREATE:
   3456 	case SIOCIFDESTROY: {
   3457 		const int bound = curlwp_bind();
   3458 		if (l != NULL) {
   3459 			ifp = if_get(ifr->ifr_name, &psref);
   3460 			error = kauth_authorize_network(l->l_cred,
   3461 			    KAUTH_NETWORK_INTERFACE,
   3462 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
   3463 			    KAUTH_ARG(cmd), NULL);
   3464 			if (ifp != NULL)
   3465 				if_put(ifp, &psref);
   3466 			if (error != 0) {
   3467 				curlwp_bindx(bound);
   3468 				return error;
   3469 			}
   3470 		}
   3471 		KERNEL_LOCK_UNLESS_NET_MPSAFE();
   3472 		mutex_enter(&if_clone_mtx);
   3473 		r = (cmd == SIOCIFCREATE) ?
   3474 			if_clone_create(ifr->ifr_name) :
   3475 			if_clone_destroy(ifr->ifr_name);
   3476 		mutex_exit(&if_clone_mtx);
   3477 		KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
   3478 		curlwp_bindx(bound);
   3479 		return r;
   3480 	    }
   3481 	case SIOCIFGCLONERS: {
   3482 		struct if_clonereq *req = (struct if_clonereq *)data;
   3483 		return if_clone_list(req->ifcr_count, req->ifcr_buffer,
   3484 		    &req->ifcr_total);
   3485 	    }
   3486 	}
   3487 
   3488 	if ((cmd & IOC_IN) == 0 || IOCPARM_LEN(cmd) < sizeof(ifr->ifr_name))
   3489 		return EINVAL;
   3490 
   3491 	const int bound = curlwp_bind();
   3492 	ifp = if_get(ifr->ifr_name, &psref);
   3493 	if (ifp == NULL) {
   3494 		curlwp_bindx(bound);
   3495 		return ENXIO;
   3496 	}
   3497 
   3498 	switch (cmd) {
   3499 	case SIOCALIFADDR:
   3500 	case SIOCDLIFADDR:
   3501 	case SIOCSIFADDRPREF:
   3502 	case SIOCSIFFLAGS:
   3503 	case SIOCSIFCAP:
   3504 	case SIOCSIFMETRIC:
   3505 	case SIOCZIFDATA:
   3506 	case SIOCSIFMTU:
   3507 	case SIOCSIFPHYADDR:
   3508 	case SIOCDIFPHYADDR:
   3509 #ifdef INET6
   3510 	case SIOCSIFPHYADDR_IN6:
   3511 #endif
   3512 	case SIOCSLIFPHYADDR:
   3513 	case SIOCADDMULTI:
   3514 	case SIOCDELMULTI:
   3515 	case SIOCSETHERCAP:
   3516 	case SIOCSIFMEDIA:
   3517 	case SIOCSDRVSPEC:
   3518 	case SIOCG80211:
   3519 	case SIOCS80211:
   3520 	case SIOCS80211NWID:
   3521 	case SIOCS80211NWKEY:
   3522 	case SIOCS80211POWER:
   3523 	case SIOCS80211BSSID:
   3524 	case SIOCS80211CHANNEL:
   3525 	case SIOCSLINKSTR:
   3526 		if (l != NULL) {
   3527 			error = kauth_authorize_network(l->l_cred,
   3528 			    KAUTH_NETWORK_INTERFACE,
   3529 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
   3530 			    KAUTH_ARG(cmd), NULL);
   3531 			if (error != 0)
   3532 				goto out;
   3533 		}
   3534 	}
   3535 
   3536 	oif_flags = ifp->if_flags;
   3537 
   3538 	KERNEL_LOCK_UNLESS_IFP_MPSAFE(ifp);
   3539 	IFNET_LOCK(ifp);
   3540 
   3541 	error = if_ioctl(ifp, cmd, data);
   3542 	if (error != ENOTTY)
   3543 		;
   3544 	else if (so->so_proto == NULL)
   3545 		error = EOPNOTSUPP;
   3546 	else {
   3547 		KERNEL_LOCK_IF_IFP_MPSAFE(ifp);
   3548 		MODULE_HOOK_CALL(if_ifioctl_43_hook,
   3549 			     (so, ocmd, cmd, data, l), enosys(), error);
   3550 		if (error == ENOSYS)
   3551 			error = (*so->so_proto->pr_usrreqs->pr_ioctl)(so,
   3552 			    cmd, data, ifp);
   3553 		KERNEL_UNLOCK_IF_IFP_MPSAFE(ifp);
   3554 	}
   3555 
   3556 	if (((oif_flags ^ ifp->if_flags) & IFF_UP) != 0) {
   3557 		if ((ifp->if_flags & IFF_UP) != 0) {
   3558 			const int s = splsoftnet();
   3559 			if_up_locked(ifp);
   3560 			splx(s);
   3561 		}
   3562 	}
   3563 
   3564 	/* Post-conversion */
   3565 	if (do_ifm80_post && (error == 0))
   3566 		MODULE_HOOK_CALL(ifmedia_80_post_hook, (ifr, cmd),
   3567 		    enosys(), error);
   3568 	if (do_if43_post)
   3569 		IFREQN2O_43(oifr, ifr);
   3570 
   3571 	IFNET_UNLOCK(ifp);
   3572 	KERNEL_UNLOCK_UNLESS_IFP_MPSAFE(ifp);
   3573 out:
   3574 	if_put(ifp, &psref);
   3575 	curlwp_bindx(bound);
   3576 	return error;
   3577 }
   3578 
   3579 /*
   3580  * Return interface configuration
   3581  * of system.  List may be used
   3582  * in later ioctl's (above) to get
   3583  * other information.
   3584  *
   3585  * Each record is a struct ifreq.  Before the addition of
   3586  * sockaddr_storage, the API rule was that sockaddr flavors that did
   3587  * not fit would extend beyond the struct ifreq, with the next struct
   3588  * ifreq starting sa_len beyond the struct sockaddr.  Because the
   3589  * union in struct ifreq includes struct sockaddr_storage, every kind
   3590  * of sockaddr must fit.  Thus, there are no longer any overlength
   3591  * records.
   3592  *
   3593  * Records are added to the user buffer if they fit, and ifc_len is
   3594  * adjusted to the length that was written.  Thus, the user is only
   3595  * assured of getting the complete list if ifc_len on return is at
   3596  * least sizeof(struct ifreq) less than it was on entry.
   3597  *
   3598  * If the user buffer pointer is NULL, this routine copies no data and
   3599  * returns the amount of space that would be needed.
   3600  *
   3601  * Invariants:
   3602  * ifrp points to the next part of the user's buffer to be used.  If
   3603  * ifrp != NULL, space holds the number of bytes remaining that we may
   3604  * write at ifrp.  Otherwise, space holds the number of bytes that
   3605  * would have been written had there been adequate space.
   3606  */
   3607 /*ARGSUSED*/
   3608 static int
   3609 ifconf(u_long cmd, void *data)
   3610 {
   3611 	struct ifconf *ifc = (struct ifconf *)data;
   3612 	struct ifnet *ifp;
   3613 	struct ifaddr *ifa;
   3614 	struct ifreq ifr, *ifrp = NULL;
   3615 	int space = 0, error = 0;
   3616 	const int sz = (int)sizeof(struct ifreq);
   3617 	const bool docopy = ifc->ifc_req != NULL;
   3618 	struct psref psref;
   3619 
   3620 	if (docopy) {
   3621 		if (ifc->ifc_len < 0)
   3622 			return EINVAL;
   3623 
   3624 		space = ifc->ifc_len;
   3625 		ifrp = ifc->ifc_req;
   3626 	}
   3627 	memset(&ifr, 0, sizeof(ifr));
   3628 
   3629 	const int bound = curlwp_bind();
   3630 	int s = pserialize_read_enter();
   3631 	IFNET_READER_FOREACH(ifp) {
   3632 		psref_acquire(&psref, &ifp->if_psref, ifnet_psref_class);
   3633 		pserialize_read_exit(s);
   3634 
   3635 		(void)strncpy(ifr.ifr_name, ifp->if_xname,
   3636 		    sizeof(ifr.ifr_name));
   3637 		if (ifr.ifr_name[sizeof(ifr.ifr_name) - 1] != '\0') {
   3638 			error = ENAMETOOLONG;
   3639 			goto release_exit;
   3640 		}
   3641 		if (IFADDR_READER_EMPTY(ifp)) {
   3642 			/* Interface with no addresses - send zero sockaddr. */
   3643 			memset(&ifr.ifr_addr, 0, sizeof(ifr.ifr_addr));
   3644 			if (!docopy) {
   3645 				space += sz;
   3646 				goto next;
   3647 			}
   3648 			if (space >= sz) {
   3649 				error = copyout(&ifr, ifrp, sz);
   3650 				if (error != 0)
   3651 					goto release_exit;
   3652 				ifrp++;
   3653 				space -= sz;
   3654 			}
   3655 		}
   3656 
   3657 		s = pserialize_read_enter();
   3658 		IFADDR_READER_FOREACH(ifa, ifp) {
   3659 			struct sockaddr *sa = ifa->ifa_addr;
   3660 			/* all sockaddrs must fit in sockaddr_storage */
   3661 			KASSERT(sa->sa_len <= sizeof(ifr.ifr_ifru));
   3662 
   3663 			if (!docopy) {
   3664 				space += sz;
   3665 				continue;
   3666 			}
   3667 			memcpy(&ifr.ifr_space, sa, sa->sa_len);
   3668 			pserialize_read_exit(s);
   3669 
   3670 			if (space >= sz) {
   3671 				error = copyout(&ifr, ifrp, sz);
   3672 				if (error != 0)
   3673 					goto release_exit;
   3674 				ifrp++; space -= sz;
   3675 			}
   3676 			s = pserialize_read_enter();
   3677 		}
   3678 		pserialize_read_exit(s);
   3679 
   3680 next:
   3681 		s = pserialize_read_enter();
   3682 		psref_release(&psref, &ifp->if_psref, ifnet_psref_class);
   3683 	}
   3684 	pserialize_read_exit(s);
   3685 	curlwp_bindx(bound);
   3686 
   3687 	if (docopy) {
   3688 		KASSERT(0 <= space && space <= ifc->ifc_len);
   3689 		ifc->ifc_len -= space;
   3690 	} else {
   3691 		KASSERT(space >= 0);
   3692 		ifc->ifc_len = space;
   3693 	}
   3694 	return 0;
   3695 
   3696 release_exit:
   3697 	psref_release(&psref, &ifp->if_psref, ifnet_psref_class);
   3698 	curlwp_bindx(bound);
   3699 	return error;
   3700 }
   3701 
   3702 int
   3703 ifreq_setaddr(u_long cmd, struct ifreq *ifr, const struct sockaddr *sa)
   3704 {
   3705 	uint8_t len = sizeof(ifr->ifr_ifru.ifru_space);
   3706 	struct ifreq ifrb;
   3707 	struct oifreq *oifr = NULL;
   3708 	u_long ocmd = cmd;
   3709 	int hook;
   3710 
   3711 	MODULE_HOOK_CALL(if_cvtcmd_43_hook, (&cmd, ocmd), enosys(), hook);
   3712 	if (hook != ENOSYS) {
   3713 		if (cmd != ocmd) {
   3714 			oifr = (struct oifreq *)(void *)ifr;
   3715 			ifr = &ifrb;
   3716 			IFREQO2N_43(oifr, ifr);
   3717 				len = sizeof(oifr->ifr_addr);
   3718 		}
   3719 	}
   3720 
   3721 	if (len < sa->sa_len)
   3722 		return EFBIG;
   3723 
   3724 	memset(&ifr->ifr_addr, 0, len);
   3725 	sockaddr_copy(&ifr->ifr_addr, len, sa);
   3726 
   3727 	if (cmd != ocmd)
   3728 		IFREQN2O_43(oifr, ifr);
   3729 	return 0;
   3730 }
   3731 
   3732 /*
   3733  * wrapper function for the drivers which doesn't have if_transmit().
   3734  */
   3735 static int
   3736 if_transmit(struct ifnet *ifp, struct mbuf *m)
   3737 {
   3738 	int error;
   3739 	size_t pktlen = m->m_pkthdr.len;
   3740 	bool mcast = (m->m_flags & M_MCAST) != 0;
   3741 
   3742 	const int s = splnet();
   3743 
   3744 	IFQ_ENQUEUE(&ifp->if_snd, m, error);
   3745 	if (error != 0) {
   3746 		/* mbuf is already freed */
   3747 		goto out;
   3748 	}
   3749 
   3750 	net_stat_ref_t nsr = IF_STAT_GETREF(ifp);
   3751 	if_statadd_ref(ifp, nsr, if_obytes, pktlen);
   3752 	if (mcast)
   3753 		if_statinc_ref(ifp, nsr, if_omcasts);
   3754 	IF_STAT_PUTREF(ifp);
   3755 
   3756 	if ((ifp->if_flags & IFF_OACTIVE) == 0)
   3757 		if_start_lock(ifp);
   3758 out:
   3759 	splx(s);
   3760 
   3761 	return error;
   3762 }
   3763 
   3764 int
   3765 if_transmit_lock(struct ifnet *ifp, struct mbuf *m)
   3766 {
   3767 	int error;
   3768 
   3769 	kmsan_check_mbuf(m);
   3770 
   3771 #ifdef ALTQ
   3772 	KERNEL_LOCK(1, NULL);
   3773 	if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
   3774 		error = if_transmit(ifp, m);
   3775 		KERNEL_UNLOCK_ONE(NULL);
   3776 	} else {
   3777 		KERNEL_UNLOCK_ONE(NULL);
   3778 		error = (*ifp->if_transmit)(ifp, m);
   3779 		/* mbuf is already freed */
   3780 	}
   3781 #else /* !ALTQ */
   3782 	error = (*ifp->if_transmit)(ifp, m);
   3783 	/* mbuf is already freed */
   3784 #endif /* !ALTQ */
   3785 
   3786 	return error;
   3787 }
   3788 
   3789 /*
   3790  * Queue message on interface, and start output if interface
   3791  * not yet active.
   3792  */
   3793 int
   3794 ifq_enqueue(struct ifnet *ifp, struct mbuf *m)
   3795 {
   3796 
   3797 	return if_transmit_lock(ifp, m);
   3798 }
   3799 
   3800 /*
   3801  * Queue message on interface, possibly using a second fast queue
   3802  */
   3803 int
   3804 ifq_enqueue2(struct ifnet *ifp, struct ifqueue *ifq, struct mbuf *m)
   3805 {
   3806 	int error = 0;
   3807 
   3808 	if (ifq != NULL
   3809 #ifdef ALTQ
   3810 	    && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
   3811 #endif
   3812 	    ) {
   3813 		if (IF_QFULL(ifq)) {
   3814 			IF_DROP(&ifp->if_snd);
   3815 			m_freem(m);
   3816 			if (error == 0)
   3817 				error = ENOBUFS;
   3818 		} else
   3819 			IF_ENQUEUE(ifq, m);
   3820 	} else
   3821 		IFQ_ENQUEUE(&ifp->if_snd, m, error);
   3822 	if (error != 0) {
   3823 		if_statinc(ifp, if_oerrors);
   3824 		return error;
   3825 	}
   3826 	return 0;
   3827 }
   3828 
   3829 int
   3830 if_addr_init(ifnet_t *ifp, struct ifaddr *ifa, const bool src)
   3831 {
   3832 	int rc;
   3833 
   3834 	KASSERT(IFNET_LOCKED(ifp));
   3835 	if (ifp->if_initaddr != NULL)
   3836 		rc = (*ifp->if_initaddr)(ifp, ifa, src);
   3837 	else if (src || (rc = if_ioctl(ifp, SIOCSIFDSTADDR, ifa)) == ENOTTY)
   3838 		rc = if_ioctl(ifp, SIOCINITIFADDR, ifa);
   3839 
   3840 	return rc;
   3841 }
   3842 
   3843 int
   3844 if_do_dad(struct ifnet *ifp)
   3845 {
   3846 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
   3847 		return 0;
   3848 
   3849 	switch (ifp->if_type) {
   3850 	case IFT_FAITH:
   3851 		/*
   3852 		 * These interfaces do not have the IFF_LOOPBACK flag,
   3853 		 * but loop packets back.  We do not have to do DAD on such
   3854 		 * interfaces.  We should even omit it, because loop-backed
   3855 		 * responses would confuse the DAD procedure.
   3856 		 */
   3857 		return 0;
   3858 	default:
   3859 		/*
   3860 		 * Our DAD routine requires the interface up and running.
   3861 		 * However, some interfaces can be up before the RUNNING
   3862 		 * status.  Additionally, users may try to assign addresses
   3863 		 * before the interface becomes up (or running).
   3864 		 * We simply skip DAD in such a case as a work around.
   3865 		 * XXX: we should rather mark "tentative" on such addresses,
   3866 		 * and do DAD after the interface becomes ready.
   3867 		 */
   3868 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
   3869 		    (IFF_UP | IFF_RUNNING))
   3870 			return 0;
   3871 
   3872 		return 1;
   3873 	}
   3874 }
   3875 
   3876 /*
   3877  * if_flags_set(ifp, flags)
   3878  *
   3879  *	Ask ifp to change ifp->if_flags to flags, as if with the
   3880  *	SIOCSIFFLAGS ioctl command.
   3881  *
   3882  *	May sleep.  Caller must hold ifp->if_ioctl_lock, a.k.a
   3883  *	IFNET_LOCK.
   3884  */
   3885 int
   3886 if_flags_set(ifnet_t *ifp, const u_short flags)
   3887 {
   3888 	int rc;
   3889 
   3890 	KASSERT(IFNET_LOCKED(ifp));
   3891 
   3892 	if (ifp->if_setflags != NULL)
   3893 		rc = (*ifp->if_setflags)(ifp, flags);
   3894 	else {
   3895 		u_short cantflags, chgdflags;
   3896 		struct ifreq ifr;
   3897 
   3898 		chgdflags = ifp->if_flags ^ flags;
   3899 		cantflags = chgdflags & IFF_CANTCHANGE;
   3900 
   3901 		if (cantflags != 0)
   3902 			ifp->if_flags ^= cantflags;
   3903 
   3904 		/*
   3905 		 * Traditionally, we do not call if_ioctl after
   3906 		 * setting/clearing only IFF_PROMISC if the interface
   3907 		 * isn't IFF_UP.  Uphold that tradition.
   3908 		 */
   3909 		if (chgdflags == IFF_PROMISC && (ifp->if_flags & IFF_UP) == 0)
   3910 			return 0;
   3911 
   3912 		memset(&ifr, 0, sizeof(ifr));
   3913 
   3914 		ifr.ifr_flags = flags & ~IFF_CANTCHANGE;
   3915 		rc = if_ioctl(ifp, SIOCSIFFLAGS, &ifr);
   3916 
   3917 		if (rc != 0 && cantflags != 0)
   3918 			ifp->if_flags ^= cantflags;
   3919 	}
   3920 
   3921 	return rc;
   3922 }
   3923 
   3924 /*
   3925  * if_mcast_op(ifp, cmd, sa)
   3926  *
   3927  *	Apply a multicast command, SIOCADDMULTI/SIOCDELMULTI, to the
   3928  *	interface.  Returns 0 on success, nonzero errno(3) number on
   3929  *	failure.
   3930  *
   3931  *	May sleep.
   3932  *
   3933  *	Use this, not if_ioctl, for the multicast commands.
   3934  */
   3935 int
   3936 if_mcast_op(ifnet_t *ifp, const unsigned long cmd, const struct sockaddr *sa)
   3937 {
   3938 	int rc;
   3939 	struct ifreq ifr;
   3940 
   3941 	switch (cmd) {
   3942 	case SIOCADDMULTI:
   3943 	case SIOCDELMULTI:
   3944 		break;
   3945 	default:
   3946 		panic("invalid ifnet multicast command: 0x%lx", cmd);
   3947 	}
   3948 
   3949 	ifreq_setaddr(cmd, &ifr, sa);
   3950 	rc = if_ioctl(ifp, cmd, &ifr);
   3951 
   3952 	return rc;
   3953 }
   3954 
   3955 static void
   3956 sysctl_sndq_setup(struct sysctllog **clog, const char *ifname,
   3957     struct ifaltq *ifq)
   3958 {
   3959 	const struct sysctlnode *cnode, *rnode;
   3960 
   3961 	if (sysctl_createv(clog, 0, NULL, &rnode,
   3962 		       CTLFLAG_PERMANENT,
   3963 		       CTLTYPE_NODE, "interfaces",
   3964 		       SYSCTL_DESCR("Per-interface controls"),
   3965 		       NULL, 0, NULL, 0,
   3966 		       CTL_NET, CTL_CREATE, CTL_EOL) != 0)
   3967 		goto bad;
   3968 
   3969 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   3970 		       CTLFLAG_PERMANENT,
   3971 		       CTLTYPE_NODE, ifname,
   3972 		       SYSCTL_DESCR("Interface controls"),
   3973 		       NULL, 0, NULL, 0,
   3974 		       CTL_CREATE, CTL_EOL) != 0)
   3975 		goto bad;
   3976 
   3977 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   3978 		       CTLFLAG_PERMANENT,
   3979 		       CTLTYPE_NODE, "sndq",
   3980 		       SYSCTL_DESCR("Interface output queue controls"),
   3981 		       NULL, 0, NULL, 0,
   3982 		       CTL_CREATE, CTL_EOL) != 0)
   3983 		goto bad;
   3984 
   3985 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   3986 		       CTLFLAG_PERMANENT,
   3987 		       CTLTYPE_INT, "len",
   3988 		       SYSCTL_DESCR("Current output queue length"),
   3989 		       NULL, 0, &ifq->ifq_len, 0,
   3990 		       CTL_CREATE, CTL_EOL) != 0)
   3991 		goto bad;
   3992 
   3993 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   3994 		       CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   3995 		       CTLTYPE_INT, "maxlen",
   3996 		       SYSCTL_DESCR("Maximum allowed output queue length"),
   3997 		       NULL, 0, &ifq->ifq_maxlen, 0,
   3998 		       CTL_CREATE, CTL_EOL) != 0)
   3999 		goto bad;
   4000 
   4001 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   4002 		       CTLFLAG_PERMANENT,
   4003 		       CTLTYPE_QUAD, "drops",
   4004 		       SYSCTL_DESCR("Packets dropped due to full output queue"),
   4005 		       NULL, 0, &ifq->ifq_drops, 0,
   4006 		       CTL_CREATE, CTL_EOL) != 0)
   4007 		goto bad;
   4008 
   4009 	return;
   4010 bad:
   4011 	printf("%s: could not attach sysctl nodes\n", ifname);
   4012 	return;
   4013 }
   4014 
   4015 static int
   4016 if_sdl_sysctl(SYSCTLFN_ARGS)
   4017 {
   4018 	struct ifnet *ifp;
   4019 	const struct sockaddr_dl *sdl;
   4020 	struct psref psref;
   4021 	int error = 0;
   4022 
   4023 	if (namelen != 1)
   4024 		return EINVAL;
   4025 
   4026 	const int bound = curlwp_bind();
   4027 	ifp = if_get_byindex(name[0], &psref);
   4028 	if (ifp == NULL) {
   4029 		error = ENODEV;
   4030 		goto out0;
   4031 	}
   4032 
   4033 	sdl = ifp->if_sadl;
   4034 	if (sdl == NULL) {
   4035 		*oldlenp = 0;
   4036 		goto out1;
   4037 	}
   4038 
   4039 	if (oldp == NULL) {
   4040 		*oldlenp = sdl->sdl_alen;
   4041 		goto out1;
   4042 	}
   4043 
   4044 	if (*oldlenp >= sdl->sdl_alen)
   4045 		*oldlenp = sdl->sdl_alen;
   4046 	error = sysctl_copyout(l, &sdl->sdl_data[sdl->sdl_nlen],
   4047 	    oldp, *oldlenp);
   4048 out1:
   4049 	if_put(ifp, &psref);
   4050 out0:
   4051 	curlwp_bindx(bound);
   4052 	return error;
   4053 }
   4054 
   4055 static void
   4056 if_sysctl_setup(struct sysctllog **clog)
   4057 {
   4058 	const struct sysctlnode *rnode = NULL;
   4059 
   4060 	sysctl_createv(clog, 0, NULL, &rnode,
   4061 		       CTLFLAG_PERMANENT,
   4062 		       CTLTYPE_NODE, "sdl",
   4063 		       SYSCTL_DESCR("Get active link-layer address"),
   4064 		       if_sdl_sysctl, 0, NULL, 0,
   4065 		       CTL_NET, CTL_CREATE, CTL_EOL);
   4066 }
   4067