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