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