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