Home | History | Annotate | Line # | Download | only in net
if.c revision 1.259
      1 /*	$NetBSD: if.c,v 1.259 2011/12/28 02:14:57 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.259 2011/12/28 02:14:57 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 nflags;
   1419 
   1420 	pcount = ifp->if_pcount;
   1421 	if (pswitch) {
   1422 		/*
   1423 		 * Allow the device to be "placed" into promiscuous
   1424 		 * mode even if it is not configured up.  It will
   1425 		 * consult IFF_PROMISC when it is brought up.
   1426 		 */
   1427 		if (ifp->if_pcount++ != 0)
   1428 			return 0;
   1429 		nflags = ifp->if_flags | IFF_PROMISC;
   1430 	} else {
   1431 		if (--ifp->if_pcount > 0)
   1432 			return 0;
   1433 		nflags = ifp->if_flags & ~IFF_PROMISC;
   1434 	}
   1435 	ret = if_flags_set(ifp, nflags);
   1436 	/* Restore interface state if not successful. */
   1437 	if (ret != 0) {
   1438 		ifp->if_pcount = pcount;
   1439 	}
   1440 	return ret;
   1441 }
   1442 
   1443 /*
   1444  * Map interface name to
   1445  * interface structure pointer.
   1446  */
   1447 struct ifnet *
   1448 ifunit(const char *name)
   1449 {
   1450 	struct ifnet *ifp;
   1451 	const char *cp = name;
   1452 	u_int unit = 0;
   1453 	u_int i;
   1454 
   1455 	/*
   1456 	 * If the entire name is a number, treat it as an ifindex.
   1457 	 */
   1458 	for (i = 0; i < IFNAMSIZ && *cp >= '0' && *cp <= '9'; i++, cp++) {
   1459 		unit = unit * 10 + (*cp - '0');
   1460 	}
   1461 
   1462 	/*
   1463 	 * If the number took all of the name, then it's a valid ifindex.
   1464 	 */
   1465 	if (i == IFNAMSIZ || (cp != name && *cp == '\0')) {
   1466 		if (unit >= if_indexlim)
   1467 			return NULL;
   1468 		ifp = ifindex2ifnet[unit];
   1469 		if (ifp == NULL || ifp->if_output == if_nulloutput)
   1470 			return NULL;
   1471 		return ifp;
   1472 	}
   1473 
   1474 	IFNET_FOREACH(ifp) {
   1475 		if (ifp->if_output == if_nulloutput)
   1476 			continue;
   1477 	 	if (strcmp(ifp->if_xname, name) == 0)
   1478 			return ifp;
   1479 	}
   1480 	return NULL;
   1481 }
   1482 
   1483 ifnet_t *
   1484 if_byindex(u_int idx)
   1485 {
   1486 
   1487 	return (idx < if_indexlim) ? ifindex2ifnet[idx] : NULL;
   1488 }
   1489 
   1490 /* common */
   1491 int
   1492 ifioctl_common(struct ifnet *ifp, u_long cmd, void *data)
   1493 {
   1494 	int s;
   1495 	struct ifreq *ifr;
   1496 	struct ifcapreq *ifcr;
   1497 	struct ifdatareq *ifdr;
   1498 
   1499 	switch (cmd) {
   1500 	case SIOCSIFCAP:
   1501 		ifcr = data;
   1502 		if ((ifcr->ifcr_capenable & ~ifp->if_capabilities) != 0)
   1503 			return EINVAL;
   1504 
   1505 		if (ifcr->ifcr_capenable == ifp->if_capenable)
   1506 			return 0;
   1507 
   1508 		ifp->if_capenable = ifcr->ifcr_capenable;
   1509 
   1510 		/* Pre-compute the checksum flags mask. */
   1511 		ifp->if_csum_flags_tx = 0;
   1512 		ifp->if_csum_flags_rx = 0;
   1513 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Tx) {
   1514 			ifp->if_csum_flags_tx |= M_CSUM_IPv4;
   1515 		}
   1516 		if (ifp->if_capenable & IFCAP_CSUM_IPv4_Rx) {
   1517 			ifp->if_csum_flags_rx |= M_CSUM_IPv4;
   1518 		}
   1519 
   1520 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Tx) {
   1521 			ifp->if_csum_flags_tx |= M_CSUM_TCPv4;
   1522 		}
   1523 		if (ifp->if_capenable & IFCAP_CSUM_TCPv4_Rx) {
   1524 			ifp->if_csum_flags_rx |= M_CSUM_TCPv4;
   1525 		}
   1526 
   1527 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Tx) {
   1528 			ifp->if_csum_flags_tx |= M_CSUM_UDPv4;
   1529 		}
   1530 		if (ifp->if_capenable & IFCAP_CSUM_UDPv4_Rx) {
   1531 			ifp->if_csum_flags_rx |= M_CSUM_UDPv4;
   1532 		}
   1533 
   1534 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Tx) {
   1535 			ifp->if_csum_flags_tx |= M_CSUM_TCPv6;
   1536 		}
   1537 		if (ifp->if_capenable & IFCAP_CSUM_TCPv6_Rx) {
   1538 			ifp->if_csum_flags_rx |= M_CSUM_TCPv6;
   1539 		}
   1540 
   1541 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Tx) {
   1542 			ifp->if_csum_flags_tx |= M_CSUM_UDPv6;
   1543 		}
   1544 		if (ifp->if_capenable & IFCAP_CSUM_UDPv6_Rx) {
   1545 			ifp->if_csum_flags_rx |= M_CSUM_UDPv6;
   1546 		}
   1547 		if (ifp->if_flags & IFF_UP)
   1548 			return ENETRESET;
   1549 		return 0;
   1550 	case SIOCSIFFLAGS:
   1551 		ifr = data;
   1552 		if (ifp->if_flags & IFF_UP && (ifr->ifr_flags & IFF_UP) == 0) {
   1553 			s = splnet();
   1554 			if_down(ifp);
   1555 			splx(s);
   1556 		}
   1557 		if (ifr->ifr_flags & IFF_UP && (ifp->if_flags & IFF_UP) == 0) {
   1558 			s = splnet();
   1559 			if_up(ifp);
   1560 			splx(s);
   1561 		}
   1562 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
   1563 			(ifr->ifr_flags &~ IFF_CANTCHANGE);
   1564 		break;
   1565 	case SIOCGIFFLAGS:
   1566 		ifr = data;
   1567 		ifr->ifr_flags = ifp->if_flags;
   1568 		break;
   1569 
   1570 	case SIOCGIFMETRIC:
   1571 		ifr = data;
   1572 		ifr->ifr_metric = ifp->if_metric;
   1573 		break;
   1574 
   1575 	case SIOCGIFMTU:
   1576 		ifr = data;
   1577 		ifr->ifr_mtu = ifp->if_mtu;
   1578 		break;
   1579 
   1580 	case SIOCGIFDLT:
   1581 		ifr = data;
   1582 		ifr->ifr_dlt = ifp->if_dlt;
   1583 		break;
   1584 
   1585 	case SIOCGIFCAP:
   1586 		ifcr = data;
   1587 		ifcr->ifcr_capabilities = ifp->if_capabilities;
   1588 		ifcr->ifcr_capenable = ifp->if_capenable;
   1589 		break;
   1590 
   1591 	case SIOCSIFMETRIC:
   1592 		ifr = data;
   1593 		ifp->if_metric = ifr->ifr_metric;
   1594 		break;
   1595 
   1596 	case SIOCGIFDATA:
   1597 		ifdr = data;
   1598 		ifdr->ifdr_data = ifp->if_data;
   1599 		break;
   1600 
   1601 	case SIOCZIFDATA:
   1602 		ifdr = data;
   1603 		ifdr->ifdr_data = ifp->if_data;
   1604 		/*
   1605 		 * Assumes that the volatile counters that can be
   1606 		 * zero'ed are at the end of if_data.
   1607 		 */
   1608 		memset(&ifp->if_data.ifi_ipackets, 0, sizeof(ifp->if_data) -
   1609 		    offsetof(struct if_data, ifi_ipackets));
   1610 		break;
   1611 	case SIOCSIFMTU:
   1612 		ifr = data;
   1613 		if (ifp->if_mtu == ifr->ifr_mtu)
   1614 			break;
   1615 		ifp->if_mtu = ifr->ifr_mtu;
   1616 		/*
   1617 		 * If the link MTU changed, do network layer specific procedure.
   1618 		 */
   1619 #ifdef INET6
   1620 		nd6_setmtu(ifp);
   1621 #endif
   1622 		return ENETRESET;
   1623 	default:
   1624 		return ENOTTY;
   1625 	}
   1626 	return 0;
   1627 }
   1628 
   1629 int
   1630 ifaddrpref_ioctl(struct socket *so, u_long cmd, void *data, struct ifnet *ifp,
   1631     lwp_t *l)
   1632 {
   1633 	struct if_addrprefreq *ifap = (struct if_addrprefreq *)data;
   1634 	struct ifaddr *ifa;
   1635 	const struct sockaddr *any, *sa;
   1636 	union {
   1637 		struct sockaddr sa;
   1638 		struct sockaddr_storage ss;
   1639 	} u, v;
   1640 
   1641 	switch (cmd) {
   1642 	case SIOCSIFADDRPREF:
   1643 		if (kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
   1644 		    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp, (void *)cmd,
   1645 		    NULL) != 0)
   1646 			return EPERM;
   1647 	case SIOCGIFADDRPREF:
   1648 		break;
   1649 	default:
   1650 		return EOPNOTSUPP;
   1651 	}
   1652 
   1653 	/* sanity checks */
   1654 	if (data == NULL || ifp == NULL) {
   1655 		panic("invalid argument to %s", __func__);
   1656 		/*NOTREACHED*/
   1657 	}
   1658 
   1659 	/* address must be specified on ADD and DELETE */
   1660 	sa = sstocsa(&ifap->ifap_addr);
   1661 	if (sa->sa_family != sofamily(so))
   1662 		return EINVAL;
   1663 	if ((any = sockaddr_any(sa)) == NULL || sa->sa_len != any->sa_len)
   1664 		return EINVAL;
   1665 
   1666 	sockaddr_externalize(&v.sa, sizeof(v.ss), sa);
   1667 
   1668 	IFADDR_FOREACH(ifa, ifp) {
   1669 		if (ifa->ifa_addr->sa_family != sa->sa_family)
   1670 			continue;
   1671 		sockaddr_externalize(&u.sa, sizeof(u.ss), ifa->ifa_addr);
   1672 		if (sockaddr_cmp(&u.sa, &v.sa) == 0)
   1673 			break;
   1674 	}
   1675 	if (ifa == NULL)
   1676 		return EADDRNOTAVAIL;
   1677 
   1678 	switch (cmd) {
   1679 	case SIOCSIFADDRPREF:
   1680 		ifa->ifa_preference = ifap->ifap_preference;
   1681 		return 0;
   1682 	case SIOCGIFADDRPREF:
   1683 		/* fill in the if_laddrreq structure */
   1684 		(void)sockaddr_copy(sstosa(&ifap->ifap_addr),
   1685 		    sizeof(ifap->ifap_addr), ifa->ifa_addr);
   1686 		ifap->ifap_preference = ifa->ifa_preference;
   1687 		return 0;
   1688 	default:
   1689 		return EOPNOTSUPP;
   1690 	}
   1691 }
   1692 
   1693 static void
   1694 ifnet_lock_enter(struct ifnet_lock *il)
   1695 {
   1696 	uint64_t *nenter;
   1697 
   1698 	/* Before trying to acquire the mutex, increase the count of threads
   1699 	 * who have entered or who wait to enter the critical section.
   1700 	 * Avoid one costly locked memory transaction by keeping a count for
   1701 	 * each CPU.
   1702 	 */
   1703 	nenter = percpu_getref(il->il_nenter);
   1704 	(*nenter)++;
   1705 	percpu_putref(il->il_nenter);
   1706 	mutex_enter(&il->il_lock);
   1707 }
   1708 
   1709 static void
   1710 ifnet_lock_exit(struct ifnet_lock *il)
   1711 {
   1712 	/* Increase the count of threads who have exited the critical
   1713 	 * section.  Increase while we still hold the lock.
   1714 	 */
   1715 	il->il_nexit++;
   1716 	mutex_exit(&il->il_lock);
   1717 }
   1718 
   1719 /*
   1720  * Interface ioctls.
   1721  */
   1722 int
   1723 ifioctl(struct socket *so, u_long cmd, void *data, struct lwp *l)
   1724 {
   1725 	struct ifnet *ifp;
   1726 	struct ifreq *ifr;
   1727 	int error = 0;
   1728 #if defined(COMPAT_OSOCK) || defined(COMPAT_OIFREQ)
   1729 	u_long ocmd = cmd;
   1730 #endif
   1731 	short oif_flags;
   1732 #ifdef COMPAT_OIFREQ
   1733 	struct ifreq ifrb;
   1734 	struct oifreq *oifr = NULL;
   1735 #endif
   1736 
   1737 	switch (cmd) {
   1738 #ifdef COMPAT_OIFREQ
   1739 	case OSIOCGIFCONF:
   1740 	case OOSIOCGIFCONF:
   1741 		return compat_ifconf(cmd, data);
   1742 #endif
   1743 #ifdef COMPAT_OIFDATA
   1744 	case OSIOCGIFDATA:
   1745 	case OSIOCZIFDATA:
   1746 		return compat_ifdatareq(l, cmd, data);
   1747 #endif
   1748 	case SIOCGIFCONF:
   1749 		return ifconf(cmd, data);
   1750 	case SIOCINITIFADDR:
   1751 		return EPERM;
   1752 	}
   1753 
   1754 #ifdef COMPAT_OIFREQ
   1755 	cmd = compat_cvtcmd(cmd);
   1756 	if (cmd != ocmd) {
   1757 		oifr = data;
   1758 		data = ifr = &ifrb;
   1759 		ifreqo2n(oifr, ifr);
   1760 	} else
   1761 #endif
   1762 		ifr = data;
   1763 
   1764 	ifp = ifunit(ifr->ifr_name);
   1765 
   1766 	switch (cmd) {
   1767 	case SIOCIFCREATE:
   1768 	case SIOCIFDESTROY:
   1769 		if (l != NULL) {
   1770 			error = kauth_authorize_network(l->l_cred,
   1771 			    KAUTH_NETWORK_INTERFACE,
   1772 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
   1773 			    (void *)cmd, NULL);
   1774 			if (error != 0)
   1775 				return error;
   1776 		}
   1777 		return (cmd == SIOCIFCREATE) ?
   1778 			if_clone_create(ifr->ifr_name) :
   1779 			if_clone_destroy(ifr->ifr_name);
   1780 
   1781 	case SIOCIFGCLONERS:
   1782 		return if_clone_list((struct if_clonereq *)data);
   1783 	}
   1784 
   1785 	if (ifp == NULL)
   1786 		return ENXIO;
   1787 
   1788 	switch (cmd) {
   1789 	case SIOCALIFADDR:
   1790 	case SIOCDLIFADDR:
   1791 	case SIOCSIFADDRPREF:
   1792 	case SIOCSIFFLAGS:
   1793 	case SIOCSIFCAP:
   1794 	case SIOCSIFMETRIC:
   1795 	case SIOCZIFDATA:
   1796 	case SIOCSIFMTU:
   1797 	case SIOCSIFPHYADDR:
   1798 	case SIOCDIFPHYADDR:
   1799 #ifdef INET6
   1800 	case SIOCSIFPHYADDR_IN6:
   1801 #endif
   1802 	case SIOCSLIFPHYADDR:
   1803 	case SIOCADDMULTI:
   1804 	case SIOCDELMULTI:
   1805 	case SIOCSIFMEDIA:
   1806 	case SIOCSDRVSPEC:
   1807 	case SIOCG80211:
   1808 	case SIOCS80211:
   1809 	case SIOCS80211NWID:
   1810 	case SIOCS80211NWKEY:
   1811 	case SIOCS80211POWER:
   1812 	case SIOCS80211BSSID:
   1813 	case SIOCS80211CHANNEL:
   1814 	case SIOCSLINKSTR:
   1815 		if (l != NULL) {
   1816 			error = kauth_authorize_network(l->l_cred,
   1817 			    KAUTH_NETWORK_INTERFACE,
   1818 			    KAUTH_REQ_NETWORK_INTERFACE_SETPRIV, ifp,
   1819 			    (void *)cmd, NULL);
   1820 			if (error != 0)
   1821 				return error;
   1822 		}
   1823 	}
   1824 
   1825 	oif_flags = ifp->if_flags;
   1826 
   1827 	ifnet_lock_enter(ifp->if_ioctl_lock);
   1828 	error = (*ifp->if_ioctl)(ifp, cmd, data);
   1829 	if (error != ENOTTY)
   1830 		;
   1831 	else if (so->so_proto == NULL)
   1832 		error = EOPNOTSUPP;
   1833 	else {
   1834 #ifdef COMPAT_OSOCK
   1835 		error = compat_ifioctl(so, ocmd, cmd, data, l);
   1836 #else
   1837 		error = (*so->so_proto->pr_usrreq)(so, PRU_CONTROL,
   1838 		    (struct mbuf *)cmd, (struct mbuf *)data,
   1839 		    (struct mbuf *)ifp, l);
   1840 #endif
   1841 	}
   1842 
   1843 	if (((oif_flags ^ ifp->if_flags) & IFF_UP) != 0) {
   1844 #ifdef INET6
   1845 		if ((ifp->if_flags & IFF_UP) != 0) {
   1846 			int s = splnet();
   1847 			in6_if_up(ifp);
   1848 			splx(s);
   1849 		}
   1850 #endif
   1851 	}
   1852 #ifdef COMPAT_OIFREQ
   1853 	if (cmd != ocmd)
   1854 		ifreqn2o(oifr, ifr);
   1855 #endif
   1856 
   1857 	ifnet_lock_exit(ifp->if_ioctl_lock);
   1858 	return error;
   1859 }
   1860 
   1861 /* This callback adds to the sum in `arg' the number of
   1862  * threads on `ci' who have entered or who wait to enter the
   1863  * critical section.
   1864  */
   1865 static void
   1866 ifnet_lock_sum(void *p, void *arg, struct cpu_info *ci)
   1867 {
   1868 	uint64_t *sum = arg, *nenter = p;
   1869 
   1870 	*sum += *nenter;
   1871 }
   1872 
   1873 /* Return the number of threads who have entered or who wait
   1874  * to enter the critical section on all CPUs.
   1875  */
   1876 static uint64_t
   1877 ifnet_lock_entrances(struct ifnet_lock *il)
   1878 {
   1879 	uint64_t sum = 0;
   1880 
   1881 	percpu_foreach(il->il_nenter, ifnet_lock_sum, &sum);
   1882 
   1883 	return sum;
   1884 }
   1885 
   1886 static int
   1887 ifioctl_attach(struct ifnet *ifp)
   1888 {
   1889 	struct ifnet_lock *il;
   1890 
   1891 	/* If the driver has not supplied its own if_ioctl, then
   1892 	 * supply the default.
   1893 	 */
   1894 	if (ifp->if_ioctl == NULL)
   1895 		ifp->if_ioctl = ifioctl_common;
   1896 
   1897 	/* Create an ifnet_lock for synchronizing ifioctls. */
   1898 	if ((il = kmem_zalloc(sizeof(*il), KM_SLEEP)) == NULL)
   1899 		return ENOMEM;
   1900 
   1901 	il->il_nenter = percpu_alloc(sizeof(uint64_t));
   1902 	if (il->il_nenter == NULL) {
   1903 		kmem_free(il, sizeof(*il));
   1904 		return ENOMEM;
   1905 	}
   1906 
   1907 	mutex_init(&il->il_lock, MUTEX_DEFAULT, IPL_NONE);
   1908 	cv_init(&il->il_emptied, ifp->if_xname);
   1909 
   1910 	ifp->if_ioctl_lock = il;
   1911 
   1912 	return 0;
   1913 }
   1914 
   1915 /*
   1916  * This must not be called until after `ifp' has been withdrawn from the
   1917  * ifnet tables so that ifioctl() cannot get a handle on it by calling
   1918  * ifunit().
   1919  */
   1920 static void
   1921 ifioctl_detach(struct ifnet *ifp)
   1922 {
   1923 	struct ifnet_lock *il;
   1924 
   1925 	il = ifp->if_ioctl_lock;
   1926 	mutex_enter(&il->il_lock);
   1927 	/* Install if_nullioctl to make sure that any thread that
   1928 	 * subsequently enters the critical section will quit it
   1929 	 * immediately and signal the condition variable that we
   1930 	 * wait on, below.
   1931 	 */
   1932 	ifp->if_ioctl = if_nullioctl;
   1933 	/* Sleep while threads are still in the critical section or
   1934 	 * wait to enter it.
   1935 	 */
   1936 	while (ifnet_lock_entrances(il) != il->il_nexit)
   1937 		cv_wait(&il->il_emptied, &il->il_lock);
   1938 	/* At this point, we are the only thread still in the critical
   1939 	 * section, and no new thread can get a handle on the ifioctl
   1940 	 * lock, so it is safe to free its memory.
   1941 	 */
   1942 	mutex_exit(&il->il_lock);
   1943 	ifp->if_ioctl_lock = NULL;
   1944 	percpu_free(il->il_nenter, sizeof(uint64_t));
   1945 	il->il_nenter = NULL;
   1946 	cv_destroy(&il->il_emptied);
   1947 	mutex_destroy(&il->il_lock);
   1948 	kmem_free(il, sizeof(*il));
   1949 }
   1950 
   1951 /*
   1952  * Return interface configuration
   1953  * of system.  List may be used
   1954  * in later ioctl's (above) to get
   1955  * other information.
   1956  *
   1957  * Each record is a struct ifreq.  Before the addition of
   1958  * sockaddr_storage, the API rule was that sockaddr flavors that did
   1959  * not fit would extend beyond the struct ifreq, with the next struct
   1960  * ifreq starting sa_len beyond the struct sockaddr.  Because the
   1961  * union in struct ifreq includes struct sockaddr_storage, every kind
   1962  * of sockaddr must fit.  Thus, there are no longer any overlength
   1963  * records.
   1964  *
   1965  * Records are added to the user buffer if they fit, and ifc_len is
   1966  * adjusted to the length that was written.  Thus, the user is only
   1967  * assured of getting the complete list if ifc_len on return is at
   1968  * least sizeof(struct ifreq) less than it was on entry.
   1969  *
   1970  * If the user buffer pointer is NULL, this routine copies no data and
   1971  * returns the amount of space that would be needed.
   1972  *
   1973  * Invariants:
   1974  * ifrp points to the next part of the user's buffer to be used.  If
   1975  * ifrp != NULL, space holds the number of bytes remaining that we may
   1976  * write at ifrp.  Otherwise, space holds the number of bytes that
   1977  * would have been written had there been adequate space.
   1978  */
   1979 /*ARGSUSED*/
   1980 int
   1981 ifconf(u_long cmd, void *data)
   1982 {
   1983 	struct ifconf *ifc = (struct ifconf *)data;
   1984 	struct ifnet *ifp;
   1985 	struct ifaddr *ifa;
   1986 	struct ifreq ifr, *ifrp;
   1987 	int space, error = 0;
   1988 	const int sz = (int)sizeof(struct ifreq);
   1989 
   1990 	if ((ifrp = ifc->ifc_req) == NULL)
   1991 		space = 0;
   1992 	else
   1993 		space = ifc->ifc_len;
   1994 	IFNET_FOREACH(ifp) {
   1995 		(void)strncpy(ifr.ifr_name, ifp->if_xname,
   1996 		    sizeof(ifr.ifr_name));
   1997 		if (ifr.ifr_name[sizeof(ifr.ifr_name) - 1] != '\0')
   1998 			return ENAMETOOLONG;
   1999 		if (IFADDR_EMPTY(ifp)) {
   2000 			/* Interface with no addresses - send zero sockaddr. */
   2001 			memset(&ifr.ifr_addr, 0, sizeof(ifr.ifr_addr));
   2002 			if (ifrp == NULL) {
   2003 				space += sz;
   2004 				continue;
   2005 			}
   2006 			if (space >= sz) {
   2007 				error = copyout(&ifr, ifrp, sz);
   2008 				if (error != 0)
   2009 					return error;
   2010 				ifrp++;
   2011 				space -= sz;
   2012 			}
   2013 		}
   2014 
   2015 		IFADDR_FOREACH(ifa, ifp) {
   2016 			struct sockaddr *sa = ifa->ifa_addr;
   2017 			/* all sockaddrs must fit in sockaddr_storage */
   2018 			KASSERT(sa->sa_len <= sizeof(ifr.ifr_ifru));
   2019 
   2020 			if (ifrp == NULL) {
   2021 				space += sz;
   2022 				continue;
   2023 			}
   2024 			memcpy(&ifr.ifr_space, sa, sa->sa_len);
   2025 			if (space >= sz) {
   2026 				error = copyout(&ifr, ifrp, sz);
   2027 				if (error != 0)
   2028 					return (error);
   2029 				ifrp++; space -= sz;
   2030 			}
   2031 		}
   2032 	}
   2033 	if (ifrp != NULL) {
   2034 		KASSERT(0 <= space && space <= ifc->ifc_len);
   2035 		ifc->ifc_len -= space;
   2036 	} else {
   2037 		KASSERT(space >= 0);
   2038 		ifc->ifc_len = space;
   2039 	}
   2040 	return (0);
   2041 }
   2042 
   2043 int
   2044 ifreq_setaddr(u_long cmd, struct ifreq *ifr, const struct sockaddr *sa)
   2045 {
   2046 	uint8_t len;
   2047 #ifdef COMPAT_OIFREQ
   2048 	struct ifreq ifrb;
   2049 	struct oifreq *oifr = NULL;
   2050 	u_long ocmd = cmd;
   2051 	cmd = compat_cvtcmd(cmd);
   2052 	if (cmd != ocmd) {
   2053 		oifr = (struct oifreq *)(void *)ifr;
   2054 		ifr = &ifrb;
   2055 		ifreqo2n(oifr, ifr);
   2056 		len = sizeof(oifr->ifr_addr);
   2057 	} else
   2058 #endif
   2059 		len = sizeof(ifr->ifr_ifru.ifru_space);
   2060 
   2061 	if (len < sa->sa_len)
   2062 		return EFBIG;
   2063 
   2064 	memset(&ifr->ifr_addr, 0, len);
   2065 	sockaddr_copy(&ifr->ifr_addr, len, sa);
   2066 
   2067 #ifdef COMPAT_OIFREQ
   2068 	if (cmd != ocmd)
   2069 		ifreqn2o(oifr, ifr);
   2070 #endif
   2071 	return 0;
   2072 }
   2073 
   2074 /*
   2075  * Queue message on interface, and start output if interface
   2076  * not yet active.
   2077  */
   2078 int
   2079 ifq_enqueue(struct ifnet *ifp, struct mbuf *m
   2080     ALTQ_COMMA ALTQ_DECL(struct altq_pktattr *pktattr))
   2081 {
   2082 	int len = m->m_pkthdr.len;
   2083 	int mflags = m->m_flags;
   2084 	int s = splnet();
   2085 	int error;
   2086 
   2087 	IFQ_ENQUEUE(&ifp->if_snd, m, pktattr, error);
   2088 	if (error != 0)
   2089 		goto out;
   2090 	ifp->if_obytes += len;
   2091 	if (mflags & M_MCAST)
   2092 		ifp->if_omcasts++;
   2093 	if ((ifp->if_flags & IFF_OACTIVE) == 0)
   2094 		(*ifp->if_start)(ifp);
   2095 out:
   2096 	splx(s);
   2097 	return error;
   2098 }
   2099 
   2100 /*
   2101  * Queue message on interface, possibly using a second fast queue
   2102  */
   2103 int
   2104 ifq_enqueue2(struct ifnet *ifp, struct ifqueue *ifq, struct mbuf *m
   2105     ALTQ_COMMA ALTQ_DECL(struct altq_pktattr *pktattr))
   2106 {
   2107 	int error = 0;
   2108 
   2109 	if (ifq != NULL
   2110 #ifdef ALTQ
   2111 	    && ALTQ_IS_ENABLED(&ifp->if_snd) == 0
   2112 #endif
   2113 	    ) {
   2114 		if (IF_QFULL(ifq)) {
   2115 			IF_DROP(&ifp->if_snd);
   2116 			m_freem(m);
   2117 			if (error == 0)
   2118 				error = ENOBUFS;
   2119 		} else
   2120 			IF_ENQUEUE(ifq, m);
   2121 	} else
   2122 		IFQ_ENQUEUE(&ifp->if_snd, m, pktattr, error);
   2123 	if (error != 0) {
   2124 		++ifp->if_oerrors;
   2125 		return error;
   2126 	}
   2127 	return 0;
   2128 }
   2129 
   2130 int
   2131 if_addr_init(ifnet_t *ifp, struct ifaddr *ifa, const bool src)
   2132 {
   2133 	int rc;
   2134 
   2135 	if (ifp->if_initaddr != NULL)
   2136 		rc = (*ifp->if_initaddr)(ifp, ifa, src);
   2137 	else if (src ||
   2138 	         (rc = (*ifp->if_ioctl)(ifp, SIOCSIFDSTADDR, ifa)) == ENOTTY)
   2139 		rc = (*ifp->if_ioctl)(ifp, SIOCINITIFADDR, ifa);
   2140 
   2141 	return rc;
   2142 }
   2143 
   2144 int
   2145 if_flags_set(ifnet_t *ifp, const short flags)
   2146 {
   2147 	int rc;
   2148 
   2149 	if (ifp->if_setflags != NULL)
   2150 		rc = (*ifp->if_setflags)(ifp, flags);
   2151 	else {
   2152 		short cantflags, chgdflags;
   2153 		struct ifreq ifr;
   2154 
   2155 		chgdflags = ifp->if_flags ^ flags;
   2156 		cantflags = chgdflags & IFF_CANTCHANGE;
   2157 
   2158 		if (cantflags != 0)
   2159 			ifp->if_flags ^= cantflags;
   2160 
   2161                 /* Traditionally, we do not call if_ioctl after
   2162                  * setting/clearing only IFF_PROMISC if the interface
   2163                  * isn't IFF_UP.  Uphold that tradition.
   2164 		 */
   2165 		if (chgdflags == IFF_PROMISC && (ifp->if_flags & IFF_UP) == 0)
   2166 			return 0;
   2167 
   2168 		memset(&ifr, 0, sizeof(ifr));
   2169 
   2170 		ifr.ifr_flags = flags & ~IFF_CANTCHANGE;
   2171 		rc = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, &ifr);
   2172 
   2173 		if (rc != 0 && cantflags != 0)
   2174 			ifp->if_flags ^= cantflags;
   2175 	}
   2176 
   2177 	return rc;
   2178 }
   2179 
   2180 int
   2181 if_mcast_op(ifnet_t *ifp, const unsigned long cmd, const struct sockaddr *sa)
   2182 {
   2183 	int rc;
   2184 	struct ifreq ifr;
   2185 
   2186 	if (ifp->if_mcastop != NULL)
   2187 		rc = (*ifp->if_mcastop)(ifp, cmd, sa);
   2188 	else {
   2189 		ifreq_setaddr(cmd, &ifr, sa);
   2190 		rc = (*ifp->if_ioctl)(ifp, cmd, &ifr);
   2191 	}
   2192 
   2193 	return rc;
   2194 }
   2195 
   2196 static void
   2197 sysctl_sndq_setup(struct sysctllog **clog, const char *ifname,
   2198     struct ifaltq *ifq)
   2199 {
   2200 	const struct sysctlnode *cnode, *rnode;
   2201 
   2202 	if (sysctl_createv(clog, 0, NULL, &rnode,
   2203 		       CTLFLAG_PERMANENT,
   2204 		       CTLTYPE_NODE, "net", NULL,
   2205 		       NULL, 0, NULL, 0,
   2206 		       CTL_NET, CTL_EOL) != 0)
   2207 		goto bad;
   2208 
   2209 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   2210 		       CTLFLAG_PERMANENT,
   2211 		       CTLTYPE_NODE, "interfaces",
   2212 		       SYSCTL_DESCR("Per-interface controls"),
   2213 		       NULL, 0, NULL, 0,
   2214 		       CTL_CREATE, CTL_EOL) != 0)
   2215 		goto bad;
   2216 
   2217 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   2218 		       CTLFLAG_PERMANENT,
   2219 		       CTLTYPE_NODE, ifname,
   2220 		       SYSCTL_DESCR("Interface controls"),
   2221 		       NULL, 0, NULL, 0,
   2222 		       CTL_CREATE, CTL_EOL) != 0)
   2223 		goto bad;
   2224 
   2225 	if (sysctl_createv(clog, 0, &rnode, &rnode,
   2226 		       CTLFLAG_PERMANENT,
   2227 		       CTLTYPE_NODE, "sndq",
   2228 		       SYSCTL_DESCR("Interface output queue controls"),
   2229 		       NULL, 0, NULL, 0,
   2230 		       CTL_CREATE, CTL_EOL) != 0)
   2231 		goto bad;
   2232 
   2233 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   2234 		       CTLFLAG_PERMANENT,
   2235 		       CTLTYPE_INT, "len",
   2236 		       SYSCTL_DESCR("Current output queue length"),
   2237 		       NULL, 0, &ifq->ifq_len, 0,
   2238 		       CTL_CREATE, CTL_EOL) != 0)
   2239 		goto bad;
   2240 
   2241 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   2242 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2243 		       CTLTYPE_INT, "maxlen",
   2244 		       SYSCTL_DESCR("Maximum allowed output queue length"),
   2245 		       NULL, 0, &ifq->ifq_maxlen, 0,
   2246 		       CTL_CREATE, CTL_EOL) != 0)
   2247 		goto bad;
   2248 
   2249 	if (sysctl_createv(clog, 0, &rnode, &cnode,
   2250 		       CTLFLAG_PERMANENT,
   2251 		       CTLTYPE_INT, "drops",
   2252 		       SYSCTL_DESCR("Packets dropped due to full output queue"),
   2253 		       NULL, 0, &ifq->ifq_drops, 0,
   2254 		       CTL_CREATE, CTL_EOL) != 0)
   2255 		goto bad;
   2256 
   2257 	return;
   2258 bad:
   2259 	printf("%s: could not attach sysctl nodes\n", ifname);
   2260 	return;
   2261 }
   2262 
   2263 #if defined(INET) || defined(INET6)
   2264 static void
   2265 sysctl_net_ifq_setup(struct sysctllog **clog,
   2266 		     int pf, const char *pfname,
   2267 		     int ipn, const char *ipname,
   2268 		     int qid, struct ifqueue *ifq)
   2269 {
   2270 
   2271 	sysctl_createv(clog, 0, NULL, NULL,
   2272 		       CTLFLAG_PERMANENT,
   2273 		       CTLTYPE_NODE, "net", NULL,
   2274 		       NULL, 0, NULL, 0,
   2275 		       CTL_NET, CTL_EOL);
   2276 	sysctl_createv(clog, 0, NULL, NULL,
   2277 		       CTLFLAG_PERMANENT,
   2278 		       CTLTYPE_NODE, pfname, NULL,
   2279 		       NULL, 0, NULL, 0,
   2280 		       CTL_NET, pf, CTL_EOL);
   2281 	sysctl_createv(clog, 0, NULL, NULL,
   2282 		       CTLFLAG_PERMANENT,
   2283 		       CTLTYPE_NODE, ipname, NULL,
   2284 		       NULL, 0, NULL, 0,
   2285 		       CTL_NET, pf, ipn, CTL_EOL);
   2286 	sysctl_createv(clog, 0, NULL, NULL,
   2287 		       CTLFLAG_PERMANENT,
   2288 		       CTLTYPE_NODE, "ifq",
   2289 		       SYSCTL_DESCR("Protocol input queue controls"),
   2290 		       NULL, 0, NULL, 0,
   2291 		       CTL_NET, pf, ipn, qid, CTL_EOL);
   2292 
   2293 	sysctl_createv(clog, 0, NULL, NULL,
   2294 		       CTLFLAG_PERMANENT,
   2295 		       CTLTYPE_INT, "len",
   2296 		       SYSCTL_DESCR("Current input queue length"),
   2297 		       NULL, 0, &ifq->ifq_len, 0,
   2298 		       CTL_NET, pf, ipn, qid, IFQCTL_LEN, CTL_EOL);
   2299 	sysctl_createv(clog, 0, NULL, NULL,
   2300 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2301 		       CTLTYPE_INT, "maxlen",
   2302 		       SYSCTL_DESCR("Maximum allowed input queue length"),
   2303 		       NULL, 0, &ifq->ifq_maxlen, 0,
   2304 		       CTL_NET, pf, ipn, qid, IFQCTL_MAXLEN, CTL_EOL);
   2305 #ifdef notyet
   2306 	sysctl_createv(clog, 0, NULL, NULL,
   2307 		       CTLFLAG_PERMANENT,
   2308 		       CTLTYPE_INT, "peak",
   2309 		       SYSCTL_DESCR("Highest input queue length"),
   2310 		       NULL, 0, &ifq->ifq_peak, 0,
   2311 		       CTL_NET, pf, ipn, qid, IFQCTL_PEAK, CTL_EOL);
   2312 #endif
   2313 	sysctl_createv(clog, 0, NULL, NULL,
   2314 		       CTLFLAG_PERMANENT,
   2315 		       CTLTYPE_INT, "drops",
   2316 		       SYSCTL_DESCR("Packets dropped due to full input queue"),
   2317 		       NULL, 0, &ifq->ifq_drops, 0,
   2318 		       CTL_NET, pf, ipn, qid, IFQCTL_DROPS, CTL_EOL);
   2319 }
   2320 #endif /* INET || INET6 */
   2321