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