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