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