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