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