Home | History | Annotate | Line # | Download | only in net
if.c revision 1.271
      1 /*	$NetBSD: if.c,v 1.271 2014/01/03 12:49:59 pooka 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.271 2014/01/03 12:49:59 pooka Exp $");
     94 
     95 #include "opt_inet.h"
     96 
     97 #include "opt_atalk.h"
     98 #include "opt_natm.h"
     99 
    100 #include <sys/param.h>
    101 #include <sys/mbuf.h>
    102 #include <sys/systm.h>
    103 #include <sys/callout.h>
    104 #include <sys/proc.h>
    105 #include <sys/socket.h>
    106 #include <sys/socketvar.h>
    107 #include <sys/domain.h>
    108 #include <sys/protosw.h>
    109 #include <sys/kernel.h>
    110 #include <sys/ioctl.h>
    111 #include <sys/sysctl.h>
    112 #include <sys/syslog.h>
    113 #include <sys/kauth.h>
    114 #include <sys/kmem.h>
    115 
    116 #include <net/if.h>
    117 #include <net/if_dl.h>
    118 #include <net/if_ether.h>
    119 #include <net/if_media.h>
    120 #include <net80211/ieee80211.h>
    121 #include <net80211/ieee80211_ioctl.h>
    122 #include <net/if_types.h>
    123 #include <net/radix.h>
    124 #include <net/route.h>
    125 #include <net/netisr.h>
    126 #include <sys/module.h>
    127 #ifdef NETATALK
    128 #include <netatalk/at_extern.h>
    129 #include <netatalk/at.h>
    130 #endif
    131 #include <net/pfil.h>
    132 
    133 #ifdef INET6
    134 #include <netinet/in.h>
    135 #include <netinet6/in6_var.h>
    136 #include <netinet6/nd6.h>
    137 #endif
    138 
    139 #include "carp.h"
    140 #if NCARP > 0
    141 #include <netinet/ip_carp.h>
    142 #endif
    143 
    144 #include <compat/sys/sockio.h>
    145 #include <compat/sys/socket.h>
    146 
    147 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
    148 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
    149 
    150 int	ifqmaxlen = IFQ_MAXLEN;
    151 callout_t if_slowtimo_ch;
    152 
    153 int netisr;			/* scheduling bits for network */
    154 
    155 static int	if_rt_walktree(struct rtentry *, void *);
    156 
    157 static struct if_clone *if_clone_lookup(const char *, int *);
    158 static int	if_clone_list(struct if_clonereq *);
    159 
    160 static LIST_HEAD(, if_clone) if_cloners = LIST_HEAD_INITIALIZER(if_cloners);
    161 static int if_cloners_count;
    162 
    163 static uint64_t index_gen;
    164 static kmutex_t index_gen_mtx;
    165 
    166 /* Packet filtering hook for interfaces. */
    167 pfil_head_t *	if_pfil;
    168 
    169 static kauth_listener_t if_listener;
    170 
    171 static int ifioctl_attach(struct ifnet *);
    172 static void ifioctl_detach(struct ifnet *);
    173 static void ifnet_lock_enter(struct ifnet_lock *);
    174 static void ifnet_lock_exit(struct ifnet_lock *);
    175 static void if_detach_queues(struct ifnet *, struct ifqueue *);
    176 static void sysctl_sndq_setup(struct sysctllog **, const char *,
    177     struct ifaltq *);
    178 
    179 #if defined(INET) || defined(INET6)
    180 static void sysctl_net_ifq_setup(struct sysctllog **, int, const char *,
    181 				 int, const char *, int, struct ifqueue *);
    182 #endif
    183 
    184 static int
    185 if_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    186     void *arg0, void *arg1, void *arg2, void *arg3)
    187 {
    188 	int result;
    189 	enum kauth_network_req req;
    190 
    191 	result = KAUTH_RESULT_DEFER;
    192 	req = (enum kauth_network_req)arg1;
    193 
    194 	if (action != KAUTH_NETWORK_INTERFACE)
    195 		return result;
    196 
    197 	if ((req == KAUTH_REQ_NETWORK_INTERFACE_GET) ||
    198 	    (req == KAUTH_REQ_NETWORK_INTERFACE_SET))
    199 		result = KAUTH_RESULT_ALLOW;
    200 
    201 	return result;
    202 }
    203 
    204 /*
    205  * Network interface utility routines.
    206  *
    207  * Routines with ifa_ifwith* names take sockaddr *'s as
    208  * parameters.
    209  */
    210 void
    211 ifinit(void)
    212 {
    213 #ifdef INET
    214 	{extern struct ifqueue ipintrq;
    215 	sysctl_net_ifq_setup(NULL, PF_INET, "inet", IPPROTO_IP, "ip",
    216 			     IPCTL_IFQ, &ipintrq);}
    217 #endif /* INET */
    218 #ifdef INET6
    219 	{extern struct ifqueue ip6intrq;
    220 	sysctl_net_ifq_setup(NULL, PF_INET6, "inet6", IPPROTO_IPV6, "ip6",
    221 			     IPV6CTL_IFQ, &ip6intrq);}
    222 #endif /* INET6 */
    223 
    224 	callout_init(&if_slowtimo_ch, 0);
    225 	if_slowtimo(NULL);
    226 
    227 	if_listener = kauth_listen_scope(KAUTH_SCOPE_NETWORK,
    228 	    if_listener_cb, NULL);
    229 }
    230 
    231 /*
    232  * XXX Initialization before configure().
    233  * XXX hack to get pfil_add_hook working in autoconf.
    234  */
    235 void
    236 ifinit1(void)
    237 {
    238 	mutex_init(&index_gen_mtx, MUTEX_DEFAULT, IPL_NONE);
    239 	if_pfil = pfil_head_create(PFIL_TYPE_IFNET, NULL);
    240 	KASSERT(if_pfil != NULL);
    241 }
    242 
    243 struct ifnet *
    244 if_alloc(u_char type)
    245 {
    246 	return malloc(sizeof(struct ifnet), M_DEVBUF, M_WAITOK|M_ZERO);
    247 }
    248 
    249 void
    250 if_free(struct ifnet *ifp)
    251 {
    252 	free(ifp, M_DEVBUF);
    253 }
    254 
    255 void
    256 if_initname(struct ifnet *ifp, const char *name, int unit)
    257 {
    258 	(void)snprintf(ifp->if_xname, sizeof(ifp->if_xname),
    259 	    "%s%d", name, unit);
    260 }
    261 
    262 /*
    263  * Null routines used while an interface is going away.  These routines
    264  * just return an error.
    265  */
    266 
    267 int
    268 if_nulloutput(struct ifnet *ifp, struct mbuf *m,
    269     const struct sockaddr *so, struct rtentry *rt)
    270 {
    271 
    272 	return ENXIO;
    273 }
    274 
    275 void
    276 if_nullinput(struct ifnet *ifp, struct mbuf *m)
    277 {
    278 
    279 	/* Nothing. */
    280 }
    281 
    282 void
    283 if_nullstart(struct ifnet *ifp)
    284 {
    285 
    286 	/* Nothing. */
    287 }
    288 
    289 int
    290 if_nullioctl(struct ifnet *ifp, u_long cmd, void *data)
    291 {
    292 
    293 	/* Wake ifioctl_detach(), who may wait for all threads to
    294 	 * quit the critical section.
    295 	 */
    296 	cv_signal(&ifp->if_ioctl_lock->il_emptied);
    297 	return ENXIO;
    298 }
    299 
    300 int
    301 if_nullinit(struct ifnet *ifp)
    302 {
    303 
    304 	return ENXIO;
    305 }
    306 
    307 void
    308 if_nullstop(struct ifnet *ifp, int disable)
    309 {
    310 
    311 	/* Nothing. */
    312 }
    313 
    314 void
    315 if_nullwatchdog(struct ifnet *ifp)
    316 {
    317 
    318 	/* Nothing. */
    319 }
    320 
    321 void
    322 if_nulldrain(struct ifnet *ifp)
    323 {
    324 
    325 	/* Nothing. */
    326 }
    327 
    328 static u_int if_index = 1;
    329 struct ifnet_head ifnet;
    330 size_t if_indexlim = 0;
    331 struct ifaddr **ifnet_addrs = NULL;
    332 struct ifnet **ifindex2ifnet = NULL;
    333 struct ifnet *lo0ifp;
    334 
    335 void
    336 if_set_sadl(struct ifnet *ifp, const void *lla, u_char addrlen, bool factory)
    337 {
    338 	struct ifaddr *ifa;
    339 	struct sockaddr_dl *sdl;
    340 
    341 	ifp->if_addrlen = addrlen;
    342 	if_alloc_sadl(ifp);
    343 	ifa = ifp->if_dl;
    344 	sdl = satosdl(ifa->ifa_addr);
    345 
    346 	(void)sockaddr_dl_setaddr(sdl, sdl->sdl_len, lla, ifp->if_addrlen);
    347 	if (factory) {
    348 		ifp->if_hwdl = ifp->if_dl;
    349 		IFAREF(ifp->if_hwdl);
    350 	}
    351 	/* TBD routing socket */
    352 }
    353 
    354 struct ifaddr *
    355 if_dl_create(const struct ifnet *ifp, const struct sockaddr_dl **sdlp)
    356 {
    357 	unsigned socksize, ifasize;
    358 	int addrlen, namelen;
    359 	struct sockaddr_dl *mask, *sdl;
    360 	struct ifaddr *ifa;
    361 
    362 	namelen = strlen(ifp->if_xname);
    363 	addrlen = ifp->if_addrlen;
    364 	socksize = roundup(sockaddr_dl_measure(namelen, addrlen), sizeof(long));
    365 	ifasize = sizeof(*ifa) + 2 * socksize;
    366 	ifa = (struct ifaddr *)malloc(ifasize, M_IFADDR, M_WAITOK|M_ZERO);
    367 
    368 	sdl = (struct sockaddr_dl *)(ifa + 1);
    369 	mask = (struct sockaddr_dl *)(socksize + (char *)sdl);
    370 
    371 	sockaddr_dl_init(sdl, socksize, ifp->if_index, ifp->if_type,
    372 	    ifp->if_xname, namelen, NULL, addrlen);
    373 	mask->sdl_len = sockaddr_dl_measure(namelen, 0);
    374 	memset(&mask->sdl_data[0], 0xff, namelen);
    375 	ifa->ifa_rtrequest = link_rtrequest;
    376 	ifa->ifa_addr = (struct sockaddr *)sdl;
    377 	ifa->ifa_netmask = (struct sockaddr *)mask;
    378 
    379 	*sdlp = sdl;
    380 
    381 	return ifa;
    382 }
    383 
    384 static void
    385 if_sadl_setrefs(struct ifnet *ifp, struct ifaddr *ifa)
    386 {
    387 	const struct sockaddr_dl *sdl;
    388 	ifnet_addrs[ifp->if_index] = ifa;
    389 	IFAREF(ifa);
    390 	ifp->if_dl = ifa;
    391 	IFAREF(ifa);
    392 	sdl = satosdl(ifa->ifa_addr);
    393 	ifp->if_sadl = sdl;
    394 }
    395 
    396 /*
    397  * Allocate the link level name for the specified interface.  This
    398  * is an attachment helper.  It must be called after ifp->if_addrlen
    399  * is initialized, which may not be the case when if_attach() is
    400  * called.
    401  */
    402 void
    403 if_alloc_sadl(struct ifnet *ifp)
    404 {
    405 	struct ifaddr *ifa;
    406 	const struct sockaddr_dl *sdl;
    407 
    408 	/*
    409 	 * If the interface already has a link name, release it
    410 	 * now.  This is useful for interfaces that can change
    411 	 * link types, and thus switch link names often.
    412 	 */
    413 	if (ifp->if_sadl != NULL)
    414 		if_free_sadl(ifp);
    415 
    416 	ifa = if_dl_create(ifp, &sdl);
    417 
    418 	ifa_insert(ifp, ifa);
    419 	if_sadl_setrefs(ifp, ifa);
    420 }
    421 
    422 static void
    423 if_deactivate_sadl(struct ifnet *ifp)
    424 {
    425 	struct ifaddr *ifa;
    426 
    427 	KASSERT(ifp->if_dl != NULL);
    428 
    429 	ifa = ifp->if_dl;
    430 
    431 	ifp->if_sadl = NULL;
    432 
    433 	ifnet_addrs[ifp->if_index] = NULL;
    434 	IFAFREE(ifa);
    435 	ifp->if_dl = NULL;
    436 	IFAFREE(ifa);
    437 }
    438 
    439 void
    440 if_activate_sadl(struct ifnet *ifp, struct ifaddr *ifa,
    441     const struct sockaddr_dl *sdl)
    442 {
    443 	int s;
    444 
    445 	s = splnet();
    446 
    447 	if_deactivate_sadl(ifp);
    448 
    449 	if_sadl_setrefs(ifp, ifa);
    450 	IFADDR_FOREACH(ifa, ifp)
    451 		rtinit(ifa, RTM_LLINFO_UPD, 0);
    452 	splx(s);
    453 }
    454 
    455 /*
    456  * Free the link level name for the specified interface.  This is
    457  * a detach helper.  This is called from if_detach() or from
    458  * link layer type specific detach functions.
    459  */
    460 void
    461 if_free_sadl(struct ifnet *ifp)
    462 {
    463 	struct ifaddr *ifa;
    464 	int s;
    465 
    466 	ifa = ifnet_addrs[ifp->if_index];
    467 	if (ifa == NULL) {
    468 		KASSERT(ifp->if_sadl == NULL);
    469 		KASSERT(ifp->if_dl == NULL);
    470 		return;
    471 	}
    472 
    473 	KASSERT(ifp->if_sadl != NULL);
    474 	KASSERT(ifp->if_dl != NULL);
    475 
    476 	s = splnet();
    477 	rtinit(ifa, RTM_DELETE, 0);
    478 	ifa_remove(ifp, ifa);
    479 	if_deactivate_sadl(ifp);
    480 	if (ifp->if_hwdl == ifa) {
    481 		IFAFREE(ifa);
    482 		ifp->if_hwdl = NULL;
    483 	}
    484 	splx(s);
    485 }
    486 
    487 /*
    488  * Attach an interface to the
    489  * list of "active" interfaces.
    490  */
    491 void
    492 if_attach(struct ifnet *ifp)
    493 {
    494 	int indexlim = 0;
    495 
    496 	if (if_indexlim == 0) {
    497 		TAILQ_INIT(&ifnet);
    498 		if_indexlim = 8;
    499 	}
    500 	TAILQ_INIT(&ifp->if_addrlist);
    501 	TAILQ_INSERT_TAIL(&ifnet, ifp, if_list);
    502 
    503 	if (ifioctl_attach(ifp) != 0)
    504 		panic("%s: ifioctl_attach() failed", __func__);
    505 
    506 	mutex_enter(&index_gen_mtx);
    507 	ifp->if_index_gen = index_gen++;
    508 	mutex_exit(&index_gen_mtx);
    509 
    510 	ifp->if_index = if_index;
    511 	if (ifindex2ifnet == NULL)
    512 		if_index++;
    513 	else
    514 		while (ifp->if_index < if_indexlim &&
    515 		    ifindex2ifnet[ifp->if_index] != NULL) {
    516 			++if_index;
    517 			if (if_index == 0)
    518 				if_index = 1;
    519 			/*
    520 			 * If we hit USHRT_MAX, we skip back to 0 since
    521 			 * there are a number of places where the value
    522 			 * of if_index or if_index itself is compared
    523 			 * to or stored in an unsigned short.  By
    524 			 * jumping back, we won't botch those assignments
    525 			 * or comparisons.
    526 			 */
    527 			else if (if_index == USHRT_MAX) {
    528 				/*
    529 				 * However, if we have to jump back to
    530 				 * zero *twice* without finding an empty
    531 				 * slot in ifindex2ifnet[], then there
    532 				 * there are too many (>65535) interfaces.
    533 				 */
    534 				if (indexlim++)
    535 					panic("too many interfaces");
    536 				else
    537 					if_index = 1;
    538 			}
    539 			ifp->if_index = if_index;
    540 		}
    541 
    542 	/*
    543 	 * We have some arrays that should be indexed by if_index.
    544 	 * since if_index will grow dynamically, they should grow too.
    545 	 *	struct ifadd **ifnet_addrs
    546 	 *	struct ifnet **ifindex2ifnet
    547 	 */
    548 	if (ifnet_addrs == NULL || ifindex2ifnet == NULL ||
    549 	    ifp->if_index >= if_indexlim) {
    550 		size_t m, n, oldlim;
    551 		void *q;
    552 
    553 		oldlim = if_indexlim;
    554 		while (ifp->if_index >= if_indexlim)
    555 			if_indexlim <<= 1;
    556 
    557 		/* grow ifnet_addrs */
    558 		m = oldlim * sizeof(struct ifaddr *);
    559 		n = if_indexlim * sizeof(struct ifaddr *);
    560 		q = malloc(n, M_IFADDR, M_WAITOK|M_ZERO);
    561 		if (ifnet_addrs != NULL) {
    562 			memcpy(q, ifnet_addrs, m);
    563 			free(ifnet_addrs, M_IFADDR);
    564 		}
    565 		ifnet_addrs = (struct ifaddr **)q;
    566 
    567 		/* grow ifindex2ifnet */
    568 		m = oldlim * sizeof(struct ifnet *);
    569 		n = if_indexlim * sizeof(struct ifnet *);
    570 		q = malloc(n, M_IFADDR, M_WAITOK|M_ZERO);
    571 		if (ifindex2ifnet != NULL) {
    572 			memcpy(q, ifindex2ifnet, m);
    573 			free(ifindex2ifnet, M_IFADDR);
    574 		}
    575 		ifindex2ifnet = (struct ifnet **)q;
    576 	}
    577 
    578 	ifindex2ifnet[ifp->if_index] = ifp;
    579 
    580 	/*
    581 	 * Link level name is allocated later by a separate call to
    582 	 * if_alloc_sadl().
    583 	 */
    584 
    585 	if (ifp->if_snd.ifq_maxlen == 0)
    586 		ifp->if_snd.ifq_maxlen = ifqmaxlen;
    587 
    588 	sysctl_sndq_setup(&ifp->if_sysctl_log, ifp->if_xname, &ifp->if_snd);
    589 
    590 	ifp->if_broadcastaddr = 0; /* reliably crash if used uninitialized */
    591 
    592 	ifp->if_link_state = LINK_STATE_UNKNOWN;
    593 
    594 	ifp->if_capenable = 0;
    595 	ifp->if_csum_flags_tx = 0;
    596 	ifp->if_csum_flags_rx = 0;
    597 
    598 #ifdef ALTQ
    599 	ifp->if_snd.altq_type = 0;
    600 	ifp->if_snd.altq_disc = NULL;
    601 	ifp->if_snd.altq_flags &= ALTQF_CANTCHANGE;
    602 	ifp->if_snd.altq_tbr  = NULL;
    603 	ifp->if_snd.altq_ifp  = ifp;
    604 #endif
    605 
    606 	ifp->if_pfil = pfil_head_create(PFIL_TYPE_IFNET, ifp);
    607 	(void)pfil_run_hooks(if_pfil,
    608 	    (struct mbuf **)PFIL_IFNET_ATTACH, ifp, PFIL_IFNET);
    609 
    610 	if (!STAILQ_EMPTY(&domains))
    611 		if_attachdomain1(ifp);
    612 
    613 	/* Announce the interface. */
    614 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
    615 }
    616 
    617 void
    618 if_attachdomain(void)
    619 {
    620 	struct ifnet *ifp;
    621 	int s;
    622 
    623 	s = splnet();
    624 	IFNET_FOREACH(ifp)
    625 		if_attachdomain1(ifp);
    626 	splx(s);
    627 }
    628 
    629 void
    630 if_attachdomain1(struct ifnet *ifp)
    631 {
    632 	struct domain *dp;
    633 	int s;
    634 
    635 	s = splnet();
    636 
    637 	/* address family dependent data region */
    638 	memset(ifp->if_afdata, 0, sizeof(ifp->if_afdata));
    639 	DOMAIN_FOREACH(dp) {
    640 		if (dp->dom_ifattach != NULL)
    641 			ifp->if_afdata[dp->dom_family] =
    642 			    (*dp->dom_ifattach)(ifp);
    643 	}
    644 
    645 	splx(s);
    646 }
    647 
    648 /*
    649  * Deactivate an interface.  This points all of the procedure
    650  * handles at error stubs.  May be called from interrupt context.
    651  */
    652 void
    653 if_deactivate(struct ifnet *ifp)
    654 {
    655 	int s;
    656 
    657 	s = splnet();
    658 
    659 	ifp->if_output	 = if_nulloutput;
    660 	ifp->if_input	 = if_nullinput;
    661 	ifp->if_start	 = if_nullstart;
    662 	ifp->if_ioctl	 = if_nullioctl;
    663 	ifp->if_init	 = if_nullinit;
    664 	ifp->if_stop	 = if_nullstop;
    665 	ifp->if_watchdog = if_nullwatchdog;
    666 	ifp->if_drain	 = if_nulldrain;
    667 
    668 	/* No more packets may be enqueued. */
    669 	ifp->if_snd.ifq_maxlen = 0;
    670 
    671 	splx(s);
    672 }
    673 
    674 void
    675 if_purgeaddrs(struct ifnet *ifp, int family, void (*purgeaddr)(struct ifaddr *))
    676 {
    677 	struct ifaddr *ifa, *nifa;
    678 
    679 	for (ifa = IFADDR_FIRST(ifp); ifa != NULL; ifa = nifa) {
    680 		nifa = IFADDR_NEXT(ifa);
    681 		if (ifa->ifa_addr->sa_family != family)
    682 			continue;
    683 		(*purgeaddr)(ifa);
    684 	}
    685 }
    686 
    687 /*
    688  * Detach an interface from the list of "active" interfaces,
    689  * freeing any resources as we go along.
    690  *
    691  * NOTE: This routine must be called with a valid thread context,
    692  * as it may block.
    693  */
    694 void
    695 if_detach(struct ifnet *ifp)
    696 {
    697 	struct socket so;
    698 	struct ifaddr *ifa;
    699 #ifdef IFAREF_DEBUG
    700 	struct ifaddr *last_ifa = NULL;
    701 #endif
    702 	struct domain *dp;
    703 	const struct protosw *pr;
    704 	int s, i, family, purged;
    705 
    706 	/*
    707 	 * XXX It's kind of lame that we have to have the
    708 	 * XXX socket structure...
    709 	 */
    710 	memset(&so, 0, sizeof(so));
    711 
    712 	s = splnet();
    713 
    714 	/*
    715 	 * Do an if_down() to give protocols a chance to do something.
    716 	 */
    717 	if_down(ifp);
    718 
    719 #ifdef ALTQ
    720 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
    721 		altq_disable(&ifp->if_snd);
    722 	if (ALTQ_IS_ATTACHED(&ifp->if_snd))
    723 		altq_detach(&ifp->if_snd);
    724 #endif
    725 
    726 	sysctl_teardown(&ifp->if_sysctl_log);
    727 
    728 #if NCARP > 0
    729 	/* Remove the interface from any carp group it is a part of.  */
    730 	if (ifp->if_carp != NULL && ifp->if_type != IFT_CARP)
    731 		carp_ifdetach(ifp);
    732 #endif
    733 
    734 	/*
    735 	 * Rip all the addresses off the interface.  This should make
    736 	 * all of the routes go away.
    737 	 *
    738 	 * pr_usrreq calls can remove an arbitrary number of ifaddrs
    739 	 * from the list, including our "cursor", ifa.  For safety,
    740 	 * and to honor the TAILQ abstraction, I just restart the
    741 	 * loop after each removal.  Note that the loop will exit
    742 	 * when all of the remaining ifaddrs belong to the AF_LINK
    743 	 * family.  I am counting on the historical fact that at
    744 	 * least one pr_usrreq in each address domain removes at
    745 	 * least one ifaddr.
    746 	 */
    747 again:
    748 	IFADDR_FOREACH(ifa, ifp) {
    749 		family = ifa->ifa_addr->sa_family;
    750 #ifdef IFAREF_DEBUG
    751 		printf("if_detach: ifaddr %p, family %d, refcnt %d\n",
    752 		    ifa, family, ifa->ifa_refcnt);
    753 		if (last_ifa != NULL && ifa == last_ifa)
    754 			panic("if_detach: loop detected");
    755 		last_ifa = ifa;
    756 #endif
    757 		if (family == AF_LINK)
    758 			continue;
    759 		dp = pffinddomain(family);
    760 #ifdef DIAGNOSTIC
    761 		if (dp == NULL)
    762 			panic("if_detach: no domain for AF %d",
    763 			    family);
    764 #endif
    765 		/*
    766 		 * XXX These PURGEIF calls are redundant with the
    767 		 * purge-all-families calls below, but are left in for
    768 		 * now both to make a smaller change, and to avoid
    769 		 * unplanned interactions with clearing of
    770 		 * ifp->if_addrlist.
    771 		 */
    772 		purged = 0;
    773 		for (pr = dp->dom_protosw;
    774 		     pr < dp->dom_protoswNPROTOSW; pr++) {
    775 			so.so_proto = pr;
    776 			if (pr->pr_usrreq != NULL) {
    777 				(void) (*pr->pr_usrreq)(&so,
    778 				    PRU_PURGEIF, NULL, NULL,
    779 				    (struct mbuf *) ifp, curlwp);
    780 				purged = 1;
    781 			}
    782 		}
    783 		if (purged == 0) {
    784 			/*
    785 			 * XXX What's really the best thing to do
    786 			 * XXX here?  --thorpej (at) NetBSD.org
    787 			 */
    788 			printf("if_detach: WARNING: AF %d not purged\n",
    789 			    family);
    790 			ifa_remove(ifp, ifa);
    791 		}
    792 		goto again;
    793 	}
    794 
    795 	if_free_sadl(ifp);
    796 
    797 	/* Walk the routing table looking for stragglers. */
    798 	for (i = 0; i <= AF_MAX; i++) {
    799 		while (rt_walktree(i, if_rt_walktree, ifp) == ERESTART)
    800 			continue;
    801 	}
    802 
    803 	DOMAIN_FOREACH(dp) {
    804 		if (dp->dom_ifdetach != NULL && ifp->if_afdata[dp->dom_family])
    805 		{
    806 			void *p = ifp->if_afdata[dp->dom_family];
    807 			if (p) {
    808 				ifp->if_afdata[dp->dom_family] = NULL;
    809 				(*dp->dom_ifdetach)(ifp, p);
    810 			}
    811 		}
    812 
    813 		/*
    814 		 * One would expect multicast memberships (INET and
    815 		 * INET6) on UDP sockets to be purged by the PURGEIF
    816 		 * calls above, but if all addresses were removed from
    817 		 * the interface prior to destruction, the calls will
    818 		 * not be made (e.g. ppp, for which pppd(8) generally
    819 		 * removes addresses before destroying the interface).
    820 		 * Because there is no invariant that multicast
    821 		 * memberships only exist for interfaces with IPv4
    822 		 * addresses, we must call PURGEIF regardless of
    823 		 * addresses.  (Protocols which might store ifnet
    824 		 * pointers are marked with PR_PURGEIF.)
    825 		 */
    826 		for (pr = dp->dom_protosw; pr < dp->dom_protoswNPROTOSW; pr++) {
    827 			so.so_proto = pr;
    828 			if (pr->pr_usrreq != NULL && pr->pr_flags & PR_PURGEIF)
    829 				(void)(*pr->pr_usrreq)(&so, PRU_PURGEIF, NULL,
    830 				    NULL, (struct mbuf *)ifp, curlwp);
    831 		}
    832 	}
    833 
    834 	(void)pfil_run_hooks(if_pfil,
    835 	    (struct mbuf **)PFIL_IFNET_DETACH, ifp, PFIL_IFNET);
    836 	(void)pfil_head_destroy(ifp->if_pfil);
    837 
    838 	/* Announce that the interface is gone. */
    839 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
    840 
    841 	ifindex2ifnet[ifp->if_index] = NULL;
    842 
    843 	TAILQ_REMOVE(&ifnet, ifp, if_list);
    844 
    845 	ifioctl_detach(ifp);
    846 
    847 	/*
    848 	 * remove packets that came from ifp, from software interrupt queues.
    849 	 */
    850 	DOMAIN_FOREACH(dp) {
    851 		for (i = 0; i < __arraycount(dp->dom_ifqueues); i++) {
    852 			struct ifqueue *iq = dp->dom_ifqueues[i];
    853 			if (iq == NULL)
    854 				break;
    855 			dp->dom_ifqueues[i] = NULL;
    856 			if_detach_queues(ifp, iq);
    857 		}
    858 	}
    859 
    860 	splx(s);
    861 }
    862 
    863 static void
    864 if_detach_queues(struct ifnet *ifp, struct ifqueue *q)
    865 {
    866 	struct mbuf *m, *prev, *next;
    867 
    868 	prev = NULL;
    869 	for (m = q->ifq_head; m != NULL; m = next) {
    870 		next = m->m_nextpkt;
    871 #ifdef DIAGNOSTIC
    872 		if ((m->m_flags & M_PKTHDR) == 0) {
    873 			prev = m;
    874 			continue;
    875 		}
    876 #endif
    877 		if (m->m_pkthdr.rcvif != ifp) {
    878 			prev = m;
    879 			continue;
    880 		}
    881 
    882 		if (prev != NULL)
    883 			prev->m_nextpkt = m->m_nextpkt;
    884 		else
    885 			q->ifq_head = m->m_nextpkt;
    886 		if (q->ifq_tail == m)
    887 			q->ifq_tail = prev;
    888 		q->ifq_len--;
    889 
    890 		m->m_nextpkt = NULL;
    891 		m_freem(m);
    892 		IF_DROP(q);
    893 	}
    894 }
    895 
    896 /*
    897  * Callback for a radix tree walk to delete all references to an
    898  * ifnet.
    899  */
    900 static int
    901 if_rt_walktree(struct rtentry *rt, void *v)
    902 {
    903 	struct ifnet *ifp = (struct ifnet *)v;
    904 	int error;
    905 
    906 	if (rt->rt_ifp != ifp)
    907 		return 0;
    908 
    909 	/* Delete the entry. */
    910 	++rt->rt_refcnt;
    911 	error = rtrequest(RTM_DELETE, rt_getkey(rt), rt->rt_gateway,
    912 	    rt_mask(rt), rt->rt_flags, NULL);
    913 	KASSERT((rt->rt_flags & RTF_UP) == 0);
    914 	rt->rt_ifp = NULL;
    915 	RTFREE(rt);
    916 	if (error != 0)
    917 		printf("%s: warning: unable to delete rtentry @ %p, "
    918 		    "error = %d\n", ifp->if_xname, rt, error);
    919 	return ERESTART;
    920 }
    921 
    922 /*
    923  * Create a clone network interface.
    924  */
    925 int
    926 if_clone_create(const char *name)
    927 {
    928 	struct if_clone *ifc;
    929 	int unit;
    930 
    931 	ifc = if_clone_lookup(name, &unit);
    932 	if (ifc == NULL)
    933 		return EINVAL;
    934 
    935 	if (ifunit(name) != NULL)
    936 		return EEXIST;
    937 
    938 	return (*ifc->ifc_create)(ifc, unit);
    939 }
    940 
    941 /*
    942  * Destroy a clone network interface.
    943  */
    944 int
    945 if_clone_destroy(const char *name)
    946 {
    947 	struct if_clone *ifc;
    948 	struct ifnet *ifp;
    949 
    950 	ifc = if_clone_lookup(name, NULL);
    951 	if (ifc == NULL)
    952 		return EINVAL;
    953 
    954 	ifp = ifunit(name);
    955 	if (ifp == NULL)
    956 		return ENXIO;
    957 
    958 	if (ifc->ifc_destroy == NULL)
    959 		return EOPNOTSUPP;
    960 
    961 	return (*ifc->ifc_destroy)(ifp);
    962 }
    963 
    964 /*
    965  * Look up a network interface cloner.
    966  */
    967 static struct if_clone *
    968 if_clone_lookup(const char *name, int *unitp)
    969 {
    970 	struct if_clone *ifc;
    971 	const char *cp;
    972 	char *dp, ifname[IFNAMSIZ + 3];
    973 	int unit;
    974 
    975 	strcpy(ifname, "if_");
    976 	/* separate interface name from unit */
    977 	for (dp = ifname + 3, cp = name; cp - name < IFNAMSIZ &&
    978 	    *cp && (*cp < '0' || *cp > '9');)
    979 		*dp++ = *cp++;
    980 
    981 	if (cp == name || cp - name == IFNAMSIZ || !*cp)
    982 		return NULL;	/* No name or unit number */
    983 	*dp++ = '\0';
    984 
    985 again:
    986 	LIST_FOREACH(ifc, &if_cloners, ifc_list) {
    987 		if (strcmp(ifname + 3, ifc->ifc_name) == 0)
    988 			break;
    989 	}
    990 
    991 	if (ifc == NULL) {
    992 		if (*ifname == '\0' ||
    993 		    module_autoload(ifname, MODULE_CLASS_DRIVER))
    994 			return NULL;
    995 		*ifname = '\0';
    996 		goto again;
    997 	}
    998 
    999 	unit = 0;
   1000 	while (cp - name < IFNAMSIZ && *cp) {
   1001 		if (*cp < '0' || *cp > '9' || unit >= INT_MAX / 10) {
   1002 			/* Bogus unit number. */
   1003 			return NULL;
   1004 		}
   1005 		unit = (unit * 10) + (*cp++ - '0');
   1006 	}
   1007 
   1008 	if (unitp != NULL)
   1009 		*unitp = unit;
   1010 	return ifc;
   1011 }
   1012 
   1013 /*
   1014  * Register a network interface cloner.
   1015  */
   1016 void
   1017 if_clone_attach(struct if_clone *ifc)
   1018 {
   1019 
   1020 	LIST_INSERT_HEAD(&if_cloners, ifc, ifc_list);
   1021 	if_cloners_count++;
   1022 }
   1023 
   1024 /*
   1025  * Unregister a network interface cloner.
   1026  */
   1027 void
   1028 if_clone_detach(struct if_clone *ifc)
   1029 {
   1030 
   1031 	LIST_REMOVE(ifc, ifc_list);
   1032 	if_cloners_count--;
   1033 }
   1034 
   1035 /*
   1036  * Provide list of interface cloners to userspace.
   1037  */
   1038 static int
   1039 if_clone_list(struct if_clonereq *ifcr)
   1040 {
   1041 	char outbuf[IFNAMSIZ], *dst;
   1042 	struct if_clone *ifc;
   1043 	int count, error = 0;
   1044 
   1045 	ifcr->ifcr_total = if_cloners_count;
   1046 	if ((dst = ifcr->ifcr_buffer) == NULL) {
   1047 		/* Just asking how many there are. */
   1048 		return 0;
   1049 	}
   1050 
   1051 	if (ifcr->ifcr_count < 0)
   1052 		return EINVAL;
   1053 
   1054 	count = (if_cloners_count < ifcr->ifcr_count) ?
   1055 	    if_cloners_count : ifcr->ifcr_count;
   1056 
   1057 	for (ifc = LIST_FIRST(&if_cloners); ifc != NULL && count != 0;
   1058 	     ifc = LIST_NEXT(ifc, ifc_list), count--, dst += IFNAMSIZ) {
   1059 		(void)strncpy(outbuf, ifc->ifc_name, sizeof(outbuf));
   1060 		if (outbuf[sizeof(outbuf) - 1] != '\0')
   1061 			return ENAMETOOLONG;
   1062 		error = copyout(outbuf, dst, sizeof(outbuf));
   1063 		if (error != 0)
   1064 			break;
   1065 	}
   1066 
   1067 	return error;
   1068 }
   1069 
   1070 void
   1071 ifa_insert(struct ifnet *ifp, struct ifaddr *ifa)
   1072 {
   1073 	ifa->ifa_ifp = ifp;
   1074 	TAILQ_INSERT_TAIL(&ifp->if_addrlist, ifa, ifa_list);
   1075 	IFAREF(ifa);
   1076 }
   1077 
   1078 void
   1079 ifa_remove(struct ifnet *ifp, struct ifaddr *ifa)
   1080 {
   1081 	KASSERT(ifa->ifa_ifp == ifp);
   1082 	TAILQ_REMOVE(&ifp->if_addrlist, ifa, ifa_list);
   1083 	IFAFREE(ifa);
   1084 }
   1085 
   1086 static inline int
   1087 equal(const struct sockaddr *sa1, const struct sockaddr *sa2)
   1088 {
   1089 	return sockaddr_cmp(sa1, sa2) == 0;
   1090 }
   1091 
   1092 /*
   1093  * Locate an interface based on a complete address.
   1094  */
   1095 /*ARGSUSED*/
   1096 struct ifaddr *
   1097 ifa_ifwithaddr(const struct sockaddr *addr)
   1098 {
   1099 	struct ifnet *ifp;
   1100 	struct ifaddr *ifa;
   1101 
   1102 	IFNET_FOREACH(ifp) {
   1103 		if (ifp->if_output == if_nulloutput)
   1104 			continue;
   1105 		IFADDR_FOREACH(ifa, ifp) {
   1106 			if (ifa->ifa_addr->sa_family != addr->sa_family)
   1107 				continue;
   1108 			if (equal(addr, ifa->ifa_addr))
   1109 				return ifa;
   1110 			if ((ifp->if_flags & IFF_BROADCAST) &&
   1111 			    ifa->ifa_broadaddr &&
   1112 			    /* IP6 doesn't have broadcast */
   1113 			    ifa->ifa_broadaddr->sa_len != 0 &&
   1114 			    equal(ifa->ifa_broadaddr, addr))
   1115 				return ifa;
   1116 		}
   1117 	}
   1118 	return NULL;
   1119 }
   1120 
   1121 /*
   1122  * Locate the point to point interface with a given destination address.
   1123  */
   1124 /*ARGSUSED*/
   1125 struct ifaddr *
   1126 ifa_ifwithdstaddr(const struct sockaddr *addr)
   1127 {
   1128 	struct ifnet *ifp;
   1129 	struct ifaddr *ifa;
   1130 
   1131 	IFNET_FOREACH(ifp) {
   1132 		if (ifp->if_output == if_nulloutput)
   1133 			continue;
   1134 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
   1135 			continue;
   1136 		IFADDR_FOREACH(ifa, ifp) {
   1137 			if (ifa->ifa_addr->sa_family != addr->sa_family ||
   1138 			    ifa->ifa_dstaddr == NULL)
   1139 				continue;
   1140 			if (equal(addr, ifa->ifa_dstaddr))
   1141 				return ifa;
   1142 		}
   1143 	}
   1144 	return NULL;
   1145 }
   1146 
   1147 /*
   1148  * Find an interface on a specific network.  If many, choice
   1149  * is most specific found.
   1150  */
   1151 struct ifaddr *
   1152 ifa_ifwithnet(const struct sockaddr *addr)
   1153 {
   1154 	struct ifnet *ifp;
   1155 	struct ifaddr *ifa;
   1156 	const struct sockaddr_dl *sdl;
   1157 	struct ifaddr *ifa_maybe = 0;
   1158 	u_int af = addr->sa_family;
   1159 	const char *addr_data = addr->sa_data, *cplim;
   1160 
   1161 	if (af == AF_LINK) {
   1162 		sdl = satocsdl(addr);
   1163 		if (sdl->sdl_index && sdl->sdl_index < if_indexlim &&
   1164 		    ifindex2ifnet[sdl->sdl_index] &&
   1165 		    ifindex2ifnet[sdl->sdl_index]->if_output != if_nulloutput)
   1166 			return ifnet_addrs[sdl->sdl_index];
   1167 	}
   1168 #ifdef NETATALK
   1169 	if (af == AF_APPLETALK) {
   1170 		const struct sockaddr_at *sat, *sat2;
   1171 		sat = (const struct sockaddr_at *)addr;
   1172 		IFNET_FOREACH(ifp) {
   1173 			if (ifp->if_output == if_nulloutput)
   1174 				continue;
   1175 			ifa = at_ifawithnet((const struct sockaddr_at *)addr, ifp);
   1176 			if (ifa == NULL)
   1177 				continue;
   1178 			sat2 = (struct sockaddr_at *)ifa->ifa_addr;
   1179 			if (sat2->sat_addr.s_net == sat->sat_addr.s_net)
   1180 				return ifa; /* exact match */
   1181 			if (ifa_maybe == NULL) {
   1182 				/* else keep the if with the right range */
   1183 				ifa_maybe = ifa;
   1184 			}
   1185 		}
   1186 		return ifa_maybe;
   1187 	}
   1188 #endif
   1189 	IFNET_FOREACH(ifp) {
   1190 		if (ifp->if_output == if_nulloutput)
   1191 			continue;
   1192 		IFADDR_FOREACH(ifa, ifp) {
   1193 			const char *cp, *cp2, *cp3;
   1194 
   1195 			if (ifa->ifa_addr->sa_family != af ||
   1196 			    ifa->ifa_netmask == NULL)
   1197  next:				continue;
   1198 			cp = addr_data;
   1199 			cp2 = ifa->ifa_addr->sa_data;
   1200 			cp3 = ifa->ifa_netmask->sa_data;
   1201 			cplim = (const char *)ifa->ifa_netmask +
   1202 			    ifa->ifa_netmask->sa_len;
   1203 			while (cp3 < cplim) {
   1204 				if ((*cp++ ^ *cp2++) & *cp3++) {
   1205 					/* want to continue for() loop */
   1206 					goto next;
   1207 				}
   1208 			}
   1209 			if (ifa_maybe == NULL ||
   1210 			    rn_refines((void *)ifa->ifa_netmask,
   1211 			    (void *)ifa_maybe->ifa_netmask))
   1212 				ifa_maybe = ifa;
   1213 		}
   1214 	}
   1215 	return ifa_maybe;
   1216 }
   1217 
   1218 /*
   1219  * Find the interface of the addresss.
   1220  */
   1221 struct ifaddr *
   1222 ifa_ifwithladdr(const struct sockaddr *addr)
   1223 {
   1224 	struct ifaddr *ia;
   1225 
   1226 	if ((ia = ifa_ifwithaddr(addr)) || (ia = ifa_ifwithdstaddr(addr)) ||
   1227 	    (ia = ifa_ifwithnet(addr)))
   1228 		return ia;
   1229 	return NULL;
   1230 }
   1231 
   1232 /*
   1233  * Find an interface using a specific address family
   1234  */
   1235 struct ifaddr *
   1236 ifa_ifwithaf(int af)
   1237 {
   1238 	struct ifnet *ifp;
   1239 	struct ifaddr *ifa;
   1240 
   1241 	IFNET_FOREACH(ifp) {
   1242 		if (ifp->if_output == if_nulloutput)
   1243 			continue;
   1244 		IFADDR_FOREACH(ifa, ifp) {
   1245 			if (ifa->ifa_addr->sa_family == af)
   1246 				return ifa;
   1247 		}
   1248 	}
   1249 	return NULL;
   1250 }
   1251 
   1252 /*
   1253  * Find an interface address specific to an interface best matching
   1254  * a given address.
   1255  */
   1256 struct ifaddr *
   1257 ifaof_ifpforaddr(const struct sockaddr *addr, struct ifnet *ifp)
   1258 {
   1259 	struct ifaddr *ifa;
   1260 	const char *cp, *cp2, *cp3;
   1261 	const char *cplim;
   1262 	struct ifaddr *ifa_maybe = 0;
   1263 	u_int af = addr->sa_family;
   1264 
   1265 	if (ifp->if_output == if_nulloutput)
   1266 		return NULL;
   1267 
   1268 	if (af >= AF_MAX)
   1269 		return NULL;
   1270 
   1271 	IFADDR_FOREACH(ifa, ifp) {
   1272 		if (ifa->ifa_addr->sa_family != af)
   1273 			continue;
   1274 		ifa_maybe = ifa;
   1275 		if (ifa->ifa_netmask == NULL) {
   1276 			if (equal(addr, ifa->ifa_addr) ||
   1277 			    (ifa->ifa_dstaddr &&
   1278 			     equal(addr, ifa->ifa_dstaddr)))
   1279 				return ifa;
   1280 			continue;
   1281 		}
   1282 		cp = addr->sa_data;
   1283 		cp2 = ifa->ifa_addr->sa_data;
   1284 		cp3 = ifa->ifa_netmask->sa_data;
   1285 		cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
   1286 		for (; cp3 < cplim; cp3++) {
   1287 			if ((*cp++ ^ *cp2++) & *cp3)
   1288 				break;
   1289 		}
   1290 		if (cp3 == cplim)
   1291 			return ifa;
   1292 	}
   1293 	return ifa_maybe;
   1294 }
   1295 
   1296 /*
   1297  * Default action when installing a route with a Link Level gateway.
   1298  * Lookup an appropriate real ifa to point to.
   1299  * This should be moved to /sys/net/link.c eventually.
   1300  */
   1301 void
   1302 link_rtrequest(int cmd, struct rtentry *rt, const struct rt_addrinfo *info)
   1303 {
   1304 	struct ifaddr *ifa;
   1305 	const struct sockaddr *dst;
   1306 	struct ifnet *ifp;
   1307 
   1308 	if (cmd != RTM_ADD || (ifa = rt->rt_ifa) == NULL ||
   1309 	    (ifp = ifa->ifa_ifp) == NULL || (dst = rt_getkey(rt)) == NULL)
   1310 		return;
   1311 	if ((ifa = ifaof_ifpforaddr(dst, ifp)) != NULL) {
   1312 		rt_replace_ifa(rt, ifa);
   1313 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
   1314 			ifa->ifa_rtrequest(cmd, rt, info);
   1315 	}
   1316 }
   1317 
   1318 /*
   1319  * Handle a change in the interface link state.
   1320  * XXX: We should listen to the routing socket in-kernel rather
   1321  * than calling in6_if_link_* functions directly from here.
   1322  */
   1323 void
   1324 if_link_state_change(struct ifnet *ifp, int link_state)
   1325 {
   1326 	int s;
   1327 #if defined(DEBUG) || defined(INET6)
   1328 	int old_link_state;
   1329 #endif
   1330 
   1331 	s = splnet();
   1332 	if (ifp->if_link_state == link_state) {
   1333 		splx(s);
   1334 		return;
   1335 	}
   1336 
   1337 #if defined(DEBUG) || defined(INET6)
   1338 	old_link_state = ifp->if_link_state;
   1339 #endif
   1340 	ifp->if_link_state = link_state;
   1341 #ifdef DEBUG
   1342 	log(LOG_DEBUG, "%s: link state %s (was %s)\n", ifp->if_xname,
   1343 		link_state == LINK_STATE_UP ? "UP" :
   1344 		link_state == LINK_STATE_DOWN ? "DOWN" :
   1345 		"UNKNOWN",
   1346 		 old_link_state == LINK_STATE_UP ? "UP" :
   1347 		old_link_state == LINK_STATE_DOWN ? "DOWN" :
   1348 		"UNKNOWN");
   1349 #endif
   1350 
   1351 #ifdef INET6
   1352 	/*
   1353 	 * When going from UNKNOWN to UP, we need to mark existing
   1354 	 * IPv6 addresses as tentative and restart DAD as we may have
   1355 	 * erroneously not found a duplicate.
   1356 	 *
   1357 	 * This needs to happen before rt_ifmsg to avoid a race where
   1358 	 * listeners would have an address and expect it to work right
   1359 	 * away.
   1360 	 */
   1361 	if (in6_present && link_state == LINK_STATE_UP &&
   1362 	    old_link_state == LINK_STATE_UNKNOWN)
   1363 		in6_if_link_down(ifp);
   1364 #endif
   1365 
   1366 	/* Notify that the link state has changed. */
   1367 	rt_ifmsg(ifp);
   1368 
   1369 #if NCARP > 0
   1370 	if (ifp->if_carp)
   1371 		carp_carpdev_state(ifp);
   1372 #endif
   1373 
   1374 #ifdef INET6
   1375 	if (in6_present) {
   1376 		if (link_state == LINK_STATE_DOWN)
   1377 			in6_if_link_down(ifp);
   1378 		else if (link_state == LINK_STATE_UP)
   1379 			in6_if_link_up(ifp);
   1380 	}
   1381 #endif
   1382 
   1383 	splx(s);
   1384 }
   1385 
   1386 /*
   1387  * Mark an interface down and notify protocols of
   1388  * the transition.
   1389  * NOTE: must be called at splsoftnet or equivalent.
   1390  */
   1391 void
   1392 if_down(struct ifnet *ifp)
   1393 {
   1394 	struct ifaddr *ifa;
   1395 
   1396 	ifp->if_flags &= ~IFF_UP;
   1397 	nanotime(&ifp->if_lastchange);
   1398 	IFADDR_FOREACH(ifa, ifp)
   1399 		pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
   1400 	IFQ_PURGE(&ifp->if_snd);
   1401 #if NCARP > 0
   1402 	if (ifp->if_carp)
   1403 		carp_carpdev_state(ifp);
   1404 #endif
   1405 	rt_ifmsg(ifp);
   1406 #ifdef INET6
   1407 	if (in6_present)
   1408 		in6_if_down(ifp);
   1409 #endif
   1410 }
   1411 
   1412 /*
   1413  * Mark an interface up and notify protocols of
   1414  * the transition.
   1415  * NOTE: must be called at splsoftnet or equivalent.
   1416  */
   1417 void
   1418 if_up(struct ifnet *ifp)
   1419 {
   1420 #ifdef notyet
   1421 	struct ifaddr *ifa;
   1422 #endif
   1423 
   1424 	ifp->if_flags |= IFF_UP;
   1425 	nanotime(&ifp->if_lastchange);
   1426 #ifdef notyet
   1427 	/* this has no effect on IP, and will kill all ISO connections XXX */
   1428 	IFADDR_FOREACH(ifa, ifp)
   1429 		pfctlinput(PRC_IFUP, ifa->ifa_addr);
   1430 #endif
   1431 #if NCARP > 0
   1432 	if (ifp->if_carp)
   1433 		carp_carpdev_state(ifp);
   1434 #endif
   1435 	rt_ifmsg(ifp);
   1436 #ifdef INET6
   1437 	if (in6_present)
   1438 		in6_if_up(ifp);
   1439 #endif
   1440 }
   1441 
   1442 /*
   1443  * Handle interface watchdog timer routines.  Called
   1444  * from softclock, we decrement timers (if set) and
   1445  * call the appropriate interface routine on expiration.
   1446  */
   1447 void
   1448 if_slowtimo(void *arg)
   1449 {
   1450 	struct ifnet *ifp;
   1451 	int s = splnet();
   1452 
   1453 	IFNET_FOREACH(ifp) {
   1454 		if (ifp->if_timer == 0 || --ifp->if_timer)
   1455 			continue;
   1456 		if (ifp->if_watchdog != NULL)
   1457 			(*ifp->if_watchdog)(ifp);
   1458 	}
   1459 	splx(s);
   1460 	callout_reset(&if_slowtimo_ch, hz / IFNET_SLOWHZ, if_slowtimo, NULL);
   1461 }
   1462 
   1463 /*
   1464  * Set/clear promiscuous mode on interface ifp based on the truth value
   1465  * of pswitch.  The calls are reference counted so that only the first
   1466  * "on" request actually has an effect, as does the final "off" request.
   1467  * Results are undefined if the "off" and "on" requests are not matched.
   1468  */
   1469 int
   1470 ifpromisc(struct ifnet *ifp, int pswitch)
   1471 {
   1472 	int pcount, ret;
   1473 	short nflags;
   1474 
   1475 	pcount = ifp->if_pcount;
   1476 	if (pswitch) {
   1477 		/*
   1478 		 * Allow the device to be "placed" into promiscuous
   1479 		 * mode even if it is not configured up.  It will
   1480 		 * consult IFF_PROMISC when it is brought up.
   1481 		 */
   1482 		if (ifp->if_pcount++ != 0)
   1483 			return 0;
   1484 		nflags = ifp->if_flags | IFF_PROMISC;
   1485 	} else {
   1486 		if (--ifp->if_pcount > 0)
   1487 			return 0;
   1488 		nflags = ifp->if_flags & ~IFF_PROMISC;
   1489 	}
   1490 	ret = if_flags_set(ifp, nflags);
   1491 	/* Restore interface state if not successful. */
   1492 	if (ret != 0) {
   1493 		ifp->if_pcount = pcount;
   1494 	}
   1495 	return ret;
   1496 }
   1497 
   1498 /*
   1499  * Map interface name to
   1500  * interface structure pointer.
   1501  */
   1502 struct ifnet *
   1503 ifunit(const char *name)
   1504 {
   1505 	struct ifnet *ifp;
   1506 	const char *cp = name;
   1507 	u_int unit = 0;
   1508 	u_int i;
   1509 
   1510 	/*
   1511 	 * If the entire name is a number, treat it as an ifindex.
   1512 	 */
   1513 	for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++) {
   1514 		unit = unit * 10 + (*cp - '0');
   1515 	}
   1516 
   1517 	/*
   1518 	 * If the number took all of the name, then it's a valid ifindex.
   1519 	 */
   1520 	if (i == IFNAMSIZ || (cp != name && *cp == '\0')) {
   1521 		if (unit >= if_indexlim)
   1522 			return NULL;
   1523 		ifp = ifindex2ifnet[unit];
   1524 		if (ifp == NULL || ifp->if_output == if_nulloutput)
   1525 			return NULL;
   1526 		return ifp;
   1527 	}
   1528 
   1529 	IFNET_FOREACH(ifp) {
   1530 		if (ifp->if_output == if_nulloutput)
   1531 			continue;
   1532 	 	if (strcmp(ifp->if_xname, name) == 0)
   1533 			return ifp;
   1534 	}
   1535 	return NULL;
   1536 }
   1537 
   1538 ifnet_t *
   1539 if_byindex(u_int idx)
   1540 {
   1541 
   1542 	return (idx < if_indexlim) ? ifindex2ifnet[idx] : NULL;
   1543 }
   1544 
   1545 /* common */
   1546 int
   1547 ifioctl_common(struct ifnet *ifp, u_long cmd, void *data)
   1548 {
   1549 	int s;
   1550 	struct ifreq *ifr;
   1551 	struct ifcapreq *ifcr;
   1552 	struct ifdatareq *ifdr;
   1553 
   1554 	switch (cmd) {
   1555 	case SIOCSIFCAP:
   1556 		ifcr = data;
   1557 		if ((ifcr->ifcr_capenable & ~ifp->if_capabilities) != 0)
   1558 			return EINVAL;
   1559 
   1560 		if (ifcr->ifcr_capenable == ifp->if_capenable)
   1561 			return 0;
   1562 
   1563 		ifp->if_capenable = ifcr->ifcr_capenable;
   1564 
   1565 		/* Pre-compute the checksum flags mask. */
   1566 		ifp->if_csum_flags_tx = 0;
   1567 		ifp->if_csum_flags_rx = 0;
   1568 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Tx) {
   1569 			ifp->if_csum_flags_tx |= M_CSUM_IPv4;
   1570 		}
   1571 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Rx) {
   1572 			ifp->if_csum_flags_rx |= M_CSUM_IPv4;
   1573 		}
   1574 
   1575 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Tx) {
   1576 			ifp->if_csum_flags_tx |= M_CSUM_TCPv4;
   1577 		}
   1578 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Rx) {
   1579 			ifp->if_csum_flags_rx |= M_CSUM_TCPv4;
   1580 		}
   1581 
   1582 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Tx) {
   1583 			ifp->if_csum_flags_tx |= M_CSUM_UDPv4;
   1584 		}
   1585 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Rx) {
   1586 			ifp->if_csum_flags_rx |= M_CSUM_UDPv4;
   1587 		}
   1588 
   1589 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Tx) {
   1590 			ifp->if_csum_flags_tx |= M_CSUM_TCPv6;
   1591 		}
   1592 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Rx) {
   1593 			ifp->if_csum_flags_rx |= M_CSUM_TCPv6;
   1594 		}
   1595 
   1596 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Tx) {
   1597 			ifp->if_csum_flags_tx |= M_CSUM_UDPv6;
   1598 		}
   1599 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Rx) {
   1600 			ifp->if_csum_flags_rx |= M_CSUM_UDPv6;
   1601 		}
   1602 		if (ifp->if_flags & IFF_UP)
   1603 			return ENETRESET;
   1604 		return 0;
   1605 	case SIOCSIFFLAGS:
   1606 		ifr = data;
   1607 		if (ifp->if_flags & IFF_UP && (ifr->ifr_flags & IFF_UP) == 0) {
   1608 			s = splnet();
   1609 			if_down(ifp);
   1610 			splx(s);
   1611 		}
   1612 		if (ifr->ifr_flags & IFF_UP && (ifp->if_flags & IFF_UP) == 0) {
   1613 			s = splnet();
   1614 			if_up(ifp);
   1615 			splx(s);
   1616 		}
   1617 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
   1618 			(ifr->ifr_flags &~ IFF_CANTCHANGE);
   1619 		break;
   1620 	case SIOCGIFFLAGS:
   1621 		ifr = data;
   1622 		ifr->ifr_flags = ifp->if_flags;
   1623 		break;
   1624 
   1625 	case SIOCGIFMETRIC:
   1626 		ifr = data;
   1627 		ifr->ifr_metric = ifp->if_metric;
   1628 		break;
   1629 
   1630 	case SIOCGIFMTU:
   1631 		ifr = data;
   1632 		ifr->ifr_mtu = ifp->if_mtu;
   1633 		break;
   1634 
   1635 	case SIOCGIFDLT:
   1636 		ifr = data;
   1637 		ifr->ifr_dlt = ifp->if_dlt;
   1638 		break;
   1639 
   1640 	case SIOCGIFCAP:
   1641 		ifcr = data;
   1642 		ifcr->ifcr_capabilities = ifp->if_capabilities;
   1643 		ifcr->ifcr_capenable = ifp->if_capenable;
   1644 		break;
   1645 
   1646 	case SIOCSIFMETRIC:
   1647 		ifr = data;
   1648 		ifp->if_metric = ifr->ifr_metric;
   1649 		break;
   1650 
   1651 	case SIOCGIFDATA:
   1652 		ifdr = data;
   1653 		ifdr->ifdr_data = ifp->if_data;
   1654 		break;
   1655 
   1656 	case SIOCGIFINDEX:
   1657 		ifr = data;
   1658 		ifr->ifr_index = ifp->if_index;
   1659 		break;
   1660 
   1661 	case SIOCZIFDATA:
   1662 		ifdr = data;
   1663 		ifdr->ifdr_data = ifp->if_data;
   1664 		/*
   1665 		 * Assumes that the volatile counters that can be
   1666 		 * zero'ed are at the end of if_data.
   1667 		 */
   1668 		memset(&ifp->if_data.ifi_ipackets, 0, sizeof(ifp->if_data) -
   1669 		    offsetof(struct if_data, ifi_ipackets));
   1670 		/*
   1671 		 * The memset() clears to the bottm of if_data. In the area,
   1672 		 * if_lastchange is included. Please be careful if new entry
   1673 		 * will be added into if_data or rewite this.
   1674 		 *
   1675 		 * And also, update if_lastchnage.
   1676 		 */
   1677 		getnanotime(&ifp->if_lastchange);
   1678 		break;
   1679 	case SIOCSIFMTU:
   1680 		ifr = data;
   1681 		if (ifp->if_mtu == ifr->ifr_mtu)
   1682 			break;
   1683 		ifp->if_mtu = ifr->ifr_mtu;
   1684 		/*
   1685 		 * If the link MTU changed, do network layer specific procedure.
   1686 		 */
   1687 #ifdef INET6
   1688 		if (in6_present)
   1689 			nd6_setmtu(ifp);
   1690 #endif
   1691 		return ENETRESET;
   1692 	default:
   1693 		return ENOTTY;
   1694 	}
   1695 	return 0;
   1696 }
   1697 
   1698 int
   1699 ifaddrpref_ioctl(struct socket *so, u_long cmd, void *data, struct ifnet *ifp,
   1700     lwp_t *l)
   1701 {
   1702 	struct if_addrprefreq *ifap = (struct if_addrprefreq *)data;
   1703 	struct ifaddr *ifa;
   1704 	const struct sockaddr *any, *sa;
   1705 	union {
   1706 		struct sockaddr sa;
   1707 		struct sockaddr_storage ss;
   1708 	} u, v;
   1709 
   1710 	switch (cmd) {
   1711 	case SIOCSIFADDRPREF:
   1712 		if (kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
   1713 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
   1714 		    NULL) != 0)
   1715 			return EPERM;
   1716 	case SIOCGIFADDRPREF:
   1717 		break;
   1718 	default:
   1719 		return EOPNOTSUPP;
   1720 	}
   1721 
   1722 	/* sanity checks */
   1723 	if (data == NULL || ifp == NULL) {
   1724 		panic("invalid argument to %s", __func__);
   1725 		/*NOTREACHED*/
   1726 	}
   1727 
   1728 	/* address must be specified on ADD and DELETE */
   1729 	sa = sstocsa(&ifap->ifap_addr);
   1730 	if (sa->sa_family != sofamily(so))
   1731 		return EINVAL;
   1732 	if ((any = sockaddr_any(sa)) == NULL || sa->sa_len != any->sa_len)
   1733 		return EINVAL;
   1734 
   1735 	sockaddr_externalize(&v.sa, sizeof(v.ss), sa);
   1736 
   1737 	IFADDR_FOREACH(ifa, ifp) {
   1738 		if (ifa->ifa_addr->sa_family != sa->sa_family)
   1739 			continue;
   1740 		sockaddr_externalize(&u.sa, sizeof(u.ss), ifa->ifa_addr);
   1741 		if (sockaddr_cmp(&u.sa, &v.sa) == 0)
   1742 			break;
   1743 	}
   1744 	if (ifa == NULL)
   1745 		return EADDRNOTAVAIL;
   1746 
   1747 	switch (cmd) {
   1748 	case SIOCSIFADDRPREF:
   1749 		ifa->ifa_preference = ifap->ifap_preference;
   1750 		return 0;
   1751 	case SIOCGIFADDRPREF:
   1752 		/* fill in the if_laddrreq structure */
   1753 		(void)sockaddr_copy(sstosa(&ifap->ifap_addr),
   1754 		    sizeof(ifap->ifap_addr), ifa->ifa_addr);
   1755 		ifap->ifap_preference = ifa->ifa_preference;
   1756 		return 0;
   1757 	default:
   1758 		return EOPNOTSUPP;
   1759 	}
   1760 }
   1761 
   1762 static void
   1763 ifnet_lock_enter(struct ifnet_lock *il)
   1764 {
   1765 	uint64_t *nenter;
   1766 
   1767 	/* Before trying to acquire the mutex, increase the count of threads
   1768 	 * who have entered or who wait to enter the critical section.
   1769 	 * Avoid one costly locked memory transaction by keeping a count for
   1770 	 * each CPU.
   1771 	 */
   1772 	nenter = percpu_getref(il->il_nenter);
   1773 	(*nenter)++;
   1774 	percpu_putref(il->il_nenter);
   1775 	mutex_enter(&il->il_lock);
   1776 }
   1777 
   1778 static void
   1779 ifnet_lock_exit(struct ifnet_lock *il)
   1780 {
   1781 	/* Increase the count of threads who have exited the critical
   1782 	 * section.  Increase while we still hold the lock.
   1783 	 */
   1784 	il->il_nexit++;
   1785 	mutex_exit(&il->il_lock);
   1786 }
   1787 
   1788 /*
   1789  * Interface ioctls.
   1790  */
   1791 int
   1792 ifioctl(struct socket *so, u_long cmd, void *data, struct lwp *l)
   1793 {
   1794 	struct ifnet *ifp;
   1795 	struct ifreq *ifr;
   1796 	int error = 0;
   1797 #if defined(COMPAT_OSOCK) || defined(COMPAT_OIFREQ)
   1798 	u_long ocmd = cmd;
   1799 #endif
   1800 	short oif_flags;
   1801 #ifdef COMPAT_OIFREQ
   1802 	struct ifreq ifrb;
   1803 	struct oifreq *oifr = NULL;
   1804 #endif
   1805 
   1806 	switch (cmd) {
   1807 #ifdef COMPAT_OIFREQ
   1808 	case OSIOCGIFCONF:
   1809 	case OOSIOCGIFCONF:
   1810 		return compat_ifconf(cmd, data);
   1811 #endif
   1812 #ifdef COMPAT_OIFDATA
   1813 	case OSIOCGIFDATA:
   1814 	case OSIOCZIFDATA:
   1815 		return compat_ifdatareq(l, cmd, data);
   1816 #endif
   1817 	case SIOCGIFCONF:
   1818 		return ifconf(cmd, data);
   1819 	case SIOCINITIFADDR:
   1820 		return EPERM;
   1821 	}
   1822 
   1823 #ifdef COMPAT_OIFREQ
   1824 	cmd = compat_cvtcmd(cmd);
   1825 	if (cmd != ocmd) {
   1826 		oifr = data;
   1827 		data = ifr = &ifrb;
   1828 		ifreqo2n(oifr, ifr);
   1829 	} else
   1830 #endif
   1831 		ifr = data;
   1832 
   1833 	ifp = ifunit(ifr->ifr_name);
   1834 
   1835 	switch (cmd) {
   1836 	case SIOCIFCREATE:
   1837 	case SIOCIFDESTROY:
   1838 		if (l != NULL) {
   1839 			error = kauth_authorize_network(l->l_cred,
   1840 			    KAUTH_NETWORK_INTERFACE,
   1841 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
   1842 			    (void *)cmd, NULL);
   1843 			if (error != 0)
   1844 				return error;
   1845 		}
   1846 		return (cmd == SIOCIFCREATE) ?
   1847 			if_clone_create(ifr->ifr_name) :
   1848 			if_clone_destroy(ifr->ifr_name);
   1849 
   1850 	case SIOCIFGCLONERS:
   1851 		return if_clone_list((struct if_clonereq *)data);
   1852 	}
   1853 
   1854 	if (ifp == NULL)
   1855 		return ENXIO;
   1856 
   1857 	switch (cmd) {
   1858 	case SIOCALIFADDR:
   1859 	case SIOCDLIFADDR:
   1860 	case SIOCSIFADDRPREF:
   1861 	case SIOCSIFFLAGS:
   1862 	case SIOCSIFCAP:
   1863 	case SIOCSIFMETRIC:
   1864 	case SIOCZIFDATA:
   1865 	case SIOCSIFMTU:
   1866 	case SIOCSIFPHYADDR:
   1867 	case SIOCDIFPHYADDR:
   1868 #ifdef INET6
   1869 	case SIOCSIFPHYADDR_IN6:
   1870 #endif
   1871 	case SIOCSLIFPHYADDR:
   1872 	case SIOCADDMULTI:
   1873 	case SIOCDELMULTI:
   1874 	case SIOCSIFMEDIA:
   1875 	case SIOCSDRVSPEC:
   1876 	case SIOCG80211:
   1877 	case SIOCS80211:
   1878 	case SIOCS80211NWID:
   1879 	case SIOCS80211NWKEY:
   1880 	case SIOCS80211POWER:
   1881 	case SIOCS80211BSSID:
   1882 	case SIOCS80211CHANNEL:
   1883 	case SIOCSLINKSTR:
   1884 		if (l != NULL) {
   1885 			error = kauth_authorize_network(l->l_cred,
   1886 			    KAUTH_NETWORK_INTERFACE,
   1887 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
   1888 			    (void *)cmd, NULL);
   1889 			if (error != 0)
   1890 				return error;
   1891 		}
   1892 	}
   1893 
   1894 	oif_flags = ifp->if_flags;
   1895 
   1896 	ifnet_lock_enter(ifp->if_ioctl_lock);
   1897 	error = (*ifp->if_ioctl)(ifp, cmd, data);
   1898 	if (error != ENOTTY)
   1899 		;
   1900 	else if (so->so_proto == NULL)
   1901 		error = EOPNOTSUPP;
   1902 	else {
   1903 #ifdef COMPAT_OSOCK
   1904 		error = compat_ifioctl(so, ocmd, cmd, data, l);
   1905 #else
   1906 		error = (*so->so_proto->pr_usrreq)(so, PRU_CONTROL,
   1907 		    (struct mbuf *)cmd, (struct mbuf *)data,
   1908 		    (struct mbuf *)ifp, l);
   1909 #endif
   1910 	}
   1911 
   1912 	if (((oif_flags ^ ifp->if_flags) & IFF_UP) != 0) {
   1913 #ifdef INET6
   1914 		if (in6_present && (ifp->if_flags & IFF_UP) != 0) {
   1915 			int s = splnet();
   1916 			in6_if_up(ifp);
   1917 			splx(s);
   1918 		}
   1919 #endif
   1920 	}
   1921 #ifdef COMPAT_OIFREQ
   1922 	if (cmd != ocmd)
   1923 		ifreqn2o(oifr, ifr);
   1924 #endif
   1925 
   1926 	ifnet_lock_exit(ifp->if_ioctl_lock);
   1927 	return error;
   1928 }
   1929 
   1930 /* This callback adds to the sum in `arg' the number of
   1931  * threads on `ci' who have entered or who wait to enter the
   1932  * critical section.
   1933  */
   1934 static void
   1935 ifnet_lock_sum(void *p, void *arg, struct cpu_info *ci)
   1936 {
   1937 	uint64_t *sum = arg, *nenter = p;
   1938 
   1939 	*sum += *nenter;
   1940 }
   1941 
   1942 /* Return the number of threads who have entered or who wait
   1943  * to enter the critical section on all CPUs.
   1944  */
   1945 static uint64_t
   1946 ifnet_lock_entrances(struct ifnet_lock *il)
   1947 {
   1948 	uint64_t sum = 0;
   1949 
   1950 	percpu_foreach(il->il_nenter, ifnet_lock_sum, &sum);
   1951 
   1952 	return sum;
   1953 }
   1954 
   1955 static int
   1956 ifioctl_attach(struct ifnet *ifp)
   1957 {
   1958 	struct ifnet_lock *il;
   1959 
   1960 	/* If the driver has not supplied its own if_ioctl, then
   1961 	 * supply the default.
   1962 	 */
   1963 	if (ifp->if_ioctl == NULL)
   1964 		ifp->if_ioctl = ifioctl_common;
   1965 
   1966 	/* Create an ifnet_lock for synchronizing ifioctls. */
   1967 	if ((il = kmem_zalloc(sizeof(*il), KM_SLEEP)) == NULL)
   1968 		return ENOMEM;
   1969 
   1970 	il->il_nenter = percpu_alloc(sizeof(uint64_t));
   1971 	if (il->il_nenter == NULL) {
   1972 		kmem_free(il, sizeof(*il));
   1973 		return ENOMEM;
   1974 	}
   1975 
   1976 	mutex_init(&il->il_lock, MUTEX_DEFAULT, IPL_NONE);
   1977 	cv_init(&il->il_emptied, ifp->if_xname);
   1978 
   1979 	ifp->if_ioctl_lock = il;
   1980 
   1981 	return 0;
   1982 }
   1983 
   1984 /*
   1985  * This must not be called until after `ifp' has been withdrawn from the
   1986  * ifnet tables so that ifioctl() cannot get a handle on it by calling
   1987  * ifunit().
   1988  */
   1989 static void
   1990 ifioctl_detach(struct ifnet *ifp)
   1991 {
   1992 	struct ifnet_lock *il;
   1993 
   1994 	il = ifp->if_ioctl_lock;
   1995 	mutex_enter(&il->il_lock);
   1996 	/* Install if_nullioctl to make sure that any thread that
   1997 	 * subsequently enters the critical section will quit it
   1998 	 * immediately and signal the condition variable that we
   1999 	 * wait on, below.
   2000 	 */
   2001 	ifp->if_ioctl = if_nullioctl;
   2002 	/* Sleep while threads are still in the critical section or
   2003 	 * wait to enter it.
   2004 	 */
   2005 	while (ifnet_lock_entrances(il) != il->il_nexit)
   2006 		cv_wait(&il->il_emptied, &il->il_lock);
   2007 	/* At this point, we are the only thread still in the critical
   2008 	 * section, and no new thread can get a handle on the ifioctl
   2009 	 * lock, so it is safe to free its memory.
   2010 	 */
   2011 	mutex_exit(&il->il_lock);
   2012 	ifp->if_ioctl_lock = NULL;
   2013 	percpu_free(il->il_nenter, sizeof(uint64_t));
   2014 	il->il_nenter = NULL;
   2015 	cv_destroy(&il->il_emptied);
   2016 	mutex_destroy(&il->il_lock);
   2017 	kmem_free(il, sizeof(*il));
   2018 }
   2019 
   2020 /*
   2021  * Return interface configuration
   2022  * of system.  List may be used
   2023  * in later ioctl's (above) to get
   2024  * other information.
   2025  *
   2026  * Each record is a struct ifreq.  Before the addition of
   2027  * sockaddr_storage, the API rule was that sockaddr flavors that did
   2028  * not fit would extend beyond the struct ifreq, with the next struct
   2029  * ifreq starting sa_len beyond the struct sockaddr.  Because the
   2030  * union in struct ifreq includes struct sockaddr_storage, every kind
   2031  * of sockaddr must fit.  Thus, there are no longer any overlength
   2032  * records.
   2033  *
   2034  * Records are added to the user buffer if they fit, and ifc_len is
   2035  * adjusted to the length that was written.  Thus, the user is only
   2036  * assured of getting the complete list if ifc_len on return is at
   2037  * least sizeof(struct ifreq) less than it was on entry.
   2038  *
   2039  * If the user buffer pointer is NULL, this routine copies no data and
   2040  * returns the amount of space that would be needed.
   2041  *
   2042  * Invariants:
   2043  * ifrp points to the next part of the user's buffer to be used.  If
   2044  * ifrp != NULL, space holds the number of bytes remaining that we may
   2045  * write at ifrp.  Otherwise, space holds the number of bytes that
   2046  * would have been written had there been adequate space.
   2047  */
   2048 /*ARGSUSED*/
   2049 int
   2050 ifconf(u_long cmd, void *data)
   2051 {
   2052 	struct ifconf *ifc = (struct ifconf *)data;
   2053 	struct ifnet *ifp;
   2054 	struct ifaddr *ifa;
   2055 	struct ifreq ifr, *ifrp;
   2056 	int space, error = 0;
   2057 	const int sz = (int)sizeof(struct ifreq);
   2058 
   2059 	if ((ifrp = ifc->ifc_req) == NULL)
   2060 		space = 0;
   2061 	else
   2062 		space = ifc->ifc_len;
   2063 	IFNET_FOREACH(ifp) {
   2064 		(void)strncpy(ifr.ifr_name, ifp->if_xname,
   2065 		    sizeof(ifr.ifr_name));
   2066 		if (ifr.ifr_name[sizeof(ifr.ifr_name) - 1] != '\0')
   2067 			return ENAMETOOLONG;
   2068 		if (IFADDR_EMPTY(ifp)) {
   2069 			/* Interface with no addresses - send zero sockaddr. */
   2070 			memset(&ifr.ifr_addr, 0, sizeof(ifr.ifr_addr));
   2071 			if (ifrp == NULL) {
   2072 				space += sz;
   2073 				continue;
   2074 			}
   2075 			if (space >= sz) {
   2076 				error = copyout(&ifr, ifrp, sz);
   2077 				if (error != 0)
   2078 					return error;
   2079 				ifrp++;
   2080 				space -= sz;
   2081 			}
   2082 		}
   2083 
   2084 		IFADDR_FOREACH(ifa, ifp) {
   2085 			struct sockaddr *sa = ifa->ifa_addr;
   2086 			/* all sockaddrs must fit in sockaddr_storage */
   2087 			KASSERT(sa->sa_len <= sizeof(ifr.ifr_ifru));
   2088 
   2089 			if (ifrp == NULL) {
   2090 				space += sz;
   2091 				continue;
   2092 			}
   2093 			memcpy(&ifr.ifr_space, sa, sa->sa_len);
   2094 			if (space >= sz) {
   2095 				error = copyout(&ifr, ifrp, sz);
   2096 				if (error != 0)
   2097 					return (error);
   2098 				ifrp++; space -= sz;
   2099 			}
   2100 		}
   2101 	}
   2102 	if (ifrp != NULL) {
   2103 		KASSERT(0 <= space && space <= ifc->ifc_len);
   2104 		ifc->ifc_len -= space;
   2105 	} else {
   2106 		KASSERT(space >= 0);
   2107 		ifc->ifc_len = space;
   2108 	}
   2109 	return (0);
   2110 }
   2111 
   2112 int
   2113 ifreq_setaddr(u_long cmd, struct ifreq *ifr, const struct sockaddr *sa)
   2114 {
   2115 	uint8_t len;
   2116 #ifdef COMPAT_OIFREQ
   2117 	struct ifreq ifrb;
   2118 	struct oifreq *oifr = NULL;
   2119 	u_long ocmd = cmd;
   2120 	cmd = compat_cvtcmd(cmd);
   2121 	if (cmd != ocmd) {
   2122 		oifr = (struct oifreq *)(void *)ifr;
   2123 		ifr = &ifrb;
   2124 		ifreqo2n(oifr, ifr);
   2125 		len = sizeof(oifr->ifr_addr);
   2126 	} else
   2127 #endif
   2128 		len = sizeof(ifr->ifr_ifru.ifru_space);
   2129 
   2130 	if (len < sa->sa_len)
   2131 		return EFBIG;
   2132 
   2133 	memset(&ifr->ifr_addr, 0, len);
   2134 	sockaddr_copy(&ifr->ifr_addr, len, sa);
   2135 
   2136 #ifdef COMPAT_OIFREQ
   2137 	if (cmd != ocmd)
   2138 		ifreqn2o(oifr, ifr);
   2139 #endif
   2140 	return 0;
   2141 }
   2142 
   2143 /*
   2144  * Queue message on interface, and start output if interface
   2145  * not yet active.
   2146  */
   2147 int
   2148 ifq_enqueue(struct ifnet *ifp, struct mbuf *m
   2149     ALTQ_COMMA ALTQ_DECL(struct altq_pktattr *pktattr))
   2150 {
   2151 	int len = m->m_pkthdr.len;
   2152 	int mflags = m->m_flags;
   2153 	int s = splnet();
   2154 	int error;
   2155 
   2156 	IFQ_ENQUEUE(&ifp->if_snd, m, pktattr, error);
   2157 	if (error != 0)
   2158 		goto out;
   2159 	ifp->if_obytes += len;
   2160 	if (mflags & M_MCAST)
   2161 		ifp->if_omcasts++;
   2162 	if ((ifp->if_flags & IFF_OACTIVE) == 0)
   2163 		(*ifp->if_start)(ifp);
   2164 out:
   2165 	splx(s);
   2166 	return error;
   2167 }
   2168 
   2169 /*
   2170  * Queue message on interface, possibly using a second fast queue
   2171  */
   2172 int
   2173 ifq_enqueue2(struct ifnet *ifp, struct ifqueue *ifq, struct mbuf *m
   2174     ALTQ_COMMA ALTQ_DECL(struct altq_pktattr *pktattr))
   2175 {
   2176 	int error = 0;
   2177 
   2178 	if (ifq != NULL
   2179 #ifdef ALTQ
   2180 	    && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
   2181 #endif
   2182 	    ) {
   2183 		if (IF_QFULL(ifq)) {
   2184 			IF_DROP(&ifp->if_snd);
   2185 			m_freem(m);
   2186 			if (error == 0)
   2187 				error = ENOBUFS;
   2188 		} else
   2189 			IF_ENQUEUE(ifq, m);
   2190 	} else
   2191 		IFQ_ENQUEUE(&ifp->if_snd, m, pktattr, error);
   2192 	if (error != 0) {
   2193 		++ifp->if_oerrors;
   2194 		return error;
   2195 	}
   2196 	return 0;
   2197 }
   2198 
   2199 int
   2200 if_addr_init(ifnet_t *ifp, struct ifaddr *ifa, const bool src)
   2201 {
   2202 	int rc;
   2203 
   2204 	if (ifp->if_initaddr != NULL)
   2205 		rc = (*ifp->if_initaddr)(ifp, ifa, src);
   2206 	else if (src ||
   2207 	         (rc = (*ifp->if_ioctl)(ifp, SIOCSIFDSTADDR, ifa)) == ENOTTY)
   2208 		rc = (*ifp->if_ioctl)(ifp, SIOCINITIFADDR, ifa);
   2209 
   2210 	return rc;
   2211 }
   2212 
   2213 int
   2214 if_flags_set(ifnet_t *ifp, const short flags)
   2215 {
   2216 	int rc;
   2217 
   2218 	if (ifp->if_setflags != NULL)
   2219 		rc = (*ifp->if_setflags)(ifp, flags);
   2220 	else {
   2221 		short cantflags, chgdflags;
   2222 		struct ifreq ifr;
   2223 
   2224 		chgdflags = ifp->if_flags ^ flags;
   2225 		cantflags = chgdflags & IFF_CANTCHANGE;
   2226 
   2227 		if (cantflags != 0)
   2228 			ifp->if_flags ^= cantflags;
   2229 
   2230                 /* Traditionally, we do not call if_ioctl after
   2231                  * setting/clearing only IFF_PROMISC if the interface
   2232                  * isn't IFF_UP.  Uphold that tradition.
   2233 		 */
   2234 		if (chgdflags == IFF_PROMISC && (ifp->if_flags & IFF_UP) == 0)
   2235 			return 0;
   2236 
   2237 		memset(&ifr, 0, sizeof(ifr));
   2238 
   2239 		ifr.ifr_flags = flags & ~IFF_CANTCHANGE;
   2240 		rc = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, &ifr);
   2241 
   2242 		if (rc != 0 && cantflags != 0)
   2243 			ifp->if_flags ^= cantflags;
   2244 	}
   2245 
   2246 	return rc;
   2247 }
   2248 
   2249 int
   2250 if_mcast_op(ifnet_t *ifp, const unsigned long cmd, const struct sockaddr *sa)
   2251 {
   2252 	int rc;
   2253 	struct ifreq ifr;
   2254 
   2255 	if (ifp->if_mcastop != NULL)
   2256 		rc = (*ifp->if_mcastop)(ifp, cmd, sa);
   2257 	else {
   2258 		ifreq_setaddr(cmd, &ifr, sa);
   2259 		rc = (*ifp->if_ioctl)(ifp, cmd, &ifr);
   2260 	}
   2261 
   2262 	return rc;
   2263 }
   2264 
   2265 static void
   2266 sysctl_sndq_setup(struct sysctllog **clog, const char *ifname,
   2267     struct ifaltq *ifq)
   2268 {
   2269 	const struct sysctlnode *cnode, *rnode;
   2270 
   2271 	if (sysctl_createv(clog, 0, NULL, &rnode,
   2272 		       CTLFLAG_PERMANENT,
   2273 		       CTLTYPE_NODE, "net", NULL,
   2274 		       NULL, 0, NULL, 0,
   2275 		       CTL_NET, CTL_EOL) != 0)
   2276 		goto bad;
   2277 
   2278 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   2279 		       CTLFLAG_PERMANENT,
   2280 		       CTLTYPE_NODE, "interfaces",
   2281 		       SYSCTL_DESCR("Per-interface controls"),
   2282 		       NULL, 0, NULL, 0,
   2283 		       CTL_CREATE, CTL_EOL) != 0)
   2284 		goto bad;
   2285 
   2286 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   2287 		       CTLFLAG_PERMANENT,
   2288 		       CTLTYPE_NODE, ifname,
   2289 		       SYSCTL_DESCR("Interface controls"),
   2290 		       NULL, 0, NULL, 0,
   2291 		       CTL_CREATE, CTL_EOL) != 0)
   2292 		goto bad;
   2293 
   2294 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   2295 		       CTLFLAG_PERMANENT,
   2296 		       CTLTYPE_NODE, "sndq",
   2297 		       SYSCTL_DESCR("Interface output queue controls"),
   2298 		       NULL, 0, NULL, 0,
   2299 		       CTL_CREATE, CTL_EOL) != 0)
   2300 		goto bad;
   2301 
   2302 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   2303 		       CTLFLAG_PERMANENT,
   2304 		       CTLTYPE_INT, "len",
   2305 		       SYSCTL_DESCR("Current output queue length"),
   2306 		       NULL, 0, &ifq->ifq_len, 0,
   2307 		       CTL_CREATE, CTL_EOL) != 0)
   2308 		goto bad;
   2309 
   2310 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   2311 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2312 		       CTLTYPE_INT, "maxlen",
   2313 		       SYSCTL_DESCR("Maximum allowed output queue length"),
   2314 		       NULL, 0, &ifq->ifq_maxlen, 0,
   2315 		       CTL_CREATE, CTL_EOL) != 0)
   2316 		goto bad;
   2317 
   2318 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   2319 		       CTLFLAG_PERMANENT,
   2320 		       CTLTYPE_INT, "drops",
   2321 		       SYSCTL_DESCR("Packets dropped due to full output queue"),
   2322 		       NULL, 0, &ifq->ifq_drops, 0,
   2323 		       CTL_CREATE, CTL_EOL) != 0)
   2324 		goto bad;
   2325 
   2326 	return;
   2327 bad:
   2328 	printf("%s: could not attach sysctl nodes\n", ifname);
   2329 	return;
   2330 }
   2331 
   2332 #if defined(INET) || defined(INET6)
   2333 static void
   2334 sysctl_net_ifq_setup(struct sysctllog **clog,
   2335 		     int pf, const char *pfname,
   2336 		     int ipn, const char *ipname,
   2337 		     int qid, struct ifqueue *ifq)
   2338 {
   2339 
   2340 	sysctl_createv(clog, 0, NULL, NULL,
   2341 		       CTLFLAG_PERMANENT,
   2342 		       CTLTYPE_NODE, "net", NULL,
   2343 		       NULL, 0, NULL, 0,
   2344 		       CTL_NET, CTL_EOL);
   2345 	sysctl_createv(clog, 0, NULL, NULL,
   2346 		       CTLFLAG_PERMANENT,
   2347 		       CTLTYPE_NODE, pfname, NULL,
   2348 		       NULL, 0, NULL, 0,
   2349 		       CTL_NET, pf, CTL_EOL);
   2350 	sysctl_createv(clog, 0, NULL, NULL,
   2351 		       CTLFLAG_PERMANENT,
   2352 		       CTLTYPE_NODE, ipname, NULL,
   2353 		       NULL, 0, NULL, 0,
   2354 		       CTL_NET, pf, ipn, CTL_EOL);
   2355 	sysctl_createv(clog, 0, NULL, NULL,
   2356 		       CTLFLAG_PERMANENT,
   2357 		       CTLTYPE_NODE, "ifq",
   2358 		       SYSCTL_DESCR("Protocol input queue controls"),
   2359 		       NULL, 0, NULL, 0,
   2360 		       CTL_NET, pf, ipn, qid, CTL_EOL);
   2361 
   2362 	sysctl_createv(clog, 0, NULL, NULL,
   2363 		       CTLFLAG_PERMANENT,
   2364 		       CTLTYPE_INT, "len",
   2365 		       SYSCTL_DESCR("Current input queue length"),
   2366 		       NULL, 0, &ifq->ifq_len, 0,
   2367 		       CTL_NET, pf, ipn, qid, IFQCTL_LEN, CTL_EOL);
   2368 	sysctl_createv(clog, 0, NULL, NULL,
   2369 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2370 		       CTLTYPE_INT, "maxlen",
   2371 		       SYSCTL_DESCR("Maximum allowed input queue length"),
   2372 		       NULL, 0, &ifq->ifq_maxlen, 0,
   2373 		       CTL_NET, pf, ipn, qid, IFQCTL_MAXLEN, CTL_EOL);
   2374 #ifdef notyet
   2375 	sysctl_createv(clog, 0, NULL, NULL,
   2376 		       CTLFLAG_PERMANENT,
   2377 		       CTLTYPE_INT, "peak",
   2378 		       SYSCTL_DESCR("Highest input queue length"),
   2379 		       NULL, 0, &ifq->ifq_peak, 0,
   2380 		       CTL_NET, pf, ipn, qid, IFQCTL_PEAK, CTL_EOL);
   2381 #endif
   2382 	sysctl_createv(clog, 0, NULL, NULL,
   2383 		       CTLFLAG_PERMANENT,
   2384 		       CTLTYPE_INT, "drops",
   2385 		       SYSCTL_DESCR("Packets dropped due to full input queue"),
   2386 		       NULL, 0, &ifq->ifq_drops, 0,
   2387 		       CTL_NET, pf, ipn, qid, IFQCTL_DROPS, CTL_EOL);
   2388 }
   2389 #endif /* INET || INET6 */
   2390