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