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