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