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