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