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