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