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